var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key, result);
  return result;
};
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);

// community-modules/core/src/main.ts
var main_exports = {};
__export(main_exports, {
  ALWAYS_SYNC_GLOBAL_EVENTS: () => ALWAYS_SYNC_GLOBAL_EVENTS,
  AbstractHeaderCellCtrl: () => AbstractHeaderCellCtrl,
  AgAbstractField: () => AgAbstractField,
  AgAbstractLabel: () => AgAbstractLabel,
  AgAutocomplete: () => AgAutocomplete,
  AgCheckbox: () => AgCheckbox,
  AgDialog: () => AgDialog,
  AgGroupComponent: () => AgGroupComponent,
  AgInputDateField: () => AgInputDateField,
  AgInputNumberField: () => AgInputNumberField,
  AgInputRange: () => AgInputRange,
  AgInputTextArea: () => AgInputTextArea,
  AgInputTextField: () => AgInputTextField,
  AgMenuItemComponent: () => AgMenuItemComponent,
  AgMenuItemRenderer: () => AgMenuItemRenderer,
  AgMenuList: () => AgMenuList,
  AgMenuPanel: () => AgMenuPanel,
  AgPanel: () => AgPanel,
  AgPickerField: () => AgPickerField,
  AgPromise: () => AgPromise,
  AgPromiseStatus: () => AgPromiseStatus,
  AgRadioButton: () => AgRadioButton,
  AgRichSelect: () => AgRichSelect,
  AgSelect: () => AgSelect,
  AgSlider: () => AgSlider,
  AgStackComponentsRegistry: () => AgStackComponentsRegistry,
  AgToggleButton: () => AgToggleButton,
  AlignedGridsService: () => AlignedGridsService,
  AnimateShowChangeCellRenderer: () => AnimateShowChangeCellRenderer,
  AnimateSlideCellRenderer: () => AnimateSlideCellRenderer,
  AnimationFrameService: () => AnimationFrameService,
  AutoScrollService: () => AutoScrollService,
  AutoWidthCalculator: () => AutoWidthCalculator,
  Autowired: () => Autowired,
  BarColumnLabelPlacement: () => BarColumnLabelPlacement,
  BaseComponentWrapper: () => BaseComponentWrapper,
  Bean: () => Bean,
  BeanStub: () => BeanStub,
  Beans: () => Beans,
  BodyDropPivotTarget: () => BodyDropPivotTarget,
  BodyDropTarget: () => BodyDropTarget,
  CellComp: () => CellComp,
  CellCtrl: () => CellCtrl,
  CellNavigationService: () => CellNavigationService,
  CellPositionUtils: () => CellPositionUtils,
  CellRangeType: () => CellRangeType,
  ChangedPath: () => ChangedPath,
  ChartMappings: () => ChartMappings,
  CheckboxCellEditor: () => CheckboxCellEditor,
  CheckboxCellRenderer: () => CheckboxCellRenderer,
  CheckboxSelectionComponent: () => CheckboxSelectionComponent,
  ClientSideRowModelSteps: () => ClientSideRowModelSteps,
  Column: () => Column,
  ColumnApi: () => ColumnApi,
  ColumnFactory: () => ColumnFactory,
  ColumnGroup: () => ColumnGroup,
  ColumnKeyCreator: () => ColumnKeyCreator,
  ColumnModel: () => ColumnModel,
  Component: () => Component,
  ComponentUtil: () => ComponentUtil,
  Context: () => Context,
  CssClassApplier: () => CssClassApplier,
  CssClassManager: () => CssClassManager,
  CtrlsService: () => CtrlsService,
  DataTypeService: () => DataTypeService,
  DateCellEditor: () => DateCellEditor,
  DateFilter: () => DateFilter,
  DateStringCellEditor: () => DateStringCellEditor,
  DisplayedGroupCreator: () => DisplayedGroupCreator,
  DragAndDropService: () => DragAndDropService,
  DragService: () => DragService,
  DragSourceType: () => DragSourceType,
  Environment: () => Environment,
  EventService: () => EventService,
  Events: () => Events,
  ExcelFactoryMode: () => ExcelFactoryMode,
  ExpansionService: () => ExpansionService,
  ExpressionService: () => ExpressionService,
  FilterManager: () => FilterManager,
  FilterWrapperComp: () => FilterWrapperComp,
  FloatingFilterMapper: () => FloatingFilterMapper,
  FocusService: () => FocusService,
  GROUP_AUTO_COLUMN_ID: () => GROUP_AUTO_COLUMN_ID,
  Grid: () => Grid,
  GridApi: () => GridApi,
  GridBodyComp: () => GridBodyComp,
  GridBodyCtrl: () => GridBodyCtrl,
  GridComp: () => GridComp,
  GridCoreCreator: () => GridCoreCreator,
  GridCtrl: () => GridCtrl,
  GridHeaderComp: () => GridHeaderComp,
  GridHeaderCtrl: () => GridHeaderCtrl,
  GridOptionsService: () => GridOptionsService,
  GroupCellRenderer: () => GroupCellRenderer,
  GroupCellRendererCtrl: () => GroupCellRendererCtrl,
  GroupInstanceIdCreator: () => GroupInstanceIdCreator,
  HeaderCellCtrl: () => HeaderCellCtrl,
  HeaderFilterCellComp: () => HeaderFilterCellComp,
  HeaderFilterCellCtrl: () => HeaderFilterCellCtrl,
  HeaderGroupCellCtrl: () => HeaderGroupCellCtrl,
  HeaderNavigationDirection: () => HeaderNavigationDirection,
  HeaderNavigationService: () => HeaderNavigationService,
  HeaderPositionUtils: () => HeaderPositionUtils,
  HeaderRowComp: () => HeaderRowComp,
  HeaderRowContainerComp: () => HeaderRowContainerComp,
  HeaderRowContainerCtrl: () => HeaderRowContainerCtrl,
  HeaderRowCtrl: () => HeaderRowCtrl,
  HeaderRowType: () => HeaderRowType,
  HorizontalDirection: () => HorizontalDirection,
  HorizontalResizeService: () => HorizontalResizeService,
  KeyCode: () => KeyCode,
  LargeTextCellEditor: () => LargeTextCellEditor,
  LayoutCssClasses: () => LayoutCssClasses,
  LocaleService: () => LocaleService,
  Logger: () => Logger,
  LoggerFactory: () => LoggerFactory,
  ManagedFocusFeature: () => ManagedFocusFeature,
  MenuService: () => MenuService,
  ModuleNames: () => ModuleNames,
  ModuleRegistry: () => ModuleRegistry,
  MouseEventService: () => MouseEventService,
  MoveColumnFeature: () => MoveColumnFeature,
  NavigationService: () => NavigationService,
  NumberCellEditor: () => NumberCellEditor,
  NumberFilter: () => NumberFilter,
  NumberSequence: () => NumberSequence,
  Optional: () => Optional,
  PaginationProxy: () => PaginationProxy,
  PillDragComp: () => PillDragComp,
  PillDropZonePanel: () => PillDropZonePanel,
  PinnedRowModel: () => PinnedRowModel,
  PopupComponent: () => PopupComponent,
  PopupEditorWrapper: () => PopupEditorWrapper,
  PopupService: () => PopupService,
  PositionableFeature: () => PositionableFeature,
  PostConstruct: () => PostConstruct,
  PreConstruct: () => PreConstruct,
  PreDestroy: () => PreDestroy,
  PropertyKeys: () => PropertyKeys,
  ProvidedColumnGroup: () => ProvidedColumnGroup,
  ProvidedFilter: () => ProvidedFilter,
  Qualifier: () => Qualifier,
  QuerySelector: () => QuerySelector,
  RefSelector: () => RefSelector,
  ResizeObserverService: () => ResizeObserverService,
  RowAnimationCssClasses: () => RowAnimationCssClasses,
  RowContainerComp: () => RowContainerComp,
  RowContainerCtrl: () => RowContainerCtrl,
  RowContainerName: () => RowContainerName,
  RowContainerType: () => RowContainerType,
  RowCtrl: () => RowCtrl,
  RowHighlightPosition: () => RowHighlightPosition,
  RowNode: () => RowNode,
  RowNodeBlock: () => RowNodeBlock,
  RowNodeBlockLoader: () => RowNodeBlockLoader,
  RowNodeSorter: () => RowNodeSorter,
  RowPositionUtils: () => RowPositionUtils,
  RowRenderer: () => RowRenderer,
  ScalarFilter: () => ScalarFilter,
  ScrollVisibleService: () => ScrollVisibleService,
  SelectCellEditor: () => SelectCellEditor,
  SelectableService: () => SelectableService,
  SelectionHandleType: () => SelectionHandleType,
  ServerSideTransactionResultStatus: () => ServerSideTransactionResultStatus,
  SetLeftFeature: () => SetLeftFeature,
  SimpleFilter: () => SimpleFilter,
  SortController: () => SortController,
  SortIndicatorComp: () => SortIndicatorComp,
  StandardMenuFactory: () => StandardMenuFactory,
  StylingService: () => StylingService,
  TabGuardClassNames: () => TabGuardClassNames,
  TabGuardComp: () => TabGuardComp,
  TabGuardCtrl: () => TabGuardCtrl,
  TabbedLayout: () => TabbedLayout,
  TextCellEditor: () => TextCellEditor,
  TextFilter: () => TextFilter,
  TextFloatingFilter: () => TextFloatingFilter,
  Timer: () => Timer,
  TooltipFeature: () => TooltipFeature,
  TooltipStateManager: () => TooltipStateManager,
  TouchListener: () => TouchListener,
  UserComponentFactory: () => UserComponentFactory,
  UserComponentRegistry: () => UserComponentRegistry,
  ValueCache: () => ValueCache,
  ValueService: () => ValueService,
  VanillaFrameworkOverrides: () => VanillaFrameworkOverrides,
  VerticalDirection: () => VerticalDirection,
  VirtualList: () => VirtualList,
  VirtualListDragFeature: () => VirtualListDragFeature,
  _: () => _,
  __FORCE_MODULE_DETECTION: () => __FORCE_MODULE_DETECTION,
  createGrid: () => createGrid,
  getRowContainerTypeForName: () => getRowContainerTypeForName,
  provideGlobalGridOptions: () => provideGlobalGridOptions
});
module.exports = __toCommonJS(main_exports);

// community-modules/core/src/utils/generic.ts
var generic_exports = {};
__export(generic_exports, {
  attrToBoolean: () => attrToBoolean,
  attrToNumber: () => attrToNumber,
  attrToString: () => attrToString,
  defaultComparator: () => defaultComparator,
  exists: () => exists,
  jsonEquals: () => jsonEquals,
  makeNull: () => makeNull,
  missing: () => missing,
  missingOrEmpty: () => missingOrEmpty,
  toStringOrNull: () => toStringOrNull,
  values: () => values
});
function makeNull(value) {
  if (value == null || value === "") {
    return null;
  }
  return value;
}
function exists(value, allowEmptyString = false) {
  return value != null && (value !== "" || allowEmptyString);
}
function missing(value) {
  return !exists(value);
}
function missingOrEmpty(value) {
  return value == null || value.length === 0;
}
function toStringOrNull(value) {
  return value != null && typeof value.toString === "function" ? value.toString() : null;
}
function attrToNumber(value) {
  if (value === void 0) {
    return;
  }
  if (value === null || value === "") {
    return null;
  }
  if (typeof value === "number") {
    return isNaN(value) ? void 0 : value;
  }
  const valueParsed = parseInt(value, 10);
  return isNaN(valueParsed) ? void 0 : valueParsed;
}
function attrToBoolean(value) {
  if (value === void 0) {
    return;
  }
  if (value === null || value === "") {
    return false;
  }
  if (typeof value === "boolean") {
    return value;
  }
  return /true/i.test(value);
}
function attrToString(value) {
  if (value == null || value === "") {
    return;
  }
  return value;
}
function jsonEquals(val1, val2) {
  const val1Json = val1 ? JSON.stringify(val1) : null;
  const val2Json = val2 ? JSON.stringify(val2) : null;
  return val1Json === val2Json;
}
function defaultComparator(valueA, valueB, accentedCompare = false) {
  const valueAMissing = valueA == null;
  const valueBMissing = valueB == null;
  if (valueA && valueA.toNumber) {
    valueA = valueA.toNumber();
  }
  if (valueB && valueB.toNumber) {
    valueB = valueB.toNumber();
  }
  if (valueAMissing && valueBMissing) {
    return 0;
  }
  if (valueAMissing) {
    return -1;
  }
  if (valueBMissing) {
    return 1;
  }
  function doQuickCompare(a, b) {
    return a > b ? 1 : a < b ? -1 : 0;
  }
  if (typeof valueA !== "string") {
    return doQuickCompare(valueA, valueB);
  }
  if (!accentedCompare) {
    return doQuickCompare(valueA, valueB);
  }
  try {
    return valueA.localeCompare(valueB);
  } catch (e) {
    return doQuickCompare(valueA, valueB);
  }
}
function values(object) {
  if (object instanceof Set || object instanceof Map) {
    const arr = [];
    object.forEach((value) => arr.push(value));
    return arr;
  }
  return Object.values(object);
}

// community-modules/core/src/columns/columnKeyCreator.ts
var ColumnKeyCreator = class {
  constructor() {
    this.existingKeys = {};
  }
  addExistingKeys(keys2) {
    for (let i = 0; i < keys2.length; i++) {
      this.existingKeys[keys2[i]] = true;
    }
  }
  getUniqueKey(colId, colField) {
    colId = toStringOrNull(colId);
    let count = 0;
    while (true) {
      let idToTry;
      if (colId) {
        idToTry = colId;
        if (count !== 0) {
          idToTry += "_" + count;
        }
      } else if (colField) {
        idToTry = colField;
        if (count !== 0) {
          idToTry += "_" + count;
        }
      } else {
        idToTry = count;
      }
      if (!this.existingKeys[idToTry]) {
        this.existingKeys[idToTry] = true;
        return String(idToTry);
      }
      count++;
    }
  }
};

// community-modules/core/src/utils/object.ts
var object_exports = {};
__export(object_exports, {
  SKIP_JS_BUILTINS: () => SKIP_JS_BUILTINS,
  cloneObject: () => cloneObject,
  deepCloneDefinition: () => deepCloneDefinition,
  getAllValuesInObject: () => getAllValuesInObject,
  getValueUsingField: () => getValueUsingField,
  isNonNullObject: () => isNonNullObject,
  iterateObject: () => iterateObject,
  mergeDeep: () => mergeDeep,
  removeAllReferences: () => removeAllReferences
});
var SKIP_JS_BUILTINS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
function iterateObject(object, callback) {
  if (object == null) {
    return;
  }
  if (Array.isArray(object)) {
    for (let i = 0; i < object.length; i++) {
      callback(i.toString(), object[i]);
    }
    return;
  }
  for (const [key, value] of Object.entries(object)) {
    callback(key, value);
  }
}
function cloneObject(object) {
  const copy = {};
  const keys2 = Object.keys(object);
  for (let i = 0; i < keys2.length; i++) {
    if (SKIP_JS_BUILTINS.has(keys2[i])) {
      continue;
    }
    const key = keys2[i];
    const value = object[key];
    copy[key] = value;
  }
  return copy;
}
function deepCloneDefinition(object, keysToSkip) {
  if (!object) {
    return;
  }
  const obj = object;
  const res = {};
  Object.keys(obj).forEach((key) => {
    if (keysToSkip && keysToSkip.indexOf(key) >= 0 || SKIP_JS_BUILTINS.has(key)) {
      return;
    }
    const value = obj[key];
    const sourceIsSimpleObject = isNonNullObject(value) && value.constructor === Object;
    if (sourceIsSimpleObject) {
      res[key] = deepCloneDefinition(value);
    } else {
      res[key] = value;
    }
  });
  return res;
}
function getAllValuesInObject(obj) {
  if (!obj) {
    return [];
  }
  const anyObject = Object;
  if (typeof anyObject.values === "function") {
    return anyObject.values(obj);
  }
  const ret = [];
  for (const key in obj) {
    if (obj.hasOwnProperty(key) && obj.propertyIsEnumerable(key)) {
      ret.push(obj[key]);
    }
  }
  return ret;
}
function mergeDeep(dest, source, copyUndefined = true, makeCopyOfSimpleObjects = false) {
  if (!exists(source)) {
    return;
  }
  iterateObject(source, (key, sourceValue) => {
    if (SKIP_JS_BUILTINS.has(key)) {
      return;
    }
    let destValue = dest[key];
    if (destValue === sourceValue) {
      return;
    }
    if (makeCopyOfSimpleObjects) {
      const objectIsDueToBeCopied = destValue == null && sourceValue != null;
      if (objectIsDueToBeCopied) {
        const sourceIsSimpleObject = typeof sourceValue === "object" && sourceValue.constructor === Object;
        const dontCopy = sourceIsSimpleObject;
        if (dontCopy) {
          destValue = {};
          dest[key] = destValue;
        }
      }
    }
    if (isNonNullObject(sourceValue) && isNonNullObject(destValue) && !Array.isArray(destValue)) {
      mergeDeep(destValue, sourceValue, copyUndefined, makeCopyOfSimpleObjects);
    } else if (copyUndefined || sourceValue !== void 0) {
      dest[key] = sourceValue;
    }
  });
}
function getValueUsingField(data, field, fieldContainsDots) {
  if (!field || !data) {
    return;
  }
  if (!fieldContainsDots) {
    return data[field];
  }
  const fields = field.split(".");
  let currentObject = data;
  for (let i = 0; i < fields.length; i++) {
    if (currentObject == null) {
      return void 0;
    }
    currentObject = currentObject[fields[i]];
  }
  return currentObject;
}
function removeAllReferences(obj, preserveKeys = [], preDestroyLink) {
  Object.keys(obj).forEach((key) => {
    const value = obj[key];
    if (typeof value === "object" && !preserveKeys.includes(key)) {
      obj[key] = void 0;
    }
  });
  const proto = Object.getPrototypeOf(obj);
  const properties = {};
  const msgFunc = (key) => `AG Grid: Grid API function ${key}() cannot be called as the grid has been destroyed.
    It is recommended to remove local references to the grid api. Alternatively, check gridApi.isDestroyed() to avoid calling methods against a destroyed grid.
    To run logic when the grid is about to be destroyed use the gridPreDestroy event. See: ${preDestroyLink}`;
  Object.getOwnPropertyNames(proto).forEach((key) => {
    const value = proto[key];
    if (typeof value === "function" && !preserveKeys.includes(key)) {
      const func = () => {
        console.warn(msgFunc(key));
      };
      properties[key] = { value: func, writable: true };
    }
  });
  Object.defineProperties(obj, properties);
}
function isNonNullObject(value) {
  return typeof value === "object" && value !== null;
}

// community-modules/core/src/utils/function.ts
var function_exports = {};
__export(function_exports, {
  compose: () => compose,
  debounce: () => debounce,
  doOnce: () => doOnce,
  errorOnce: () => errorOnce,
  executeAfter: () => executeAfter,
  executeInAWhile: () => executeInAWhile,
  executeNextVMTurn: () => executeNextVMTurn,
  getFunctionName: () => getFunctionName,
  isFunction: () => isFunction,
  noop: () => noop,
  throttle: () => throttle,
  waitUntil: () => waitUntil,
  warnOnce: () => warnOnce
});
var doOnceFlags = {};
function doOnce(func, key) {
  if (doOnceFlags[key]) {
    return;
  }
  func();
  doOnceFlags[key] = true;
}
function warnOnce(msg) {
  doOnce(() => console.warn("AG Grid: " + msg), msg);
}
function errorOnce(msg) {
  doOnce(() => console.error("AG Grid: " + msg), msg);
}
function getFunctionName(funcConstructor) {
  if (funcConstructor.name) {
    return funcConstructor.name;
  }
  const matches = /function\s+([^\(]+)/.exec(funcConstructor.toString());
  return matches && matches.length === 2 ? matches[1].trim() : null;
}
function isFunction(val) {
  return !!(val && val.constructor && val.call && val.apply);
}
function executeInAWhile(funcs) {
  executeAfter(funcs, 400);
}
var executeNextVMTurnFuncs = [];
var executeNextVMTurnPending = false;
function executeNextVMTurn(func) {
  executeNextVMTurnFuncs.push(func);
  if (executeNextVMTurnPending) {
    return;
  }
  executeNextVMTurnPending = true;
  window.setTimeout(() => {
    const funcsCopy = executeNextVMTurnFuncs.slice();
    executeNextVMTurnFuncs.length = 0;
    executeNextVMTurnPending = false;
    funcsCopy.forEach((func2) => func2());
  }, 0);
}
function executeAfter(funcs, milliseconds = 0) {
  if (funcs.length > 0) {
    window.setTimeout(() => funcs.forEach((func) => func()), milliseconds);
  }
}
function debounce(func, delay) {
  let timeout;
  return function(...args) {
    const context = this;
    window.clearTimeout(timeout);
    timeout = window.setTimeout(function() {
      func.apply(context, args);
    }, delay);
  };
}
function throttle(func, wait) {
  let previousCall = 0;
  return function(...args) {
    const context = this;
    const currentCall = (/* @__PURE__ */ new Date()).getTime();
    if (currentCall - previousCall < wait) {
      return;
    }
    previousCall = currentCall;
    func.apply(context, args);
  };
}
function waitUntil(condition, callback, timeout = 100, timeoutMessage) {
  const timeStamp = (/* @__PURE__ */ new Date()).getTime();
  let interval = null;
  let executed = false;
  const internalCallback = () => {
    const reachedTimeout = (/* @__PURE__ */ new Date()).getTime() - timeStamp > timeout;
    if (condition() || reachedTimeout) {
      callback();
      executed = true;
      if (interval != null) {
        window.clearInterval(interval);
        interval = null;
      }
      if (reachedTimeout && timeoutMessage) {
        console.warn(timeoutMessage);
      }
    }
  };
  internalCallback();
  if (!executed) {
    interval = window.setInterval(internalCallback, 10);
  }
}
function compose(...fns) {
  return (arg) => fns.reduce((composed, f) => f(composed), arg);
}
var noop = () => {
  return;
};

// community-modules/core/src/modules/moduleNames.ts
var ModuleNames = /* @__PURE__ */ ((ModuleNames2) => {
  ModuleNames2["CommunityCoreModule"] = "@ag-grid-community/core";
  ModuleNames2["InfiniteRowModelModule"] = "@ag-grid-community/infinite-row-model";
  ModuleNames2["ClientSideRowModelModule"] = "@ag-grid-community/client-side-row-model";
  ModuleNames2["CsvExportModule"] = "@ag-grid-community/csv-export";
  ModuleNames2["EnterpriseCoreModule"] = "@ag-grid-enterprise/core";
  ModuleNames2["RowGroupingModule"] = "@ag-grid-enterprise/row-grouping";
  ModuleNames2["ColumnsToolPanelModule"] = "@ag-grid-enterprise/column-tool-panel";
  ModuleNames2["FiltersToolPanelModule"] = "@ag-grid-enterprise/filter-tool-panel";
  ModuleNames2["MenuModule"] = "@ag-grid-enterprise/menu";
  ModuleNames2["SetFilterModule"] = "@ag-grid-enterprise/set-filter";
  ModuleNames2["MultiFilterModule"] = "@ag-grid-enterprise/multi-filter";
  ModuleNames2["StatusBarModule"] = "@ag-grid-enterprise/status-bar";
  ModuleNames2["SideBarModule"] = "@ag-grid-enterprise/side-bar";
  ModuleNames2["RangeSelectionModule"] = "@ag-grid-enterprise/range-selection";
  ModuleNames2["MasterDetailModule"] = "@ag-grid-enterprise/master-detail";
  ModuleNames2["RichSelectModule"] = "@ag-grid-enterprise/rich-select";
  ModuleNames2["GridChartsModule"] = "@ag-grid-enterprise/charts";
  ModuleNames2["ViewportRowModelModule"] = "@ag-grid-enterprise/viewport-row-model";
  ModuleNames2["ServerSideRowModelModule"] = "@ag-grid-enterprise/server-side-row-model";
  ModuleNames2["ExcelExportModule"] = "@ag-grid-enterprise/excel-export";
  ModuleNames2["ClipboardModule"] = "@ag-grid-enterprise/clipboard";
  ModuleNames2["SparklinesModule"] = "@ag-grid-enterprise/sparklines";
  ModuleNames2["AdvancedFilterModule"] = "@ag-grid-enterprise/advanced-filter";
  ModuleNames2["AngularModule"] = "@ag-grid-community/angular";
  ModuleNames2["ReactModule"] = "@ag-grid-community/react";
  ModuleNames2["VueModule"] = "@ag-grid-community/vue";
  return ModuleNames2;
})(ModuleNames || {});

// community-modules/core/src/modules/moduleRegistry.ts
var _ModuleRegistry = class _ModuleRegistry {
  /**
   * Globally register the given module for all grids.
   * @param module - module to register
   */
  static register(module2) {
    _ModuleRegistry.__register(module2, true, void 0);
  }
  /**
   * Globally register the given modules for all grids.
   * @param modules - modules to register
   */
  static registerModules(modules) {
    _ModuleRegistry.__registerModules(modules, true, void 0);
  }
  /** AG GRID INTERNAL - Module registration helper. */
  static __register(module2, moduleBased, gridId) {
    _ModuleRegistry.runVersionChecks(module2);
    if (gridId !== void 0) {
      _ModuleRegistry.areGridScopedModules = true;
      if (_ModuleRegistry.gridModulesMap[gridId] === void 0) {
        _ModuleRegistry.gridModulesMap[gridId] = {};
      }
      _ModuleRegistry.gridModulesMap[gridId][module2.moduleName] = module2;
    } else {
      _ModuleRegistry.globalModulesMap[module2.moduleName] = module2;
    }
    _ModuleRegistry.setModuleBased(moduleBased);
  }
  /** AG GRID INTERNAL - Unregister grid scoped module. */
  static __unRegisterGridModules(gridId) {
    delete _ModuleRegistry.gridModulesMap[gridId];
  }
  /** AG GRID INTERNAL - Module registration helper. */
  static __registerModules(modules, moduleBased, gridId) {
    _ModuleRegistry.setModuleBased(moduleBased);
    if (!modules) {
      return;
    }
    modules.forEach((module2) => _ModuleRegistry.__register(module2, moduleBased, gridId));
  }
  static isValidModuleVersion(module2) {
    const [moduleMajor, moduleMinor] = module2.version.split(".") || [];
    const [currentModuleMajor, currentModuleMinor] = _ModuleRegistry.currentModuleVersion.split(".") || [];
    return moduleMajor === currentModuleMajor && moduleMinor === currentModuleMinor;
  }
  static runVersionChecks(module2) {
    if (!_ModuleRegistry.currentModuleVersion) {
      _ModuleRegistry.currentModuleVersion = module2.version;
    }
    if (!module2.version) {
      console.error(`AG Grid: You are using incompatible versions of AG Grid modules. Major and minor versions should always match across modules. '${module2.moduleName}' is incompatible. Please update all modules to the same version.`);
    } else if (!_ModuleRegistry.isValidModuleVersion(module2)) {
      console.error(`AG Grid: You are using incompatible versions of AG Grid modules. Major and minor versions should always match across modules. '${module2.moduleName}' is version ${module2.version} but the other modules are version ${this.currentModuleVersion}. Please update all modules to the same version.`);
    }
    if (module2.validate) {
      const result = module2.validate();
      if (!result.isValid) {
        const errorResult = result;
        console.error(`AG Grid: ${errorResult.message}`);
      }
    }
  }
  static setModuleBased(moduleBased) {
    if (_ModuleRegistry.moduleBased === void 0) {
      _ModuleRegistry.moduleBased = moduleBased;
    } else {
      if (_ModuleRegistry.moduleBased !== moduleBased) {
        doOnce(
          () => {
            console.warn(`AG Grid: You are mixing modules (i.e. @ag-grid-community/core) and packages (ag-grid-community) - you can only use one or the other of these mechanisms.`);
            console.warn("Please see https://www.ag-grid.com/javascript-grid/modules/ for more information.");
          },
          "ModulePackageCheck"
        );
      }
    }
  }
  /**
   * AG GRID INTERNAL - Set if files are being served from a single UMD bundle to provide accurate enterprise upgrade steps.
   */
  static __setIsBundled() {
    _ModuleRegistry.isBundled = true;
  }
  /** AG GRID INTERNAL - Assert a given module has been register, globally or individually with this grid. */
  static __assertRegistered(moduleName, reason, gridId) {
    var _a;
    if (this.__isRegistered(moduleName, gridId)) {
      return true;
    }
    const warningKey = reason + moduleName;
    let warningMessage;
    if (_ModuleRegistry.isBundled) {
      {
        warningMessage = `AG Grid: unable to use ${reason} as 'ag-grid-enterprise' has not been loaded. Check you are using the Enterprise bundle:
        
        <script src="https://cdn.jsdelivr.net/npm/ag-grid-enterprise@AG_GRID_VERSION/dist/ag-grid-enterprise.min.js"><\/script>
        
For more info see: https://ag-grid.com/javascript-data-grid/getting-started/#getting-started-with-ag-grid-enterprise`;
      }
    } else if (_ModuleRegistry.moduleBased || _ModuleRegistry.moduleBased === void 0) {
      let modName = (_a = Object.entries(ModuleNames).find(([k, v]) => v === moduleName)) == null ? void 0 : _a[0];
      warningMessage = `AG Grid: unable to use ${reason} as the ${modName} is not registered${_ModuleRegistry.areGridScopedModules ? ` for gridId: ${gridId}` : ""}. Check if you have registered the module:
           
    import { ModuleRegistry } from '@ag-grid-community/core';
    import { ${modName} } from '${moduleName}';
    
    ModuleRegistry.registerModules([ ${modName} ]);

For more info see: https://www.ag-grid.com/javascript-grid/modules/`;
    } else {
      warningMessage = `AG Grid: unable to use ${reason} as package 'ag-grid-enterprise' has not been imported. Check that you have imported the package:
            
    import 'ag-grid-enterprise';`;
    }
    doOnce(() => {
      console.warn(warningMessage);
    }, warningKey);
    return false;
  }
  /** AG GRID INTERNAL - Is the given module registered, globally or individually with this grid. */
  static __isRegistered(moduleName, gridId) {
    var _a;
    return !!_ModuleRegistry.globalModulesMap[moduleName] || !!((_a = _ModuleRegistry.gridModulesMap[gridId]) == null ? void 0 : _a[moduleName]);
  }
  /** AG GRID INTERNAL - Get all registered modules globally / individually for this grid. */
  static __getRegisteredModules(gridId) {
    return [...values(_ModuleRegistry.globalModulesMap), ...values(_ModuleRegistry.gridModulesMap[gridId] || {})];
  }
  /** AG GRID INTERNAL - Get the list of modules registered individually for this grid. */
  static __getGridRegisteredModules(gridId) {
    var _a;
    return values((_a = _ModuleRegistry.gridModulesMap[gridId]) != null ? _a : {}) || [];
  }
  /** INTERNAL */
  static __isPackageBased() {
    return !_ModuleRegistry.moduleBased;
  }
};
// having in a map a) removes duplicates and b) allows fast lookup
_ModuleRegistry.globalModulesMap = {};
_ModuleRegistry.gridModulesMap = {};
_ModuleRegistry.areGridScopedModules = false;
var ModuleRegistry = _ModuleRegistry;

// community-modules/core/src/context/context.ts
var Context = class {
  constructor(params, logger) {
    this.beanWrappers = {};
    this.destroyed = false;
    if (!params || !params.beanClasses) {
      return;
    }
    this.contextParams = params;
    this.logger = logger;
    this.logger.log(">> creating ag-Application Context");
    this.createBeans();
    const beanInstances = this.getBeanInstances();
    this.wireBeans(beanInstances);
    this.logger.log(">> ag-Application Context ready - component is alive");
  }
  getBeanInstances() {
    return values(this.beanWrappers).map((beanEntry) => beanEntry.beanInstance);
  }
  createBean(bean, afterPreCreateCallback) {
    if (!bean) {
      throw Error(`Can't wire to bean since it is null`);
    }
    this.wireBeans([bean], afterPreCreateCallback);
    return bean;
  }
  wireBeans(beanInstances, afterPreCreateCallback) {
    this.autoWireBeans(beanInstances);
    this.methodWireBeans(beanInstances);
    this.callLifeCycleMethods(beanInstances, "preConstructMethods");
    if (exists(afterPreCreateCallback)) {
      beanInstances.forEach(afterPreCreateCallback);
    }
    this.callLifeCycleMethods(beanInstances, "postConstructMethods");
  }
  createBeans() {
    this.contextParams.beanClasses.forEach(this.createBeanWrapper.bind(this));
    iterateObject(this.beanWrappers, (key, beanEntry) => {
      let constructorParamsMeta;
      if (beanEntry.bean.__agBeanMetaData && beanEntry.bean.__agBeanMetaData.autowireMethods && beanEntry.bean.__agBeanMetaData.autowireMethods.agConstructor) {
        constructorParamsMeta = beanEntry.bean.__agBeanMetaData.autowireMethods.agConstructor;
      }
      const constructorParams = this.getBeansForParameters(constructorParamsMeta, beanEntry.bean.name);
      const newInstance = new (beanEntry.bean.bind.apply(beanEntry.bean, [null, ...constructorParams]))();
      beanEntry.beanInstance = newInstance;
    });
    const createdBeanNames = Object.keys(this.beanWrappers).join(", ");
    this.logger.log(`created beans: ${createdBeanNames}`);
  }
  // tslint:disable-next-line
  createBeanWrapper(BeanClass) {
    const metaData = BeanClass.__agBeanMetaData;
    if (!metaData) {
      let beanName;
      if (BeanClass.prototype.constructor) {
        beanName = getFunctionName(BeanClass.prototype.constructor);
      } else {
        beanName = "" + BeanClass;
      }
      console.error(`Context item ${beanName} is not a bean`);
      return;
    }
    const beanEntry = {
      bean: BeanClass,
      beanInstance: null,
      beanName: metaData.beanName
    };
    this.beanWrappers[metaData.beanName] = beanEntry;
  }
  autoWireBeans(beanInstances) {
    beanInstances.forEach((beanInstance) => {
      this.forEachMetaDataInHierarchy(beanInstance, (metaData, beanName) => {
        const attributes = metaData.agClassAttributes;
        if (!attributes) {
          return;
        }
        attributes.forEach((attribute) => {
          const otherBean = this.lookupBeanInstance(beanName, attribute.beanName, attribute.optional);
          beanInstance[attribute.attributeName] = otherBean;
        });
      });
    });
  }
  methodWireBeans(beanInstances) {
    beanInstances.forEach((beanInstance) => {
      this.forEachMetaDataInHierarchy(beanInstance, (metaData, beanName) => {
        iterateObject(metaData.autowireMethods, (methodName, wireParams) => {
          if (methodName === "agConstructor") {
            return;
          }
          const initParams = this.getBeansForParameters(wireParams, beanName);
          beanInstance[methodName].apply(beanInstance, initParams);
        });
      });
    });
  }
  forEachMetaDataInHierarchy(beanInstance, callback) {
    let prototype = Object.getPrototypeOf(beanInstance);
    while (prototype != null) {
      const constructor = prototype.constructor;
      if (constructor.hasOwnProperty("__agBeanMetaData")) {
        const metaData = constructor.__agBeanMetaData;
        const beanName = this.getBeanName(constructor);
        callback(metaData, beanName);
      }
      prototype = Object.getPrototypeOf(prototype);
    }
  }
  getBeanName(constructor) {
    if (constructor.__agBeanMetaData && constructor.__agBeanMetaData.beanName) {
      return constructor.__agBeanMetaData.beanName;
    }
    const constructorString = constructor.toString();
    const beanName = constructorString.substring(9, constructorString.indexOf("("));
    return beanName;
  }
  getBeansForParameters(parameters, beanName) {
    const beansList = [];
    if (parameters) {
      iterateObject(parameters, (paramIndex, otherBeanName) => {
        const otherBean = this.lookupBeanInstance(beanName, otherBeanName);
        beansList[Number(paramIndex)] = otherBean;
      });
    }
    return beansList;
  }
  lookupBeanInstance(wiringBean, beanName, optional = false) {
    if (this.destroyed) {
      this.logger.log(`AG Grid: bean reference ${beanName} is used after the grid is destroyed!`);
      return null;
    }
    if (beanName === "context") {
      return this;
    }
    if (this.contextParams.providedBeanInstances && this.contextParams.providedBeanInstances.hasOwnProperty(beanName)) {
      return this.contextParams.providedBeanInstances[beanName];
    }
    const beanEntry = this.beanWrappers[beanName];
    if (beanEntry) {
      return beanEntry.beanInstance;
    }
    if (!optional) {
      console.error(`AG Grid: unable to find bean reference ${beanName} while initialising ${wiringBean}`);
    }
    return null;
  }
  callLifeCycleMethods(beanInstances, lifeCycleMethod) {
    beanInstances.forEach((beanInstance) => this.callLifeCycleMethodsOnBean(beanInstance, lifeCycleMethod));
  }
  callLifeCycleMethodsOnBean(beanInstance, lifeCycleMethod, methodToIgnore) {
    const allMethods = {};
    this.forEachMetaDataInHierarchy(beanInstance, (metaData) => {
      const methods = metaData[lifeCycleMethod];
      if (methods) {
        methods.forEach((methodName) => {
          if (methodName != methodToIgnore) {
            allMethods[methodName] = true;
          }
        });
      }
    });
    const allMethodsList = Object.keys(allMethods);
    allMethodsList.forEach((methodName) => beanInstance[methodName]());
  }
  getBean(name) {
    return this.lookupBeanInstance("getBean", name, true);
  }
  destroy() {
    if (this.destroyed) {
      return;
    }
    this.destroyed = true;
    this.logger.log(">> Shutting down ag-Application Context");
    const beanInstances = this.getBeanInstances();
    this.destroyBeans(beanInstances);
    this.contextParams.providedBeanInstances = null;
    ModuleRegistry.__unRegisterGridModules(this.contextParams.gridId);
    this.logger.log(">> ag-Application Context shut down - component is dead");
  }
  destroyBean(bean) {
    if (!bean) {
      return;
    }
    this.destroyBeans([bean]);
  }
  destroyBeans(beans) {
    if (!beans) {
      return [];
    }
    beans.forEach((bean) => {
      this.callLifeCycleMethodsOnBean(bean, "preDestroyMethods", "destroy");
      const beanAny = bean;
      if (typeof beanAny.destroy === "function") {
        beanAny.destroy();
      }
    });
    return [];
  }
  isDestroyed() {
    return this.destroyed;
  }
  getGridId() {
    return this.contextParams.gridId;
  }
};
function PreConstruct(target, methodName, descriptor) {
  const props = getOrCreateProps(target.constructor);
  if (!props.preConstructMethods) {
    props.preConstructMethods = [];
  }
  props.preConstructMethods.push(methodName);
}
function PostConstruct(target, methodName, descriptor) {
  const props = getOrCreateProps(target.constructor);
  if (!props.postConstructMethods) {
    props.postConstructMethods = [];
  }
  props.postConstructMethods.push(methodName);
}
function PreDestroy(target, methodName, descriptor) {
  const props = getOrCreateProps(target.constructor);
  if (!props.preDestroyMethods) {
    props.preDestroyMethods = [];
  }
  props.preDestroyMethods.push(methodName);
}
function Bean(beanName) {
  return (classConstructor) => {
    const props = getOrCreateProps(classConstructor);
    props.beanName = beanName;
  };
}
function Autowired(name) {
  return (target, propertyKey, descriptor) => {
    autowiredFunc(target, name, false, target, propertyKey, null);
  };
}
function Optional(name) {
  return (target, propertyKey, descriptor) => {
    autowiredFunc(target, name, true, target, propertyKey, null);
  };
}
function autowiredFunc(target, name, optional, classPrototype, methodOrAttributeName, index) {
  if (name === null) {
    console.error("AG Grid: Autowired name should not be null");
    return;
  }
  if (typeof index === "number") {
    console.error("AG Grid: Autowired should be on an attribute");
    return;
  }
  const props = getOrCreateProps(target.constructor);
  if (!props.agClassAttributes) {
    props.agClassAttributes = [];
  }
  props.agClassAttributes.push({
    attributeName: methodOrAttributeName,
    beanName: name,
    optional
  });
}
function Qualifier(name) {
  return (classPrototype, methodOrAttributeName, index) => {
    const constructor = typeof classPrototype == "function" ? classPrototype : classPrototype.constructor;
    let props;
    if (typeof index === "number") {
      let methodName;
      if (methodOrAttributeName) {
        props = getOrCreateProps(constructor);
        methodName = methodOrAttributeName;
      } else {
        props = getOrCreateProps(constructor);
        methodName = "agConstructor";
      }
      if (!props.autowireMethods) {
        props.autowireMethods = {};
      }
      if (!props.autowireMethods[methodName]) {
        props.autowireMethods[methodName] = {};
      }
      props.autowireMethods[methodName][index] = name;
    }
  };
}
function getOrCreateProps(target) {
  if (!target.hasOwnProperty("__agBeanMetaData")) {
    target.__agBeanMetaData = {};
  }
  return target.__agBeanMetaData;
}

// community-modules/core/src/eventService.ts
var EventService = class {
  constructor() {
    this.allSyncListeners = /* @__PURE__ */ new Map();
    this.allAsyncListeners = /* @__PURE__ */ new Map();
    this.globalSyncListeners = /* @__PURE__ */ new Set();
    this.globalAsyncListeners = /* @__PURE__ */ new Set();
    this.asyncFunctionsQueue = [];
    this.scheduled = false;
    // using an object performs better than a Set for the number of different events we have
    this.firedEvents = {};
  }
  // because this class is used both inside the context and outside the context, we do not
  // use autowired attributes, as that would be confusing, as sometimes the attributes
  // would be wired, and sometimes not.
  //
  // the global event servers used by AG Grid is autowired by the context once, and this
  // setBeans method gets called once.
  //
  // the times when this class is used outside of the context (eg RowNode has an instance of this
  // class) then it is not a bean, and this setBeans method is not called.
  setBeans(gos, frameworkOverrides, globalEventListener = null, globalSyncEventListener = null) {
    this.frameworkOverrides = frameworkOverrides;
    this.gos = gos;
    if (globalEventListener) {
      const async = gos.useAsyncEvents();
      this.addGlobalListener(globalEventListener, async);
    }
    if (globalSyncEventListener) {
      this.addGlobalListener(globalSyncEventListener, false);
    }
  }
  setFrameworkOverrides(frameworkOverrides) {
    this.frameworkOverrides = frameworkOverrides;
  }
  getListeners(eventType, async, autoCreateListenerCollection) {
    const listenerMap = async ? this.allAsyncListeners : this.allSyncListeners;
    let listeners = listenerMap.get(eventType);
    if (!listeners && autoCreateListenerCollection) {
      listeners = /* @__PURE__ */ new Set();
      listenerMap.set(eventType, listeners);
    }
    return listeners;
  }
  noRegisteredListenersExist() {
    return this.allSyncListeners.size === 0 && this.allAsyncListeners.size === 0 && this.globalSyncListeners.size === 0 && this.globalAsyncListeners.size === 0;
  }
  addEventListener(eventType, listener, async = false) {
    this.getListeners(eventType, async, true).add(listener);
  }
  removeEventListener(eventType, listener, async = false) {
    const listeners = this.getListeners(eventType, async, false);
    if (!listeners) {
      return;
    }
    listeners.delete(listener);
    if (listeners.size === 0) {
      const listenerMap = async ? this.allAsyncListeners : this.allSyncListeners;
      listenerMap.delete(eventType);
    }
  }
  addGlobalListener(listener, async = false) {
    (async ? this.globalAsyncListeners : this.globalSyncListeners).add(listener);
  }
  removeGlobalListener(listener, async = false) {
    (async ? this.globalAsyncListeners : this.globalSyncListeners).delete(listener);
  }
  dispatchEvent(event) {
    let agEvent = event;
    if (this.gos) {
      this.gos.addGridCommonParams(agEvent);
    }
    this.dispatchToListeners(agEvent, true);
    this.dispatchToListeners(agEvent, false);
    this.firedEvents[agEvent.type] = true;
  }
  dispatchEventOnce(event) {
    if (!this.firedEvents[event.type]) {
      this.dispatchEvent(event);
    }
  }
  dispatchToListeners(event, async) {
    var _a;
    const eventType = event.type;
    if (async && "event" in event) {
      const browserEvent = event.event;
      if (browserEvent instanceof Event) {
        event.eventPath = browserEvent.composedPath();
      }
    }
    const processEventListeners = (listeners2, originalListeners2) => listeners2.forEach((listener) => {
      if (!originalListeners2.has(listener)) {
        return;
      }
      const callback = this.frameworkOverrides ? () => this.frameworkOverrides.wrapIncoming(() => listener(event)) : () => listener(event);
      if (async) {
        this.dispatchAsync(callback);
      } else {
        callback();
      }
    });
    const originalListeners = (_a = this.getListeners(eventType, async, false)) != null ? _a : /* @__PURE__ */ new Set();
    const listeners = new Set(originalListeners);
    if (listeners.size > 0) {
      processEventListeners(listeners, originalListeners);
    }
    const globalListeners = new Set(async ? this.globalAsyncListeners : this.globalSyncListeners);
    globalListeners.forEach((listener) => {
      const callback = this.frameworkOverrides ? () => this.frameworkOverrides.wrapIncoming(() => listener(eventType, event)) : () => listener(eventType, event);
      if (async) {
        this.dispatchAsync(callback);
      } else {
        callback();
      }
    });
  }
  // this gets called inside the grid's thread, for each event that it
  // wants to set async. the grid then batches the events into one setTimeout()
  // because setTimeout() is an expensive operation. ideally we would have
  // each event in it's own setTimeout(), but we batch for performance.
  dispatchAsync(func) {
    this.asyncFunctionsQueue.push(func);
    if (!this.scheduled) {
      this.frameworkOverrides.wrapIncoming(() => {
        window.setTimeout(this.flushAsyncQueue.bind(this), 0);
      });
      this.scheduled = true;
    }
  }
  // this happens in the next VM turn only, and empties the queue of events
  flushAsyncQueue() {
    this.scheduled = false;
    const queueCopy = this.asyncFunctionsQueue.slice();
    this.asyncFunctionsQueue = [];
    queueCopy.forEach((func) => func());
  }
};
__decorateClass([
  __decorateParam(0, Qualifier("gridOptionsService")),
  __decorateParam(1, Qualifier("frameworkOverrides")),
  __decorateParam(2, Qualifier("globalEventListener")),
  __decorateParam(3, Qualifier("globalSyncEventListener"))
], EventService.prototype, "setBeans", 1);
EventService = __decorateClass([
  Bean("eventService")
], EventService);

// community-modules/core/src/misc/frameworkEventListenerService.ts
var FrameworkEventListenerService = class {
  constructor(frameworkOverrides) {
    this.frameworkOverrides = frameworkOverrides;
    // Map from user listener to wrapped listener so we can remove listener provided by user
    this.wrappedListeners = /* @__PURE__ */ new Map();
    this.wrappedGlobalListeners = /* @__PURE__ */ new Map();
  }
  wrap(userListener) {
    let listener = userListener;
    if (this.frameworkOverrides.shouldWrapOutgoing) {
      listener = (event) => {
        this.frameworkOverrides.wrapOutgoing(() => userListener(event));
      };
      this.wrappedListeners.set(userListener, listener);
    }
    return listener;
  }
  wrapGlobal(userListener) {
    let listener = userListener;
    if (this.frameworkOverrides.shouldWrapOutgoing) {
      listener = (eventType, event) => {
        this.frameworkOverrides.wrapOutgoing(() => userListener(eventType, event));
      };
      this.wrappedGlobalListeners.set(userListener, listener);
    }
    return listener;
  }
  unwrap(userListener) {
    var _a;
    return (_a = this.wrappedListeners.get(userListener)) != null ? _a : userListener;
  }
  unwrapGlobal(userListener) {
    var _a;
    return (_a = this.wrappedGlobalListeners.get(userListener)) != null ? _a : userListener;
  }
};

// community-modules/core/src/entities/column.ts
var COL_DEF_DEFAULTS = {
  resizable: true,
  sortable: true
};
var instanceIdSequence = 0;
function getNextColInstanceId() {
  return instanceIdSequence++;
}
var _Column = class _Column {
  constructor(colDef, userProvidedColDef, colId, primary) {
    // used by React (and possibly other frameworks) as key for rendering. also used to
    // identify old vs new columns for destroying cols when no longer used.
    this.instanceId = getNextColInstanceId();
    // The measured height of this column's header when autoHeaderHeight is enabled
    this.autoHeaderHeight = null;
    this.moving = false;
    this.menuVisible = false;
    this.lastLeftPinned = false;
    this.firstRightPinned = false;
    this.filterActive = false;
    this.eventService = new EventService();
    this.tooltipEnabled = false;
    this.rowGroupActive = false;
    this.pivotActive = false;
    this.aggregationActive = false;
    this.colDef = colDef;
    this.userProvidedColDef = userProvidedColDef;
    this.colId = colId;
    this.primary = primary;
    this.setState(colDef);
  }
  getInstanceId() {
    return this.instanceId;
  }
  setState(colDef) {
    if (colDef.sort !== void 0) {
      if (colDef.sort === "asc" || colDef.sort === "desc") {
        this.sort = colDef.sort;
      }
    } else {
      if (colDef.initialSort === "asc" || colDef.initialSort === "desc") {
        this.sort = colDef.initialSort;
      }
    }
    const sortIndex = colDef.sortIndex;
    const initialSortIndex = colDef.initialSortIndex;
    if (sortIndex !== void 0) {
      if (sortIndex !== null) {
        this.sortIndex = sortIndex;
      }
    } else {
      if (initialSortIndex !== null) {
        this.sortIndex = initialSortIndex;
      }
    }
    const hide = colDef.hide;
    const initialHide = colDef.initialHide;
    if (hide !== void 0) {
      this.visible = !hide;
    } else {
      this.visible = !initialHide;
    }
    if (colDef.pinned !== void 0) {
      this.setPinned(colDef.pinned);
    } else {
      this.setPinned(colDef.initialPinned);
    }
    const flex = colDef.flex;
    const initialFlex = colDef.initialFlex;
    if (flex !== void 0) {
      this.flex = flex;
    } else if (initialFlex !== void 0) {
      this.flex = initialFlex;
    }
  }
  // gets called when user provides an alternative colDef, eg
  setColDef(colDef, userProvidedColDef, source) {
    this.colDef = colDef;
    this.userProvidedColDef = userProvidedColDef;
    this.initMinAndMaxWidths();
    this.initDotNotation();
    this.initTooltip();
    this.eventService.dispatchEvent(this.createColumnEvent("colDefChanged", source));
  }
  /**
   * Returns the column definition provided by the application.
   * This may not be correct, as items can be superseded by default column options.
   * However it's useful for comparison, eg to know which application column definition matches that column.
   */
  getUserProvidedColDef() {
    return this.userProvidedColDef;
  }
  setParent(parent) {
    this.parent = parent;
  }
  /** Returns the parent column group, if column grouping is active. */
  getParent() {
    return this.parent;
  }
  setOriginalParent(originalParent) {
    this.originalParent = originalParent;
  }
  /**
   * Used for marryChildren, helps with comparing when duplicate groups have been created to manage split groups.
   * 
   * Parent may contain a duplicate but not identical group when the group is split.
   */
  getOriginalParent() {
    return this.originalParent;
  }
  initialise() {
    this.initMinAndMaxWidths();
    this.resetActualWidth("gridInitializing");
    this.initDotNotation();
    this.initTooltip();
  }
  initDotNotation() {
    const suppressDotNotation = this.gos.get("suppressFieldDotNotation");
    this.fieldContainsDots = exists(this.colDef.field) && this.colDef.field.indexOf(".") >= 0 && !suppressDotNotation;
    this.tooltipFieldContainsDots = exists(this.colDef.tooltipField) && this.colDef.tooltipField.indexOf(".") >= 0 && !suppressDotNotation;
  }
  initMinAndMaxWidths() {
    var _a, _b;
    const colDef = this.colDef;
    this.minWidth = (_a = colDef.minWidth) != null ? _a : this.environment.getMinColWidth();
    this.maxWidth = (_b = colDef.maxWidth) != null ? _b : Number.MAX_SAFE_INTEGER;
  }
  initTooltip() {
    this.tooltipEnabled = exists(this.colDef.tooltipField) || exists(this.colDef.tooltipValueGetter) || exists(this.colDef.tooltipComponent);
  }
  resetActualWidth(source) {
    const initialWidth = this.calculateColInitialWidth(this.colDef);
    this.setActualWidth(initialWidth, source, true);
  }
  calculateColInitialWidth(colDef) {
    var _a, _b;
    const minColWidth = (_a = colDef.minWidth) != null ? _a : this.environment.getMinColWidth();
    const maxColWidth = (_b = colDef.maxWidth) != null ? _b : Number.MAX_SAFE_INTEGER;
    let width;
    const colDefWidth = attrToNumber(colDef.width);
    const colDefInitialWidth = attrToNumber(colDef.initialWidth);
    if (colDefWidth != null) {
      width = colDefWidth;
    } else if (colDefInitialWidth != null) {
      width = colDefInitialWidth;
    } else {
      width = 200;
    }
    return Math.max(Math.min(width, maxColWidth), minColWidth);
  }
  isEmptyGroup() {
    return false;
  }
  isRowGroupDisplayed(colId) {
    if (missing(this.colDef) || missing(this.colDef.showRowGroup)) {
      return false;
    }
    const showingAllGroups = this.colDef.showRowGroup === true;
    const showingThisGroup = this.colDef.showRowGroup === colId;
    return showingAllGroups || showingThisGroup;
  }
  /** Returns `true` if column is a primary column, `false` if secondary. Secondary columns are used for pivoting. */
  isPrimary() {
    return this.primary;
  }
  /** Returns `true` if column filtering is allowed. */
  isFilterAllowed() {
    const filterDefined = !!this.colDef.filter;
    return filterDefined;
  }
  isFieldContainsDots() {
    return this.fieldContainsDots;
  }
  isTooltipEnabled() {
    return this.tooltipEnabled;
  }
  isTooltipFieldContainsDots() {
    return this.tooltipFieldContainsDots;
  }
  /** Add an event listener to the column. */
  addEventListener(eventType, userListener) {
    var _a, _b;
    if (this.frameworkOverrides.shouldWrapOutgoing && !this.frameworkEventListenerService) {
      this.eventService.setFrameworkOverrides(this.frameworkOverrides);
      this.frameworkEventListenerService = new FrameworkEventListenerService(this.frameworkOverrides);
    }
    const listener = (_b = (_a = this.frameworkEventListenerService) == null ? void 0 : _a.wrap(userListener)) != null ? _b : userListener;
    this.eventService.addEventListener(eventType, listener);
  }
  /** Remove event listener from the column. */
  removeEventListener(eventType, userListener) {
    var _a, _b;
    const listener = (_b = (_a = this.frameworkEventListenerService) == null ? void 0 : _a.unwrap(userListener)) != null ? _b : userListener;
    this.eventService.removeEventListener(eventType, listener);
  }
  createColumnFunctionCallbackParams(rowNode) {
    return this.gos.addGridCommonParams({
      node: rowNode,
      data: rowNode.data,
      column: this,
      colDef: this.colDef
    });
  }
  isSuppressNavigable(rowNode) {
    if (typeof this.colDef.suppressNavigable === "boolean") {
      return this.colDef.suppressNavigable;
    }
    if (typeof this.colDef.suppressNavigable === "function") {
      const params = this.createColumnFunctionCallbackParams(rowNode);
      const userFunc = this.colDef.suppressNavigable;
      return userFunc(params);
    }
    return false;
  }
  /**
   * Returns `true` if the cell for this column is editable for the given `rowNode`, otherwise `false`.
   */
  isCellEditable(rowNode) {
    if (rowNode.group && !this.gos.get("enableGroupEdit")) {
      return false;
    }
    return this.isColumnFunc(rowNode, this.colDef.editable);
  }
  isSuppressFillHandle() {
    return !!this.colDef.suppressFillHandle;
  }
  isAutoHeight() {
    return !!this.colDef.autoHeight;
  }
  isAutoHeaderHeight() {
    return !!this.colDef.autoHeaderHeight;
  }
  isRowDrag(rowNode) {
    return this.isColumnFunc(rowNode, this.colDef.rowDrag);
  }
  isDndSource(rowNode) {
    return this.isColumnFunc(rowNode, this.colDef.dndSource);
  }
  isCellCheckboxSelection(rowNode) {
    return this.isColumnFunc(rowNode, this.colDef.checkboxSelection);
  }
  isSuppressPaste(rowNode) {
    return this.isColumnFunc(rowNode, this.colDef ? this.colDef.suppressPaste : null);
  }
  isResizable() {
    return !!this.getColDefValue("resizable");
  }
  /** Get value from ColDef or default if it exists. */
  getColDefValue(key) {
    var _a;
    return (_a = this.colDef[key]) != null ? _a : COL_DEF_DEFAULTS[key];
  }
  isColumnFunc(rowNode, value) {
    if (typeof value === "boolean") {
      return value;
    }
    if (typeof value === "function") {
      const params = this.createColumnFunctionCallbackParams(rowNode);
      const editableFunc = value;
      return editableFunc(params);
    }
    return false;
  }
  setMoving(moving, source) {
    this.moving = moving;
    this.eventService.dispatchEvent(this.createColumnEvent("movingChanged", source));
  }
  createColumnEvent(type, source) {
    return this.gos.addGridCommonParams({
      type,
      column: this,
      columns: [this],
      source
    });
  }
  isMoving() {
    return this.moving;
  }
  /** If sorting is active, returns the sort direction e.g. `'asc'` or `'desc'`. */
  getSort() {
    return this.sort;
  }
  setSort(sort, source) {
    if (this.sort !== sort) {
      this.sort = sort;
      this.eventService.dispatchEvent(this.createColumnEvent("sortChanged", source));
    }
    this.dispatchStateUpdatedEvent("sort");
  }
  setMenuVisible(visible, source) {
    if (this.menuVisible !== visible) {
      this.menuVisible = visible;
      this.eventService.dispatchEvent(this.createColumnEvent("menuVisibleChanged", source));
    }
  }
  isMenuVisible() {
    return this.menuVisible;
  }
  isSortable() {
    return !!this.getColDefValue("sortable");
  }
  isSortAscending() {
    return this.sort === "asc";
  }
  isSortDescending() {
    return this.sort === "desc";
  }
  isSortNone() {
    return missing(this.sort);
  }
  isSorting() {
    return exists(this.sort);
  }
  getSortIndex() {
    return this.sortIndex;
  }
  setSortIndex(sortOrder) {
    this.sortIndex = sortOrder;
    this.dispatchStateUpdatedEvent("sortIndex");
  }
  setAggFunc(aggFunc) {
    this.aggFunc = aggFunc;
    this.dispatchStateUpdatedEvent("aggFunc");
  }
  /** If aggregation is set for the column, returns the aggregation function. */
  getAggFunc() {
    return this.aggFunc;
  }
  getLeft() {
    return this.left;
  }
  getOldLeft() {
    return this.oldLeft;
  }
  getRight() {
    return this.left + this.actualWidth;
  }
  setLeft(left, source) {
    this.oldLeft = this.left;
    if (this.left !== left) {
      this.left = left;
      this.eventService.dispatchEvent(this.createColumnEvent("leftChanged", source));
    }
  }
  /** Returns `true` if filter is active on the column. */
  isFilterActive() {
    return this.filterActive;
  }
  // additionalEventAttributes is used by provided simple floating filter, so it can add 'floatingFilter=true' to the event
  setFilterActive(active, source, additionalEventAttributes) {
    if (this.filterActive !== active) {
      this.filterActive = active;
      this.eventService.dispatchEvent(this.createColumnEvent("filterActiveChanged", source));
    }
    const filterChangedEvent = this.createColumnEvent("filterChanged", source);
    if (additionalEventAttributes) {
      mergeDeep(filterChangedEvent, additionalEventAttributes);
    }
    this.eventService.dispatchEvent(filterChangedEvent);
  }
  /** Returns `true` when this `Column` is hovered, otherwise `false` */
  isHovered() {
    return this.columnHoverService.isHovered(this);
  }
  setPinned(pinned) {
    if (pinned === true || pinned === "left") {
      this.pinned = "left";
    } else if (pinned === "right") {
      this.pinned = "right";
    } else {
      this.pinned = null;
    }
    this.dispatchStateUpdatedEvent("pinned");
  }
  setFirstRightPinned(firstRightPinned, source) {
    if (this.firstRightPinned !== firstRightPinned) {
      this.firstRightPinned = firstRightPinned;
      this.eventService.dispatchEvent(this.createColumnEvent("firstRightPinnedChanged", source));
    }
  }
  setLastLeftPinned(lastLeftPinned, source) {
    if (this.lastLeftPinned !== lastLeftPinned) {
      this.lastLeftPinned = lastLeftPinned;
      this.eventService.dispatchEvent(this.createColumnEvent("lastLeftPinnedChanged", source));
    }
  }
  isFirstRightPinned() {
    return this.firstRightPinned;
  }
  isLastLeftPinned() {
    return this.lastLeftPinned;
  }
  isPinned() {
    return this.pinned === "left" || this.pinned === "right";
  }
  isPinnedLeft() {
    return this.pinned === "left";
  }
  isPinnedRight() {
    return this.pinned === "right";
  }
  getPinned() {
    return this.pinned;
  }
  setVisible(visible, source) {
    const newValue = visible === true;
    if (this.visible !== newValue) {
      this.visible = newValue;
      this.eventService.dispatchEvent(this.createColumnEvent("visibleChanged", source));
    }
    this.dispatchStateUpdatedEvent("hide");
  }
  isVisible() {
    return this.visible;
  }
  isSpanHeaderHeight() {
    const colDef = this.getColDef();
    return !colDef.suppressSpanHeaderHeight && !colDef.autoHeaderHeight;
  }
  getColumnGroupPaddingInfo() {
    let parent = this.getParent();
    if (!parent || !parent.isPadding()) {
      return { numberOfParents: 0, isSpanningTotal: false };
    }
    const numberOfParents = parent.getPaddingLevel() + 1;
    let isSpanningTotal = true;
    while (parent) {
      if (!parent.isPadding()) {
        isSpanningTotal = false;
        break;
      }
      parent = parent.getParent();
    }
    return { numberOfParents, isSpanningTotal };
  }
  /** Returns the column definition for this column.
   * The column definition will be the result of merging the application provided column definition with any provided defaults
   * (e.g. `defaultColDef` grid option, or column types.
   *
   * Equivalent: `getDefinition` */
  getColDef() {
    return this.colDef;
  }
  getColumnGroupShow() {
    return this.colDef.columnGroupShow;
  }
  /**
   * Returns the unique ID for the column.
   *
   * Equivalent: `getId`, `getUniqueId` */
  getColId() {
    return this.colId;
  }
  /**
   * Returns the unique ID for the column.
   *
   * Equivalent: `getColId`, `getUniqueId` */
  getId() {
    return this.colId;
  }
  /**
   * Returns the unique ID for the column.
   *
   * Equivalent: `getColId`, `getId` */
  getUniqueId() {
    return this.colId;
  }
  getDefinition() {
    return this.colDef;
  }
  /** Returns the current width of the column. If the column is resized, the actual width is the new size. */
  getActualWidth() {
    return this.actualWidth;
  }
  getAutoHeaderHeight() {
    return this.autoHeaderHeight;
  }
  /** Returns true if the header height has changed */
  setAutoHeaderHeight(height) {
    const changed = height !== this.autoHeaderHeight;
    this.autoHeaderHeight = height;
    return changed;
  }
  createBaseColDefParams(rowNode) {
    const params = this.gos.addGridCommonParams({
      node: rowNode,
      data: rowNode.data,
      colDef: this.colDef,
      column: this
    });
    return params;
  }
  getColSpan(rowNode) {
    if (missing(this.colDef.colSpan)) {
      return 1;
    }
    const params = this.createBaseColDefParams(rowNode);
    const colSpan = this.colDef.colSpan(params);
    return Math.max(colSpan, 1);
  }
  getRowSpan(rowNode) {
    if (missing(this.colDef.rowSpan)) {
      return 1;
    }
    const params = this.createBaseColDefParams(rowNode);
    const rowSpan = this.colDef.rowSpan(params);
    return Math.max(rowSpan, 1);
  }
  setActualWidth(actualWidth, source, silent = false) {
    if (this.minWidth != null) {
      actualWidth = Math.max(actualWidth, this.minWidth);
    }
    if (this.maxWidth != null) {
      actualWidth = Math.min(actualWidth, this.maxWidth);
    }
    if (this.actualWidth !== actualWidth) {
      this.actualWidth = actualWidth;
      if (this.flex && source !== "flex" && source !== "gridInitializing") {
        this.flex = null;
      }
      if (!silent) {
        this.fireColumnWidthChangedEvent(source);
      }
    }
    this.dispatchStateUpdatedEvent("width");
  }
  fireColumnWidthChangedEvent(source) {
    this.eventService.dispatchEvent(this.createColumnEvent("widthChanged", source));
  }
  isGreaterThanMax(width) {
    if (this.maxWidth != null) {
      return width > this.maxWidth;
    }
    return false;
  }
  getMinWidth() {
    return this.minWidth;
  }
  getMaxWidth() {
    return this.maxWidth;
  }
  getFlex() {
    return this.flex || 0;
  }
  // this method should only be used by the columnModel to
  // change flex when required by the applyColumnState method.
  setFlex(flex) {
    if (this.flex !== flex) {
      this.flex = flex;
    }
    this.dispatchStateUpdatedEvent("flex");
  }
  setMinimum(source) {
    if (exists(this.minWidth)) {
      this.setActualWidth(this.minWidth, source);
    }
  }
  setRowGroupActive(rowGroup, source) {
    if (this.rowGroupActive !== rowGroup) {
      this.rowGroupActive = rowGroup;
      this.eventService.dispatchEvent(this.createColumnEvent("columnRowGroupChanged", source));
    }
    this.dispatchStateUpdatedEvent("rowGroup");
  }
  /** Returns `true` if row group is currently active for this column. */
  isRowGroupActive() {
    return this.rowGroupActive;
  }
  setPivotActive(pivot, source) {
    if (this.pivotActive !== pivot) {
      this.pivotActive = pivot;
      this.eventService.dispatchEvent(this.createColumnEvent("columnPivotChanged", source));
    }
    this.dispatchStateUpdatedEvent("pivot");
  }
  /** Returns `true` if pivot is currently active for this column. */
  isPivotActive() {
    return this.pivotActive;
  }
  isAnyFunctionActive() {
    return this.isPivotActive() || this.isRowGroupActive() || this.isValueActive();
  }
  isAnyFunctionAllowed() {
    return this.isAllowPivot() || this.isAllowRowGroup() || this.isAllowValue();
  }
  setValueActive(value, source) {
    if (this.aggregationActive !== value) {
      this.aggregationActive = value;
      this.eventService.dispatchEvent(this.createColumnEvent("columnValueChanged", source));
    }
  }
  /** Returns `true` if value (aggregation) is currently active for this column. */
  isValueActive() {
    return this.aggregationActive;
  }
  isAllowPivot() {
    return this.colDef.enablePivot === true;
  }
  isAllowValue() {
    return this.colDef.enableValue === true;
  }
  isAllowRowGroup() {
    return this.colDef.enableRowGroup === true;
  }
  /**
   * @deprecated v31.1 Use `getColDef().menuTabs ?? defaultValues` instead.
   */
  getMenuTabs(defaultValues) {
    warnOnce(`As of v31.1, 'getMenuTabs' is deprecated. Use 'getColDef().menuTabs ?? defaultValues' instead.`);
    let menuTabs = this.getColDef().menuTabs;
    if (menuTabs == null) {
      menuTabs = defaultValues;
    }
    return menuTabs;
  }
  dispatchStateUpdatedEvent(key) {
    this.eventService.dispatchEvent({
      type: _Column.EVENT_STATE_UPDATED,
      key
    });
  }
};
// + renderedHeaderCell - for making header cell transparent when moving
_Column.EVENT_MOVING_CHANGED = "movingChanged";
// + renderedCell - changing left position
_Column.EVENT_LEFT_CHANGED = "leftChanged";
// + renderedCell - changing width
_Column.EVENT_WIDTH_CHANGED = "widthChanged";
// + renderedCell - for changing pinned classes
_Column.EVENT_LAST_LEFT_PINNED_CHANGED = "lastLeftPinnedChanged";
_Column.EVENT_FIRST_RIGHT_PINNED_CHANGED = "firstRightPinnedChanged";
// + renderedColumn - for changing visibility icon
_Column.EVENT_VISIBLE_CHANGED = "visibleChanged";
// + every time the filter changes, used in the floating filters
_Column.EVENT_FILTER_CHANGED = "filterChanged";
// + renderedHeaderCell - marks the header with filter icon
_Column.EVENT_FILTER_ACTIVE_CHANGED = "filterActiveChanged";
// + renderedHeaderCell - marks the header with sort icon
_Column.EVENT_SORT_CHANGED = "sortChanged";
// + renderedHeaderCell - marks the header with sort icon
_Column.EVENT_COL_DEF_CHANGED = "colDefChanged";
_Column.EVENT_MENU_VISIBLE_CHANGED = "menuVisibleChanged";
// + toolpanel, for gui updates
_Column.EVENT_ROW_GROUP_CHANGED = "columnRowGroupChanged";
// + toolpanel, for gui updates
_Column.EVENT_PIVOT_CHANGED = "columnPivotChanged";
// + toolpanel, for gui updates
_Column.EVENT_VALUE_CHANGED = "columnValueChanged";
// + dataTypeService - when waiting to infer cell data types
_Column.EVENT_STATE_UPDATED = "columnStateUpdated";
__decorateClass([
  Autowired("gridOptionsService")
], _Column.prototype, "gos", 2);
__decorateClass([
  Autowired("environment")
], _Column.prototype, "environment", 2);
__decorateClass([
  Autowired("columnHoverService")
], _Column.prototype, "columnHoverService", 2);
__decorateClass([
  Autowired("frameworkOverrides")
], _Column.prototype, "frameworkOverrides", 2);
__decorateClass([
  PostConstruct
], _Column.prototype, "initialise", 1);
var Column = _Column;

// community-modules/core/src/entities/providedColumnGroup.ts
var _ProvidedColumnGroup = class _ProvidedColumnGroup {
  constructor(colGroupDef, groupId, padding, level) {
    this.localEventService = new EventService();
    this.expandable = false;
    // used by React (and possibly other frameworks) as key for rendering. also used to
    // identify old vs new columns for destroying cols when no longer used.
    this.instanceId = getNextColInstanceId();
    this.expandableListenerRemoveCallback = null;
    this.colGroupDef = colGroupDef;
    this.groupId = groupId;
    this.expanded = !!colGroupDef && !!colGroupDef.openByDefault;
    this.padding = padding;
    this.level = level;
  }
  destroy() {
    if (this.expandableListenerRemoveCallback) {
      this.reset(null, void 0);
    }
  }
  reset(colGroupDef, level) {
    this.colGroupDef = colGroupDef;
    this.level = level;
    this.originalParent = null;
    if (this.expandableListenerRemoveCallback) {
      this.expandableListenerRemoveCallback();
    }
    this.children = void 0;
    this.expandable = void 0;
  }
  getInstanceId() {
    return this.instanceId;
  }
  setOriginalParent(originalParent) {
    this.originalParent = originalParent;
  }
  getOriginalParent() {
    return this.originalParent;
  }
  getLevel() {
    return this.level;
  }
  isVisible() {
    if (this.children) {
      return this.children.some((child) => child.isVisible());
    }
    return false;
  }
  isPadding() {
    return this.padding;
  }
  setExpanded(expanded) {
    this.expanded = expanded === void 0 ? false : expanded;
    const event = {
      type: _ProvidedColumnGroup.EVENT_EXPANDED_CHANGED
    };
    this.localEventService.dispatchEvent(event);
  }
  isExpandable() {
    return this.expandable;
  }
  isExpanded() {
    return this.expanded;
  }
  getGroupId() {
    return this.groupId;
  }
  getId() {
    return this.getGroupId();
  }
  setChildren(children) {
    this.children = children;
  }
  getChildren() {
    return this.children;
  }
  getColGroupDef() {
    return this.colGroupDef;
  }
  getLeafColumns() {
    const result = [];
    this.addLeafColumns(result);
    return result;
  }
  addLeafColumns(leafColumns) {
    if (!this.children) {
      return;
    }
    this.children.forEach((child) => {
      if (child instanceof Column) {
        leafColumns.push(child);
      } else if (child instanceof _ProvidedColumnGroup) {
        child.addLeafColumns(leafColumns);
      }
    });
  }
  getColumnGroupShow() {
    const colGroupDef = this.colGroupDef;
    if (!colGroupDef) {
      return;
    }
    return colGroupDef.columnGroupShow;
  }
  // need to check that this group has at least one col showing when both expanded and contracted.
  // if not, then we don't allow expanding and contracting on this group
  setupExpandable() {
    this.setExpandable();
    if (this.expandableListenerRemoveCallback) {
      this.expandableListenerRemoveCallback();
    }
    const listener = this.onColumnVisibilityChanged.bind(this);
    this.getLeafColumns().forEach((col) => col.addEventListener("visibleChanged", listener));
    this.expandableListenerRemoveCallback = () => {
      this.getLeafColumns().forEach((col) => col.removeEventListener("visibleChanged", listener));
      this.expandableListenerRemoveCallback = null;
    };
  }
  setExpandable() {
    if (this.isPadding()) {
      return;
    }
    let atLeastOneShowingWhenOpen = false;
    let atLeastOneShowingWhenClosed = false;
    let atLeastOneChangeable = false;
    const children = this.findChildrenRemovingPadding();
    for (let i = 0, j = children.length; i < j; i++) {
      const abstractColumn = children[i];
      if (!abstractColumn.isVisible()) {
        continue;
      }
      const headerGroupShow = abstractColumn.getColumnGroupShow();
      if (headerGroupShow === "open") {
        atLeastOneShowingWhenOpen = true;
        atLeastOneChangeable = true;
      } else if (headerGroupShow === "closed") {
        atLeastOneShowingWhenClosed = true;
        atLeastOneChangeable = true;
      } else {
        atLeastOneShowingWhenOpen = true;
        atLeastOneShowingWhenClosed = true;
      }
    }
    const expandable = atLeastOneShowingWhenOpen && atLeastOneShowingWhenClosed && atLeastOneChangeable;
    if (this.expandable !== expandable) {
      this.expandable = expandable;
      const event = {
        type: _ProvidedColumnGroup.EVENT_EXPANDABLE_CHANGED
      };
      this.localEventService.dispatchEvent(event);
    }
  }
  findChildrenRemovingPadding() {
    const res = [];
    const process = (items) => {
      items.forEach((item) => {
        const skipBecausePadding = item instanceof _ProvidedColumnGroup && item.isPadding();
        if (skipBecausePadding) {
          process(item.children);
        } else {
          res.push(item);
        }
      });
    };
    process(this.children);
    return res;
  }
  onColumnVisibilityChanged() {
    this.setExpandable();
  }
  addEventListener(eventType, listener) {
    this.localEventService.addEventListener(eventType, listener);
  }
  removeEventListener(eventType, listener) {
    this.localEventService.removeEventListener(eventType, listener);
  }
};
_ProvidedColumnGroup.EVENT_EXPANDED_CHANGED = "expandedChanged";
_ProvidedColumnGroup.EVENT_EXPANDABLE_CHANGED = "expandableChanged";
__decorateClass([
  PreDestroy
], _ProvidedColumnGroup.prototype, "destroy", 1);
var ProvidedColumnGroup = _ProvidedColumnGroup;

// community-modules/core/src/entities/defaultColumnTypes.ts
var DefaultColumnTypes = {
  numericColumn: {
    headerClass: "ag-right-aligned-header",
    cellClass: "ag-right-aligned-cell"
  },
  rightAligned: {
    headerClass: "ag-right-aligned-header",
    cellClass: "ag-right-aligned-cell"
  }
};

// community-modules/core/src/utils/event.ts
var event_exports = {};
__export(event_exports, {
  addSafePassiveEventListener: () => addSafePassiveEventListener,
  createEventPath: () => createEventPath,
  getCtrlForEventTarget: () => getCtrlForEventTarget,
  getEventPath: () => getEventPath,
  isElementInEventPath: () => isElementInEventPath,
  isEventSupported: () => isEventSupported,
  isStopPropagationForAgGrid: () => isStopPropagationForAgGrid,
  stopPropagationForAgGrid: () => stopPropagationForAgGrid
});

// community-modules/core/src/utils/array.ts
var array_exports = {};
__export(array_exports, {
  areEqual: () => areEqual,
  existsAndNotEmpty: () => existsAndNotEmpty,
  flatten: () => flatten,
  forEachReverse: () => forEachReverse,
  includes: () => includes,
  insertArrayIntoArray: () => insertArrayIntoArray,
  insertIntoArray: () => insertIntoArray,
  last: () => last,
  moveInArray: () => moveInArray,
  pushAll: () => pushAll,
  removeAllFromArray: () => removeAllFromArray,
  removeAllFromUnorderedArray: () => removeAllFromUnorderedArray,
  removeFromArray: () => removeFromArray,
  removeFromUnorderedArray: () => removeFromUnorderedArray,
  removeRepeatsFromArray: () => removeRepeatsFromArray,
  shallowCompare: () => shallowCompare,
  sortNumerically: () => sortNumerically,
  toStrings: () => toStrings
});
function existsAndNotEmpty(value) {
  return value != null && value.length > 0;
}
function last(arr) {
  if (!arr || !arr.length) {
    return;
  }
  return arr[arr.length - 1];
}
function areEqual(a, b, comparator) {
  if (a == null && b == null) {
    return true;
  }
  return a != null && b != null && a.length === b.length && a.every((value, index) => comparator ? comparator(value, b[index]) : b[index] === value);
}
function shallowCompare(arr1, arr2) {
  return areEqual(arr1, arr2);
}
function sortNumerically(array) {
  return array.sort((a, b) => a - b);
}
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);
    }
  }
}
function removeFromUnorderedArray(array, object) {
  const index = array.indexOf(object);
  if (index >= 0) {
    array[index] = array[array.length - 1];
    array.pop();
  }
}
function removeFromArray(array, object) {
  const index = array.indexOf(object);
  if (index >= 0) {
    array.splice(index, 1);
  }
}
function removeAllFromUnorderedArray(array, toRemove) {
  for (let i = 0; i < toRemove.length; i++) {
    removeFromUnorderedArray(array, toRemove[i]);
  }
}
function removeAllFromArray(array, toRemove) {
  for (let i = 0; i < toRemove.length; i++) {
    removeFromArray(array, toRemove[i]);
  }
}
function insertIntoArray(array, object, toIndex) {
  array.splice(toIndex, 0, object);
}
function insertArrayIntoArray(dest, src, toIndex) {
  if (dest == null || src == null) {
    return;
  }
  for (let i = src.length - 1; i >= 0; i--) {
    const item = src[i];
    insertIntoArray(dest, item, toIndex);
  }
}
function moveInArray(array, objectsToMove, toIndex) {
  removeAllFromArray(array, objectsToMove);
  objectsToMove.slice().reverse().forEach((obj) => insertIntoArray(array, obj, toIndex));
}
function includes(array, value) {
  return array.indexOf(value) > -1;
}
function flatten(arrayOfArrays) {
  return [].concat.apply([], arrayOfArrays);
}
function pushAll(target, source) {
  if (source == null || target == null) {
    return;
  }
  source.forEach((value) => target.push(value));
}
function toStrings(array) {
  return array.map(toStringOrNull);
}
function forEachReverse(list, action) {
  if (list == null) {
    return;
  }
  for (let i = list.length - 1; i >= 0; i--) {
    action(list[i], i);
  }
}

// community-modules/core/src/utils/event.ts
var AG_GRID_STOP_PROPAGATION = "__ag_Grid_Stop_Propagation";
var PASSIVE_EVENTS = ["touchstart", "touchend", "touchmove", "touchcancel", "scroll"];
var supports = {};
function stopPropagationForAgGrid(event) {
  event[AG_GRID_STOP_PROPAGATION] = true;
}
function isStopPropagationForAgGrid(event) {
  return event[AG_GRID_STOP_PROPAGATION] === true;
}
var isEventSupported = /* @__PURE__ */ (() => {
  const tags = {
    select: "input",
    change: "input",
    submit: "form",
    reset: "form",
    error: "img",
    load: "img",
    abort: "img"
  };
  const eventChecker = (eventName) => {
    if (typeof supports[eventName] === "boolean") {
      return supports[eventName];
    }
    const el = document.createElement(tags[eventName] || "div");
    eventName = "on" + eventName;
    return supports[eventName] = eventName in el;
  };
  return eventChecker;
})();
function getCtrlForEventTarget(gos, eventTarget, type) {
  let sourceElement = eventTarget;
  while (sourceElement) {
    const renderedComp = gos.getDomData(sourceElement, type);
    if (renderedComp) {
      return renderedComp;
    }
    sourceElement = sourceElement.parentElement;
  }
  return null;
}
function isElementInEventPath(element, event) {
  if (!event || !element) {
    return false;
  }
  return getEventPath(event).indexOf(element) >= 0;
}
function createEventPath(event) {
  const res = [];
  let pointer = event.target;
  while (pointer) {
    res.push(pointer);
    pointer = pointer.parentElement;
  }
  return res;
}
function getEventPath(event) {
  const eventNoType = event;
  if (eventNoType.path) {
    return eventNoType.path;
  }
  if (eventNoType.composedPath) {
    return eventNoType.composedPath();
  }
  return createEventPath(eventNoType);
}
function addSafePassiveEventListener(frameworkOverrides, eElement, event, listener) {
  const isPassive = includes(PASSIVE_EVENTS, event);
  const options = isPassive ? { passive: true } : void 0;
  if (frameworkOverrides && frameworkOverrides.addEventListener) {
    frameworkOverrides.addEventListener(eElement, event, listener, options);
  }
}

// community-modules/core/src/context/beanStub.ts
var _BeanStub = class _BeanStub {
  constructor() {
    this.destroyFunctions = [];
    this.destroyed = false;
    // for vue 3 - prevents Vue from trying to make this (and obviously any sub classes) from being reactive
    // prevents vue from creating proxies for created objects and prevents identity related issues
    this.__v_skip = true;
    // this was a test constructor niall built, when active, it prints after 5 seconds all beans/components that are
    // not destroyed. to use, create a new grid, then api.destroy() before 5 seconds. then anything that gets printed
    // points to a bean or component that was not properly disposed of.
    // constructor() {
    //     setTimeout(()=> {
    //         if (this.isAlive()) {
    //             let prototype: any = Object.getPrototypeOf(this);
    //             const constructor: any = prototype.constructor;
    //             const constructorString = constructor.toString();
    //             const beanName = constructorString.substring(9, constructorString.indexOf("("));
    //             console.log('is alive ' + beanName);
    //         }
    //     }, 5000);
    // }
    // Enable multiple grid properties to be updated together by the user but only trigger shared logic once.
    // Closely related to logic in ComponentUtil.ts
    this.lastChangeSetIdLookup = {};
    this.propertyListenerId = 0;
    this.isAlive = () => !this.destroyed;
  }
  // CellComp and GridComp and override this because they get the FrameworkOverrides from the Beans bean
  getFrameworkOverrides() {
    return this.frameworkOverrides;
  }
  getContext() {
    return this.context;
  }
  destroy() {
    for (let i = 0; i < this.destroyFunctions.length; i++) {
      this.destroyFunctions[i]();
    }
    this.destroyFunctions.length = 0;
    this.destroyed = true;
    this.dispatchEvent({ type: _BeanStub.EVENT_DESTROYED });
  }
  addEventListener(eventType, listener) {
    if (!this.localEventService) {
      this.localEventService = new EventService();
    }
    this.localEventService.addEventListener(eventType, listener);
  }
  removeEventListener(eventType, listener) {
    if (this.localEventService) {
      this.localEventService.removeEventListener(eventType, listener);
    }
  }
  dispatchEvent(event) {
    if (this.localEventService) {
      this.localEventService.dispatchEvent(event);
    }
  }
  addManagedListener(object, event, listener) {
    if (this.destroyed) {
      return;
    }
    if (object instanceof HTMLElement) {
      addSafePassiveEventListener(this.getFrameworkOverrides(), object, event, listener);
    } else {
      object.addEventListener(event, listener);
    }
    const destroyFunc = () => {
      object.removeEventListener(event, listener);
      return null;
    };
    this.destroyFunctions.push(destroyFunc);
    return () => {
      destroyFunc();
      this.destroyFunctions = this.destroyFunctions.filter((fn) => fn !== destroyFunc);
      return null;
    };
  }
  setupGridOptionListener(event, listener) {
    this.gos.addEventListener(event, listener);
    const destroyFunc = () => {
      this.gos.removeEventListener(event, listener);
      return null;
    };
    this.destroyFunctions.push(destroyFunc);
    return () => {
      destroyFunc();
      this.destroyFunctions = this.destroyFunctions.filter((fn) => fn !== destroyFunc);
      return null;
    };
  }
  /**
   * Setup a managed property listener for the given GridOption property.
   * @param event GridOption property to listen to changes for.
   * @param listener Listener to run when property value changes
   */
  addManagedPropertyListener(event, listener) {
    if (this.destroyed) {
      return () => null;
    }
    return this.setupGridOptionListener(event, listener);
  }
  /**
   * Setup managed property listeners for the given set of GridOption properties.
   * The listener will be run if any of the property changes but will only run once if
   * multiple of the properties change within the same framework lifecycle event.
   * Works on the basis that GridOptionsService updates all properties *before* any property change events are fired.
   * @param events Array of GridOption properties to listen for changes too.
   * @param listener Shared listener to run if any of the properties change
   */
  addManagedPropertyListeners(events, listener) {
    if (this.destroyed) {
      return;
    }
    const eventsKey = events.join("-") + this.propertyListenerId++;
    const wrappedListener = (event) => {
      if (event.changeSet) {
        if (event.changeSet && event.changeSet.id === this.lastChangeSetIdLookup[eventsKey]) {
          return;
        }
        this.lastChangeSetIdLookup[eventsKey] = event.changeSet.id;
      }
      const propertiesChangeEvent = {
        type: "gridPropertyChanged",
        changeSet: event.changeSet,
        source: event.source
      };
      listener(propertiesChangeEvent);
    };
    events.forEach((event) => this.setupGridOptionListener(event, wrappedListener));
  }
  addDestroyFunc(func) {
    if (this.isAlive()) {
      this.destroyFunctions.push(func);
    } else {
      func();
    }
  }
  createManagedBean(bean, context) {
    const res = this.createBean(bean, context);
    this.addDestroyFunc(this.destroyBean.bind(this, bean, context));
    return res;
  }
  createBean(bean, context, afterPreCreateCallback) {
    return (context || this.getContext()).createBean(bean, afterPreCreateCallback);
  }
  destroyBean(bean, context) {
    return (context || this.getContext()).destroyBean(bean);
  }
  destroyBeans(beans, context) {
    if (beans) {
      for (let i = 0; i < beans.length; i++) {
        this.destroyBean(beans[i], context);
      }
    }
    return [];
  }
};
_BeanStub.EVENT_DESTROYED = "destroyed";
__decorateClass([
  Autowired("frameworkOverrides")
], _BeanStub.prototype, "frameworkOverrides", 2);
__decorateClass([
  Autowired("context")
], _BeanStub.prototype, "context", 2);
__decorateClass([
  Autowired("eventService")
], _BeanStub.prototype, "eventService", 2);
__decorateClass([
  Autowired("gridOptionsService")
], _BeanStub.prototype, "gos", 2);
__decorateClass([
  Autowired("localeService")
], _BeanStub.prototype, "localeService", 2);
__decorateClass([
  Autowired("environment")
], _BeanStub.prototype, "environment", 2);
__decorateClass([
  PreDestroy
], _BeanStub.prototype, "destroy", 1);
var BeanStub = _BeanStub;

// community-modules/core/src/columns/columnFactory.ts
var ColumnFactory = class extends BeanStub {
  setBeans(loggerFactory) {
    this.logger = loggerFactory.create("ColumnFactory");
  }
  createColumnTree(defs, primaryColumns, existingTree, source) {
    const columnKeyCreator = new ColumnKeyCreator();
    const { existingCols, existingGroups, existingColKeys } = this.extractExistingTreeData(existingTree);
    columnKeyCreator.addExistingKeys(existingColKeys);
    const unbalancedTree = this.recursivelyCreateColumns(
      defs,
      0,
      primaryColumns,
      existingCols,
      columnKeyCreator,
      existingGroups,
      source
    );
    const treeDept = this.findMaxDept(unbalancedTree, 0);
    this.logger.log("Number of levels for grouped columns is " + treeDept);
    const columnTree = this.balanceColumnTree(unbalancedTree, 0, treeDept, columnKeyCreator);
    const deptFirstCallback = (child, parent) => {
      if (child instanceof ProvidedColumnGroup) {
        child.setupExpandable();
      }
      child.setOriginalParent(parent);
    };
    depthFirstOriginalTreeSearch(null, columnTree, deptFirstCallback);
    return {
      columnTree,
      treeDept
    };
  }
  extractExistingTreeData(existingTree) {
    const existingCols = [];
    const existingGroups = [];
    const existingColKeys = [];
    if (existingTree) {
      depthFirstOriginalTreeSearch(null, existingTree, (item) => {
        if (item instanceof ProvidedColumnGroup) {
          const group = item;
          existingGroups.push(group);
        } else {
          const col = item;
          existingColKeys.push(col.getId());
          existingCols.push(col);
        }
      });
    }
    return { existingCols, existingGroups, existingColKeys };
  }
  createForAutoGroups(autoGroupCols, gridBalancedTree) {
    return autoGroupCols.map((col) => this.createAutoGroupTreeItem(gridBalancedTree, col));
  }
  createAutoGroupTreeItem(balancedColumnTree, column) {
    const dept = this.findDepth(balancedColumnTree);
    let nextChild = column;
    for (let i = dept - 1; i >= 0; i--) {
      const autoGroup = new ProvidedColumnGroup(
        null,
        `FAKE_PATH_${column.getId()}}_${i}`,
        true,
        i
      );
      this.createBean(autoGroup);
      autoGroup.setChildren([nextChild]);
      nextChild.setOriginalParent(autoGroup);
      nextChild = autoGroup;
    }
    if (dept === 0) {
      column.setOriginalParent(null);
    }
    return nextChild;
  }
  findDepth(balancedColumnTree) {
    let dept = 0;
    let pointer = balancedColumnTree;
    while (pointer && pointer[0] && pointer[0] instanceof ProvidedColumnGroup) {
      dept++;
      pointer = pointer[0].getChildren();
    }
    return dept;
  }
  balanceColumnTree(unbalancedTree, currentDept, columnDept, columnKeyCreator) {
    const result = [];
    for (let i = 0; i < unbalancedTree.length; i++) {
      const child = unbalancedTree[i];
      if (child instanceof ProvidedColumnGroup) {
        const originalGroup = child;
        const newChildren = this.balanceColumnTree(
          originalGroup.getChildren(),
          currentDept + 1,
          columnDept,
          columnKeyCreator
        );
        originalGroup.setChildren(newChildren);
        result.push(originalGroup);
      } else {
        let firstPaddedGroup;
        let currentPaddedGroup;
        for (let j = columnDept - 1; j >= currentDept; j--) {
          const newColId = columnKeyCreator.getUniqueKey(null, null);
          const colGroupDefMerged = this.createMergedColGroupDef(null);
          const paddedGroup = new ProvidedColumnGroup(colGroupDefMerged, newColId, true, currentDept);
          this.createBean(paddedGroup);
          if (currentPaddedGroup) {
            currentPaddedGroup.setChildren([paddedGroup]);
          }
          currentPaddedGroup = paddedGroup;
          if (!firstPaddedGroup) {
            firstPaddedGroup = currentPaddedGroup;
          }
        }
        if (firstPaddedGroup && currentPaddedGroup) {
          result.push(firstPaddedGroup);
          const hasGroups = unbalancedTree.some((leaf) => leaf instanceof ProvidedColumnGroup);
          if (hasGroups) {
            currentPaddedGroup.setChildren([child]);
            continue;
          } else {
            currentPaddedGroup.setChildren(unbalancedTree);
            break;
          }
        }
        result.push(child);
      }
    }
    return result;
  }
  findMaxDept(treeChildren, dept) {
    let maxDeptThisLevel = dept;
    for (let i = 0; i < treeChildren.length; i++) {
      const abstractColumn = treeChildren[i];
      if (abstractColumn instanceof ProvidedColumnGroup) {
        const originalGroup = abstractColumn;
        const newDept = this.findMaxDept(originalGroup.getChildren(), dept + 1);
        if (maxDeptThisLevel < newDept) {
          maxDeptThisLevel = newDept;
        }
      }
    }
    return maxDeptThisLevel;
  }
  recursivelyCreateColumns(defs, level, primaryColumns, existingColsCopy, columnKeyCreator, existingGroups, source) {
    if (!defs)
      return [];
    const result = new Array(defs.length);
    for (let i = 0; i < result.length; i++) {
      const def = defs[i];
      if (this.isColumnGroup(def)) {
        result[i] = this.createColumnGroup(
          primaryColumns,
          def,
          level,
          existingColsCopy,
          columnKeyCreator,
          existingGroups,
          source
        );
      } else {
        result[i] = this.createColumn(primaryColumns, def, existingColsCopy, columnKeyCreator, source);
      }
    }
    return result;
  }
  createColumnGroup(primaryColumns, colGroupDef, level, existingColumns, columnKeyCreator, existingGroups, source) {
    const colGroupDefMerged = this.createMergedColGroupDef(colGroupDef);
    const groupId = columnKeyCreator.getUniqueKey(colGroupDefMerged.groupId || null, null);
    const providedGroup = new ProvidedColumnGroup(colGroupDefMerged, groupId, false, level);
    this.createBean(providedGroup);
    const existingGroupAndIndex = this.findExistingGroup(colGroupDef, existingGroups);
    if (existingGroupAndIndex) {
      existingGroups.splice(existingGroupAndIndex.idx, 1);
    }
    let existingGroup = existingGroupAndIndex == null ? void 0 : existingGroupAndIndex.group;
    if (existingGroup) {
      providedGroup.setExpanded(existingGroup.isExpanded());
    }
    const children = this.recursivelyCreateColumns(
      colGroupDefMerged.children,
      level + 1,
      primaryColumns,
      existingColumns,
      columnKeyCreator,
      existingGroups,
      source
    );
    providedGroup.setChildren(children);
    return providedGroup;
  }
  createMergedColGroupDef(colGroupDef) {
    const colGroupDefMerged = {};
    Object.assign(colGroupDefMerged, this.gos.get("defaultColGroupDef"));
    Object.assign(colGroupDefMerged, colGroupDef);
    return colGroupDefMerged;
  }
  createColumn(primaryColumns, colDef, existingColsCopy, columnKeyCreator, source) {
    const existingColAndIndex = this.findExistingColumn(colDef, existingColsCopy);
    if (existingColAndIndex) {
      existingColsCopy == null ? void 0 : existingColsCopy.splice(existingColAndIndex.idx, 1);
    }
    let column = existingColAndIndex == null ? void 0 : existingColAndIndex.column;
    if (!column) {
      const colId = columnKeyCreator.getUniqueKey(colDef.colId, colDef.field);
      const colDefMerged = this.addColumnDefaultAndTypes(colDef, colId);
      column = new Column(colDefMerged, colDef, colId, primaryColumns);
      this.context.createBean(column);
    } else {
      const colDefMerged = this.addColumnDefaultAndTypes(colDef, column.getColId());
      column.setColDef(colDefMerged, colDef, source);
      this.applyColumnState(column, colDefMerged, source);
    }
    this.dataTypeService.addColumnListeners(column);
    return column;
  }
  applyColumnState(column, colDef, source) {
    const flex = attrToNumber(colDef.flex);
    if (flex !== void 0) {
      column.setFlex(flex);
    }
    const noFlexThisCol = column.getFlex() <= 0;
    if (noFlexThisCol) {
      const width = attrToNumber(colDef.width);
      if (width != null) {
        column.setActualWidth(width, source);
      } else {
        const widthBeforeUpdate = column.getActualWidth();
        column.setActualWidth(widthBeforeUpdate, source);
      }
    }
    if (colDef.sort !== void 0) {
      if (colDef.sort == "asc" || colDef.sort == "desc") {
        column.setSort(colDef.sort, source);
      } else {
        column.setSort(void 0, source);
      }
    }
    const sortIndex = attrToNumber(colDef.sortIndex);
    if (sortIndex !== void 0) {
      column.setSortIndex(sortIndex);
    }
    const hide = attrToBoolean(colDef.hide);
    if (hide !== void 0) {
      column.setVisible(!hide, source);
    }
    if (colDef.pinned !== void 0) {
      column.setPinned(colDef.pinned);
    }
  }
  findExistingColumn(newColDef, existingColsCopy) {
    if (!existingColsCopy)
      return void 0;
    for (let i = 0; i < existingColsCopy.length; i++) {
      const def = existingColsCopy[i].getUserProvidedColDef();
      if (!def)
        continue;
      const newHasId = newColDef.colId != null;
      if (newHasId) {
        if (existingColsCopy[i].getId() === newColDef.colId) {
          return { idx: i, column: existingColsCopy[i] };
        }
        continue;
      }
      const newHasField = newColDef.field != null;
      if (newHasField) {
        if (def.field === newColDef.field) {
          return { idx: i, column: existingColsCopy[i] };
        }
        continue;
      }
      if (def === newColDef) {
        return { idx: i, column: existingColsCopy[i] };
      }
    }
    return void 0;
  }
  findExistingGroup(newGroupDef, existingGroups) {
    const newHasId = newGroupDef.groupId != null;
    if (!newHasId) {
      return void 0;
    }
    for (let i = 0; i < existingGroups.length; i++) {
      const existingGroup = existingGroups[i];
      const existingDef = existingGroup.getColGroupDef();
      if (!existingDef) {
        continue;
      }
      if (existingGroup.getId() === newGroupDef.groupId) {
        return { idx: i, group: existingGroup };
      }
    }
    return void 0;
  }
  addColumnDefaultAndTypes(colDef, colId) {
    const res = {};
    const defaultColDef = this.gos.get("defaultColDef");
    mergeDeep(res, defaultColDef, false, true);
    const columnType = this.dataTypeService.updateColDefAndGetColumnType(res, colDef, colId);
    if (columnType) {
      this.assignColumnTypes(columnType, res);
    }
    mergeDeep(res, colDef, false, true);
    const autoGroupColDef = this.gos.get("autoGroupColumnDef");
    const isSortingCoupled = this.gos.isColumnsSortingCoupledToGroup();
    if (colDef.rowGroup && autoGroupColDef && isSortingCoupled) {
      mergeDeep(res, { sort: autoGroupColDef.sort, initialSort: autoGroupColDef.initialSort }, false, true);
    }
    this.dataTypeService.validateColDef(res);
    return res;
  }
  assignColumnTypes(typeKeys, colDefMerged) {
    if (!typeKeys.length) {
      return;
    }
    const allColumnTypes = Object.assign({}, DefaultColumnTypes);
    const userTypes = this.gos.get("columnTypes") || {};
    iterateObject(userTypes, (key, value) => {
      if (key in allColumnTypes) {
        console.warn(`AG Grid: the column type '${key}' is a default column type and cannot be overridden.`);
      } else {
        const colType = value;
        if (colType.type) {
          warnOnce(`Column type definitions 'columnTypes' with a 'type' attribute are not supported because a column type cannot refer to another column type. Only column definitions 'columnDefs' can use the 'type' attribute to refer to a column type.`);
        }
        allColumnTypes[key] = value;
      }
    });
    typeKeys.forEach((t) => {
      const typeColDef = allColumnTypes[t.trim()];
      if (typeColDef) {
        mergeDeep(colDefMerged, typeColDef, false, true);
      } else {
        console.warn("AG Grid: colDef.type '" + t + "' does not correspond to defined gridOptions.columnTypes");
      }
    });
  }
  // if object has children, we assume it's a group
  isColumnGroup(abstractColDef) {
    return abstractColDef.children !== void 0;
  }
};
__decorateClass([
  Autowired("dataTypeService")
], ColumnFactory.prototype, "dataTypeService", 2);
__decorateClass([
  __decorateParam(0, Qualifier("loggerFactory"))
], ColumnFactory.prototype, "setBeans", 1);
ColumnFactory = __decorateClass([
  Bean("columnFactory")
], ColumnFactory);
function depthFirstOriginalTreeSearch(parent, tree, callback) {
  if (!tree) {
    return;
  }
  for (let i = 0; i < tree.length; i++) {
    const child = tree[i];
    if (child instanceof ProvidedColumnGroup) {
      depthFirstOriginalTreeSearch(child, child.getChildren(), callback);
    }
    callback(child, parent);
  }
}

// community-modules/core/src/entities/columnGroup.ts
var _ColumnGroup = class _ColumnGroup {
  constructor(providedColumnGroup, groupId, partId, pinned) {
    // depends on the open/closed state of the group, only displaying columns are stored here
    this.displayedChildren = [];
    this.localEventService = new EventService();
    this.groupId = groupId;
    this.partId = partId;
    this.providedColumnGroup = providedColumnGroup;
    this.pinned = pinned;
  }
  // this is static, a it is used outside of this class
  static createUniqueId(groupId, instanceId) {
    return groupId + "_" + instanceId;
  }
  // as the user is adding and removing columns, the groups are recalculated.
  // this reset clears out all children, ready for children to be added again
  reset() {
    this.parent = null;
    this.children = null;
    this.displayedChildren = null;
  }
  getParent() {
    return this.parent;
  }
  setParent(parent) {
    this.parent = parent;
  }
  getUniqueId() {
    return _ColumnGroup.createUniqueId(this.groupId, this.partId);
  }
  isEmptyGroup() {
    return this.displayedChildren.length === 0;
  }
  isMoving() {
    const allLeafColumns = this.getProvidedColumnGroup().getLeafColumns();
    if (!allLeafColumns || allLeafColumns.length === 0) {
      return false;
    }
    return allLeafColumns.every((col) => col.isMoving());
  }
  checkLeft() {
    this.displayedChildren.forEach((child) => {
      if (child instanceof _ColumnGroup) {
        child.checkLeft();
      }
    });
    if (this.displayedChildren.length > 0) {
      if (this.gos.get("enableRtl")) {
        const lastChild = last(this.displayedChildren);
        const lastChildLeft = lastChild.getLeft();
        this.setLeft(lastChildLeft);
      } else {
        const firstChildLeft = this.displayedChildren[0].getLeft();
        this.setLeft(firstChildLeft);
      }
    } else {
      this.setLeft(null);
    }
  }
  getLeft() {
    return this.left;
  }
  getOldLeft() {
    return this.oldLeft;
  }
  setLeft(left) {
    this.oldLeft = this.left;
    if (this.left !== left) {
      this.left = left;
      this.localEventService.dispatchEvent(this.createAgEvent(_ColumnGroup.EVENT_LEFT_CHANGED));
    }
  }
  getPinned() {
    return this.pinned;
  }
  createAgEvent(type) {
    return { type };
  }
  addEventListener(eventType, listener) {
    this.localEventService.addEventListener(eventType, listener);
  }
  removeEventListener(eventType, listener) {
    this.localEventService.removeEventListener(eventType, listener);
  }
  getGroupId() {
    return this.groupId;
  }
  getPartId() {
    return this.partId;
  }
  isChildInThisGroupDeepSearch(wantedChild) {
    let result = false;
    this.children.forEach((foundChild) => {
      if (wantedChild === foundChild) {
        result = true;
      }
      if (foundChild instanceof _ColumnGroup) {
        if (foundChild.isChildInThisGroupDeepSearch(wantedChild)) {
          result = true;
        }
      }
    });
    return result;
  }
  getActualWidth() {
    let groupActualWidth = 0;
    if (this.displayedChildren) {
      this.displayedChildren.forEach((child) => {
        groupActualWidth += child.getActualWidth();
      });
    }
    return groupActualWidth;
  }
  isResizable() {
    if (!this.displayedChildren) {
      return false;
    }
    let result = false;
    this.displayedChildren.forEach((child) => {
      if (child.isResizable()) {
        result = true;
      }
    });
    return result;
  }
  getMinWidth() {
    let result = 0;
    this.displayedChildren.forEach((groupChild) => {
      result += groupChild.getMinWidth() || 0;
    });
    return result;
  }
  addChild(child) {
    if (!this.children) {
      this.children = [];
    }
    this.children.push(child);
  }
  getDisplayedChildren() {
    return this.displayedChildren;
  }
  getLeafColumns() {
    const result = [];
    this.addLeafColumns(result);
    return result;
  }
  getDisplayedLeafColumns() {
    const result = [];
    this.addDisplayedLeafColumns(result);
    return result;
  }
  getDefinition() {
    return this.providedColumnGroup.getColGroupDef();
  }
  getColGroupDef() {
    return this.providedColumnGroup.getColGroupDef();
  }
  isPadding() {
    return this.providedColumnGroup.isPadding();
  }
  isExpandable() {
    return this.providedColumnGroup.isExpandable();
  }
  isExpanded() {
    return this.providedColumnGroup.isExpanded();
  }
  setExpanded(expanded) {
    this.providedColumnGroup.setExpanded(expanded);
  }
  addDisplayedLeafColumns(leafColumns) {
    this.displayedChildren.forEach((child) => {
      if (child instanceof Column) {
        leafColumns.push(child);
      } else if (child instanceof _ColumnGroup) {
        child.addDisplayedLeafColumns(leafColumns);
      }
    });
  }
  addLeafColumns(leafColumns) {
    this.children.forEach((child) => {
      if (child instanceof Column) {
        leafColumns.push(child);
      } else if (child instanceof _ColumnGroup) {
        child.addLeafColumns(leafColumns);
      }
    });
  }
  getChildren() {
    return this.children;
  }
  getColumnGroupShow() {
    return this.providedColumnGroup.getColumnGroupShow();
  }
  getProvidedColumnGroup() {
    return this.providedColumnGroup;
  }
  getPaddingLevel() {
    const parent = this.getParent();
    if (!this.isPadding() || !parent || !parent.isPadding()) {
      return 0;
    }
    return 1 + parent.getPaddingLevel();
  }
  calculateDisplayedColumns() {
    this.displayedChildren = [];
    let parentWithExpansion = this;
    while (parentWithExpansion != null && parentWithExpansion.isPadding()) {
      parentWithExpansion = parentWithExpansion.getParent();
    }
    const isExpandable = parentWithExpansion ? parentWithExpansion.providedColumnGroup.isExpandable() : false;
    if (!isExpandable) {
      this.displayedChildren = this.children;
      this.localEventService.dispatchEvent(this.createAgEvent(_ColumnGroup.EVENT_DISPLAYED_CHILDREN_CHANGED));
      return;
    }
    this.children.forEach((child) => {
      const emptyGroup = child instanceof _ColumnGroup && (!child.displayedChildren || !child.displayedChildren.length);
      if (emptyGroup) {
        return;
      }
      const headerGroupShow = child.getColumnGroupShow();
      switch (headerGroupShow) {
        case "open":
          if (parentWithExpansion.providedColumnGroup.isExpanded()) {
            this.displayedChildren.push(child);
          }
          break;
        case "closed":
          if (!parentWithExpansion.providedColumnGroup.isExpanded()) {
            this.displayedChildren.push(child);
          }
          break;
        default:
          this.displayedChildren.push(child);
          break;
      }
    });
    this.localEventService.dispatchEvent(this.createAgEvent(_ColumnGroup.EVENT_DISPLAYED_CHILDREN_CHANGED));
  }
};
_ColumnGroup.EVENT_LEFT_CHANGED = "leftChanged";
_ColumnGroup.EVENT_DISPLAYED_CHILDREN_CHANGED = "displayedChildrenChanged";
__decorateClass([
  Autowired("gridOptionsService")
], _ColumnGroup.prototype, "gos", 2);
var ColumnGroup = _ColumnGroup;

// community-modules/core/src/eventKeys.ts
var Events = class {
  /*****************************  INTERNAL EVENTS: END ******************************************* */
};
/** Everything has changed with the columns. Either complete new set of columns set, or user called applyColumnState() */
/** @deprecated - grid no longer uses this, and setSate() also fires individual events */
Events.EVENT_COLUMN_EVERYTHING_CHANGED = "columnEverythingChanged";
/** User has set in new columns. */
Events.EVENT_NEW_COLUMNS_LOADED = "newColumnsLoaded";
/** The pivot mode flag was changed */
Events.EVENT_COLUMN_PIVOT_MODE_CHANGED = "columnPivotModeChanged";
/** Exceeded the pivot limit when generating columns */
Events.EVENT_PIVOT_MAX_COLUMNS_EXCEEDED = "pivotMaxColumnsExceeded";
/** A row group column was added, removed or order changed. */
Events.EVENT_COLUMN_ROW_GROUP_CHANGED = "columnRowGroupChanged";
/** expandAll / collapseAll was called from the api. */
Events.EVENT_EXPAND_COLLAPSE_ALL = "expandOrCollapseAll";
/** A pivot column was added, removed or order changed. */
Events.EVENT_COLUMN_PIVOT_CHANGED = "columnPivotChanged";
/** The list of grid columns has changed. */
Events.EVENT_GRID_COLUMNS_CHANGED = "gridColumnsChanged";
/** A value column was added, removed or agg function was changed. */
Events.EVENT_COLUMN_VALUE_CHANGED = "columnValueChanged";
/** A column was moved */
Events.EVENT_COLUMN_MOVED = "columnMoved";
/** One or more columns was shown / hidden */
Events.EVENT_COLUMN_VISIBLE = "columnVisible";
/** One or more columns was pinned / unpinned*/
Events.EVENT_COLUMN_PINNED = "columnPinned";
/** A column group was opened / closed */
Events.EVENT_COLUMN_GROUP_OPENED = "columnGroupOpened";
/** One or more columns was resized. If just one, the column in the event is set. */
Events.EVENT_COLUMN_RESIZED = "columnResized";
/** The list of displayed columns has changed, can result from columns open / close, column move, pivot, group, etc */
Events.EVENT_DISPLAYED_COLUMNS_CHANGED = "displayedColumnsChanged";
/** The grid option related to suppressing movable columns has changed */
Events.EVENT_SUPPRESS_COLUMN_MOVE_CHANGED = "suppressMovableColumns";
/** The grid option related to suppressing column group selection has changed */
Events.EVENT_SUPPRESS_MENU_HIDE_CHANGED = "suppressMenuHide";
/** The grid option related to suppressing movable columns has changed */
Events.EVENT_SUPPRESS_FIELD_DOT_NOTATION = "suppressFieldDotNotation";
/** The list of virtual columns has changed, results from viewport changing */
Events.EVENT_VIRTUAL_COLUMNS_CHANGED = "virtualColumnsChanged";
/** Column header mouse over */
Events.EVENT_COLUMN_HEADER_MOUSE_OVER = "columnHeaderMouseOver";
/** Column header mouse leave */
Events.EVENT_COLUMN_HEADER_MOUSE_LEAVE = "columnHeaderMouseLeave";
/** Column header clicked */
Events.EVENT_COLUMN_HEADER_CLICKED = "columnHeaderClicked";
/** Column header context menu event, such as right-click or context menu key press */
Events.EVENT_COLUMN_HEADER_CONTEXT_MENU = "columnHeaderContextMenu";
/** Async Transactions Executed */
Events.EVENT_ASYNC_TRANSACTIONS_FLUSHED = "asyncTransactionsFlushed";
/** A row group was opened / closed */
Events.EVENT_ROW_GROUP_OPENED = "rowGroupOpened";
/** Client-Side Row Model only. The client has updated data for the grid */
Events.EVENT_ROW_DATA_UPDATED = "rowDataUpdated";
/** The client has set new floating data into the grid */
Events.EVENT_PINNED_ROW_DATA_CHANGED = "pinnedRowDataChanged";
/** Range selection has changed */
Events.EVENT_RANGE_SELECTION_CHANGED = "rangeSelectionChanged";
/** Chart was created */
Events.EVENT_CHART_CREATED = "chartCreated";
/** Chart Range selection has changed */
Events.EVENT_CHART_RANGE_SELECTION_CHANGED = "chartRangeSelectionChanged";
/** Chart Options have changed */
Events.EVENT_CHART_OPTIONS_CHANGED = "chartOptionsChanged";
/** Chart was destroyed */
Events.EVENT_CHART_DESTROYED = "chartDestroyed";
/** For when the tool panel is shown / hidden */
Events.EVENT_TOOL_PANEL_VISIBLE_CHANGED = "toolPanelVisibleChanged";
Events.EVENT_TOOL_PANEL_SIZE_CHANGED = "toolPanelSizeChanged";
Events.EVENT_COLUMN_PANEL_ITEM_DRAG_START = "columnPanelItemDragStart";
Events.EVENT_COLUMN_PANEL_ITEM_DRAG_END = "columnPanelItemDragEnd";
/** Model was updated - grid updates the drawn rows when this happens */
Events.EVENT_MODEL_UPDATED = "modelUpdated";
Events.EVENT_CUT_START = "cutStart";
Events.EVENT_CUT_END = "cutEnd";
Events.EVENT_PASTE_START = "pasteStart";
Events.EVENT_PASTE_END = "pasteEnd";
Events.EVENT_FILL_START = "fillStart";
Events.EVENT_FILL_END = "fillEnd";
Events.EVENT_RANGE_DELETE_START = "rangeDeleteStart";
Events.EVENT_RANGE_DELETE_END = "rangeDeleteEnd";
/** Undo operation has started. */
Events.EVENT_UNDO_STARTED = "undoStarted";
/** Undo operation has ended. */
Events.EVENT_UNDO_ENDED = "undoEnded";
/** Redo operation has started. */
Events.EVENT_REDO_STARTED = "redoStarted";
/** Redo operation has ended. */
Events.EVENT_REDO_ENDED = "redoEnded";
Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_START = "keyShortcutChangedCellStart";
Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_END = "keyShortcutChangedCellEnd";
Events.EVENT_CELL_CLICKED = "cellClicked";
Events.EVENT_CELL_DOUBLE_CLICKED = "cellDoubleClicked";
Events.EVENT_CELL_MOUSE_DOWN = "cellMouseDown";
Events.EVENT_CELL_CONTEXT_MENU = "cellContextMenu";
Events.EVENT_CELL_VALUE_CHANGED = "cellValueChanged";
Events.EVENT_CELL_EDIT_REQUEST = "cellEditRequest";
Events.EVENT_ROW_VALUE_CHANGED = "rowValueChanged";
Events.EVENT_CELL_FOCUSED = "cellFocused";
Events.EVENT_CELL_FOCUS_CLEARED = "cellFocusCleared";
Events.EVENT_FULL_WIDTH_ROW_FOCUSED = "fullWidthRowFocused";
Events.EVENT_ROW_SELECTED = "rowSelected";
Events.EVENT_SELECTION_CHANGED = "selectionChanged";
Events.EVENT_TOOLTIP_SHOW = "tooltipShow";
Events.EVENT_TOOLTIP_HIDE = "tooltipHide";
Events.EVENT_CELL_KEY_DOWN = "cellKeyDown";
Events.EVENT_CELL_MOUSE_OVER = "cellMouseOver";
Events.EVENT_CELL_MOUSE_OUT = "cellMouseOut";
/** 2 events for filtering. The grid LISTENS for filterChanged and afterFilterChanged */
Events.EVENT_FILTER_CHANGED = "filterChanged";
/** Filter was change but not applied. Only useful if apply buttons are used in filters. */
Events.EVENT_FILTER_MODIFIED = "filterModified";
Events.EVENT_FILTER_OPENED = "filterOpened";
Events.EVENT_ADVANCED_FILTER_BUILDER_VISIBLE_CHANGED = "advancedFilterBuilderVisibleChanged";
Events.EVENT_SORT_CHANGED = "sortChanged";
/** A row was removed from the dom, for any reason. Use to clean up resources (if any) used by the row. */
Events.EVENT_VIRTUAL_ROW_REMOVED = "virtualRowRemoved";
Events.EVENT_ROW_CLICKED = "rowClicked";
Events.EVENT_ROW_DOUBLE_CLICKED = "rowDoubleClicked";
/** Gets called once after the grid has finished initialising. */
Events.EVENT_GRID_READY = "gridReady";
/** Called once when the grid is about to get destroyed. */
Events.EVENT_GRID_PRE_DESTROYED = "gridPreDestroyed";
/** Width of height of the main grid div has changed. Grid listens for this and does layout of grid if it's
 * changed, so always filling the space it was given. */
Events.EVENT_GRID_SIZE_CHANGED = "gridSizeChanged";
/** The indexes of the rows rendered has changed, eg user has scrolled to a new vertical position. */
Events.EVENT_VIEWPORT_CHANGED = "viewportChanged";
/* The width of the scrollbar has been calculated */
Events.EVENT_SCROLLBAR_WIDTH_CHANGED = "scrollbarWidthChanged";
/** Rows were rendered for the first time (ie on async data load). */
Events.EVENT_FIRST_DATA_RENDERED = "firstDataRendered";
/** A column drag has started, either resizing a column or moving a column. */
Events.EVENT_DRAG_STARTED = "dragStarted";
/** A column drag has stopped */
Events.EVENT_DRAG_STOPPED = "dragStopped";
Events.EVENT_CHECKBOX_CHANGED = "checkboxChanged";
Events.EVENT_ROW_EDITING_STARTED = "rowEditingStarted";
Events.EVENT_ROW_EDITING_STOPPED = "rowEditingStopped";
Events.EVENT_CELL_EDITING_STARTED = "cellEditingStarted";
Events.EVENT_CELL_EDITING_STOPPED = "cellEditingStopped";
/** Main body of grid has scrolled, either horizontally or vertically */
Events.EVENT_BODY_SCROLL = "bodyScroll";
/** Main body of the grid has stopped scrolling, either horizontally or vertically */
Events.EVENT_BODY_SCROLL_END = "bodyScrollEnd";
Events.EVENT_HEIGHT_SCALE_CHANGED = "heightScaleChanged";
/** The displayed page for pagination has changed. For example the data was filtered or sorted,
 * or the user has moved to a different page. */
Events.EVENT_PAGINATION_CHANGED = "paginationChanged";
/** Only used by React, Angular, Web Components and VueJS AG Grid components
 * (not used if doing plain JavaScript). If the grid receives changes due
 * to bound properties, this event fires after the grid has finished processing the change. */
Events.EVENT_COMPONENT_STATE_CHANGED = "componentStateChanged";
/** Only used by the SSRM, called when the grid has no more rows to refresh */
Events.EVENT_STORE_REFRESHED = "storeRefreshed";
Events.EVENT_STATE_UPDATED = "stateUpdated";
/** The visibility of the column menu has changed. */
Events.EVENT_COLUMN_MENU_VISIBLE_CHANGED = "columnMenuVisibleChanged";
/** The visibility of the context menu has changed. */
Events.EVENT_CONTEXT_MENU_VISIBLE_CHANGED = "contextMenuVisibleChanged";
/*****************************  INTERNAL EVENTS: START ******************************************* */
/** Please remember to add to ComponentUtil.EXCLUDED_INTERNAL_EVENTS to not have these events exposed to framework components. */
/** All items from here down are used internally by the grid, not intended for external use. */
// not documented, either experimental, or we just don't want users using an depending on them
Events.EVENT_BODY_HEIGHT_CHANGED = "bodyHeightChanged";
Events.EVENT_COLUMN_CONTAINER_WIDTH_CHANGED = "columnContainerWidthChanged";
Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED = "displayedColumnsWidthChanged";
Events.EVENT_SCROLL_VISIBILITY_CHANGED = "scrollVisibilityChanged";
Events.EVENT_COLUMN_HOVER_CHANGED = "columnHoverChanged";
Events.EVENT_FLASH_CELLS = "flashCells";
Events.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED = "paginationPixelOffsetChanged";
Events.EVENT_DISPLAYED_ROWS_CHANGED = "displayedRowsChanged";
Events.EVENT_LEFT_PINNED_WIDTH_CHANGED = "leftPinnedWidthChanged";
Events.EVENT_RIGHT_PINNED_WIDTH_CHANGED = "rightPinnedWidthChanged";
Events.EVENT_ROW_CONTAINER_HEIGHT_CHANGED = "rowContainerHeightChanged";
Events.EVENT_HEADER_HEIGHT_CHANGED = "headerHeightChanged";
Events.EVENT_COLUMN_HEADER_HEIGHT_CHANGED = "columnHeaderHeightChanged";
Events.EVENT_ROW_DRAG_ENTER = "rowDragEnter";
Events.EVENT_ROW_DRAG_MOVE = "rowDragMove";
Events.EVENT_ROW_DRAG_LEAVE = "rowDragLeave";
Events.EVENT_ROW_DRAG_END = "rowDragEnd";
// environment
Events.EVENT_GRID_STYLES_CHANGED = "gridStylesChanged";
// these are used for server side group and agg - only used by CS with Viewport Row Model - intention is
// to design these better around server side functions and then release to general public when fully working with
// all the row models.
Events.EVENT_COLUMN_ROW_GROUP_CHANGE_REQUEST = "columnRowGroupChangeRequest";
Events.EVENT_COLUMN_PIVOT_CHANGE_REQUEST = "columnPivotChangeRequest";
Events.EVENT_COLUMN_VALUE_CHANGE_REQUEST = "columnValueChangeRequest";
Events.EVENT_COLUMN_AGG_FUNC_CHANGE_REQUEST = "columnAggFuncChangeRequest";
Events.EVENT_STORE_UPDATED = "storeUpdated";
Events.EVENT_FILTER_DESTROYED = "filterDestroyed";
Events.EVENT_ROW_DATA_UPDATE_STARTED = "rowDataUpdateStarted";
Events.EVENT_ROW_COUNT_READY = "rowCountReady";
// Advanced Filters
Events.EVENT_ADVANCED_FILTER_ENABLED_CHANGED = "advancedFilterEnabledChanged";
Events.EVENT_DATA_TYPES_INFERRED = "dataTypesInferred";
// Widgets
Events.EVENT_FIELD_VALUE_CHANGED = "fieldValueChanged";
Events.EVENT_FIELD_PICKER_VALUE_SELECTED = "fieldPickerValueSelected";
Events.EVENT_SIDE_BAR_UPDATED = "sideBarUpdated";

// community-modules/core/src/events.ts
var ALWAYS_SYNC_GLOBAL_EVENTS = /* @__PURE__ */ new Set([Events.EVENT_GRID_PRE_DESTROYED, Events.EVENT_FILL_START]);

// community-modules/core/src/columns/groupInstanceIdCreator.ts
var GroupInstanceIdCreator = class {
  constructor() {
    // this map contains keys to numbers, so we remember what the last call was
    this.existingIds = {};
  }
  getInstanceIdForKey(key) {
    const lastResult = this.existingIds[key];
    let result;
    if (typeof lastResult !== "number") {
      result = 0;
    } else {
      result = lastResult + 1;
    }
    this.existingIds[key] = result;
    return result;
  }
};

// community-modules/core/src/columns/autoGroupColService.ts
var GROUP_AUTO_COLUMN_ID = "ag-Grid-AutoColumn";
var AutoGroupColService = class extends BeanStub {
  createAutoGroupColumns(rowGroupColumns) {
    const groupAutoColumns = [];
    const doingTreeData = this.gos.get("treeData");
    let doingMultiAutoColumn = this.gos.isGroupMultiAutoColumn();
    if (doingTreeData && doingMultiAutoColumn) {
      console.warn('AG Grid: you cannot mix groupDisplayType = "multipleColumns" with treeData, only one column can be used to display groups when doing tree data');
      doingMultiAutoColumn = false;
    }
    if (doingMultiAutoColumn) {
      rowGroupColumns.forEach((rowGroupCol, index) => {
        groupAutoColumns.push(this.createOneAutoGroupColumn(rowGroupCol, index));
      });
    } else {
      groupAutoColumns.push(this.createOneAutoGroupColumn());
    }
    return groupAutoColumns;
  }
  updateAutoGroupColumns(autoGroupColumns, source) {
    autoGroupColumns.forEach((column, index) => this.updateOneAutoGroupColumn(column, index, source));
  }
  // rowGroupCol and index are missing if groupDisplayType != "multipleColumns"
  createOneAutoGroupColumn(rowGroupCol, index) {
    let colId;
    if (rowGroupCol) {
      colId = `${GROUP_AUTO_COLUMN_ID}-${rowGroupCol.getId()}`;
    } else {
      colId = GROUP_AUTO_COLUMN_ID;
    }
    const colDef = this.createAutoGroupColDef(colId, rowGroupCol, index);
    colDef.colId = colId;
    const newCol = new Column(colDef, null, colId, true);
    this.context.createBean(newCol);
    return newCol;
  }
  /**
   * Refreshes an auto group col to load changes from defaultColDef or autoGroupColDef
   */
  updateOneAutoGroupColumn(colToUpdate, index, source) {
    const oldColDef = colToUpdate.getColDef();
    const underlyingColId = typeof oldColDef.showRowGroup == "string" ? oldColDef.showRowGroup : void 0;
    const underlyingColumn = underlyingColId != null ? this.columnModel.getPrimaryColumn(underlyingColId) : void 0;
    const colDef = this.createAutoGroupColDef(colToUpdate.getId(), underlyingColumn != null ? underlyingColumn : void 0, index);
    colToUpdate.setColDef(colDef, null, source);
    this.columnFactory.applyColumnState(colToUpdate, colDef, source);
  }
  createAutoGroupColDef(colId, underlyingColumn, index) {
    let res = this.createBaseColDef(underlyingColumn);
    const autoGroupColumnDef = this.gos.get("autoGroupColumnDef");
    mergeDeep(res, autoGroupColumnDef);
    res = this.columnFactory.addColumnDefaultAndTypes(res, colId);
    if (!this.gos.get("treeData")) {
      const noFieldOrValueGetter = missing(res.field) && missing(res.valueGetter) && missing(res.filterValueGetter) && res.filter !== "agGroupColumnFilter";
      if (noFieldOrValueGetter) {
        res.filter = false;
      }
    }
    if (index && index > 0) {
      res.headerCheckboxSelection = false;
    }
    const isSortingCoupled = this.gos.isColumnsSortingCoupledToGroup();
    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.localeService.getLocaleTextFunc();
    const res = {
      headerName: localeTextFunc("group", "Group")
    };
    const userHasProvidedGroupCellRenderer = userDef && (userDef.cellRenderer || userDef.cellRendererSelector);
    if (!userHasProvidedGroupCellRenderer) {
      res.cellRenderer = "agGroupCellRenderer";
    }
    if (rowGroupCol) {
      const colDef = rowGroupCol.getColDef();
      Object.assign(res, {
        // cellRendererParams.groupKey: colDefToCopy.field;
        headerName: this.columnModel.getDisplayNameForColumn(rowGroupCol, "header"),
        headerValueGetter: colDef.headerValueGetter
      });
      if (colDef.cellRenderer) {
        Object.assign(res, {
          cellRendererParams: {
            innerRenderer: colDef.cellRenderer,
            innerRendererParams: colDef.cellRendererParams
          }
        });
      }
      res.showRowGroup = rowGroupCol.getColId();
    } else {
      res.showRowGroup = true;
    }
    return res;
  }
};
__decorateClass([
  Autowired("columnModel")
], AutoGroupColService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("columnFactory")
], AutoGroupColService.prototype, "columnFactory", 2);
AutoGroupColService = __decorateClass([
  Bean("autoGroupColService")
], AutoGroupColService);

// community-modules/core/src/utils/string.ts
var string_exports = {};
__export(string_exports, {
  camelCaseToHumanText: () => camelCaseToHumanText,
  camelCaseToHyphenated: () => camelCaseToHyphenated,
  capitalise: () => capitalise,
  escapeString: () => escapeString,
  utf8_encode: () => utf8_encode
});
var reUnescapedHtml = /[&<>"']/g;
var HTML_ESCAPES = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
function utf8_encode(s) {
  const stringFromCharCode = String.fromCharCode;
  function ucs2decode(string) {
    const output = [];
    if (!string) {
      return [];
    }
    const len = string.length;
    let counter = 0;
    let value;
    let extra;
    while (counter < len) {
      value = string.charCodeAt(counter++);
      if (value >= 55296 && value <= 56319 && counter < len) {
        extra = string.charCodeAt(counter++);
        if ((extra & 64512) == 56320) {
          output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
        } else {
          output.push(value);
          counter--;
        }
      } else {
        output.push(value);
      }
    }
    return output;
  }
  function checkScalarValue(point) {
    if (point >= 55296 && point <= 57343) {
      throw Error(
        "Lone surrogate U+" + point.toString(16).toUpperCase() + " is not a scalar value"
      );
    }
  }
  function createByte(point, shift) {
    return stringFromCharCode(point >> shift & 63 | 128);
  }
  function encodeCodePoint(point) {
    if (point >= 0 && point <= 31 && point !== 10) {
      const convertedCode = point.toString(16).toUpperCase();
      const paddedCode = convertedCode.padStart(4, "0");
      return `_x${paddedCode}_`;
    }
    if ((point & 4294967168) == 0) {
      return stringFromCharCode(point);
    }
    let symbol = "";
    if ((point & 4294965248) == 0) {
      symbol = stringFromCharCode(point >> 6 & 31 | 192);
    } else if ((point & 4294901760) == 0) {
      checkScalarValue(point);
      symbol = stringFromCharCode(point >> 12 & 15 | 224);
      symbol += createByte(point, 6);
    } else if ((point & 4292870144) == 0) {
      symbol = stringFromCharCode(point >> 18 & 7 | 240);
      symbol += createByte(point, 12);
      symbol += createByte(point, 6);
    }
    symbol += stringFromCharCode(point & 63 | 128);
    return symbol;
  }
  const codePoints = ucs2decode(s);
  const length = codePoints.length;
  let index = -1;
  let codePoint;
  let byteString = "";
  while (++index < length) {
    codePoint = codePoints[index];
    byteString += encodeCodePoint(codePoint);
  }
  return byteString;
}
function capitalise(str) {
  return str[0].toUpperCase() + str.substring(1).toLowerCase();
}
function escapeString(toEscape, skipEscapingHtmlChars) {
  if (toEscape == null) {
    return null;
  }
  const stringResult = toEscape.toString().toString();
  if (skipEscapingHtmlChars) {
    return stringResult;
  }
  return stringResult.replace(reUnescapedHtml, (chr) => HTML_ESCAPES[chr]);
}
function camelCaseToHumanText(camelCase) {
  if (!camelCase || camelCase == null) {
    return null;
  }
  const rex = /([a-z])([A-Z])/g;
  const rexCaps = /([A-Z]+)([A-Z])([a-z])/g;
  const words = camelCase.replace(rex, "$1 $2").replace(rexCaps, "$1 $2$3").replace(/\./g, " ").split(" ");
  return words.map((word) => word.substring(0, 1).toUpperCase() + (word.length > 1 ? word.substring(1, word.length) : "")).join(" ");
}
function camelCaseToHyphenated(camelCase) {
  return camelCase.replace(/[A-Z]/g, (s) => `-${s.toLocaleLowerCase()}`);
}

// community-modules/core/src/utils/map.ts
var map_exports = {};
__export(map_exports, {
  convertToMap: () => convertToMap,
  keys: () => keys,
  mapById: () => mapById
});
function convertToMap(arr) {
  const map = /* @__PURE__ */ new Map();
  arr.forEach((pair) => map.set(pair[0], pair[1]));
  return map;
}
function mapById(arr, callback) {
  const map = /* @__PURE__ */ new Map();
  arr.forEach((item) => map.set(callback(item), item));
  return map;
}
function keys(map) {
  const arr = [];
  map.forEach((_2, key) => arr.push(key));
  return arr;
}

// community-modules/core/src/columns/columnModel.ts
var ColumnModel = class extends BeanStub {
  constructor() {
    super(...arguments);
    // header row count, based on user provided columns
    this.primaryHeaderRowCount = 0;
    this.secondaryHeaderRowCount = 0;
    // header row count, either above, or based on pivoting if we are pivoting
    this.gridHeaderRowCount = 0;
    // leave level columns of the displayed trees
    this.displayedColumnsLeft = [];
    this.displayedColumnsRight = [];
    this.displayedColumnsCenter = [];
    // all three lists above combined
    this.displayedColumns = [];
    // for fast lookup, to see if a column or group is still displayed
    this.displayedColumnsAndGroupsMap = {};
    // all columns to be rendered
    this.viewportColumns = [];
    // A hash key to keep track of changes in viewport columns
    this.viewportColumnsHash = "";
    // same as viewportColumns, except we always include columns with headerAutoHeight
    this.headerViewportColumns = [];
    // all columns to be rendered in the centre
    this.viewportColumnsCenter = [];
    // same as viewportColumnsCenter, except we always include columns with headerAutoHeight
    this.headerViewportColumnsCenter = [];
    // all columns & groups to be rendered, index by row. used by header rows to get all items
    // to render for that row.
    this.viewportRowLeft = {};
    this.viewportRowRight = {};
    this.viewportRowCenter = {};
    this.autoHeightActiveAtLeastOnce = false;
    this.rowGroupColumns = [];
    this.valueColumns = [];
    this.pivotColumns = [];
    this.ready = false;
    this.changeEventsDispatching = false;
    this.autoGroupsNeedBuilding = false;
    this.forceRecreateAutoGroups = false;
    this.pivotMode = false;
    this.bodyWidth = 0;
    this.leftWidth = 0;
    this.rightWidth = 0;
    this.bodyWidthDirty = true;
    // when we're waiting for cell data types to be inferred, we need to defer column resizing
    this.shouldQueueResizeOperations = false;
    this.resizeOperationQueue = [];
  }
  init() {
    this.suppressColumnVirtualisation = this.gos.get("suppressColumnVirtualisation");
    const pivotMode = this.gos.get("pivotMode");
    if (this.isPivotSettingAllowed(pivotMode)) {
      this.pivotMode = pivotMode;
    }
    this.addManagedPropertyListeners(["groupDisplayType", "treeData", "treeDataDisplayType", "groupHideOpenParents"], (event) => this.buildAutoGroupColumns(convertSourceType(event.source)));
    this.addManagedPropertyListener("autoGroupColumnDef", (event) => this.onAutoGroupColumnDefChanged(convertSourceType(event.source)));
    this.addManagedPropertyListeners(["defaultColDef", "columnTypes", "suppressFieldDotNotation"], (event) => this.onSharedColDefChanged(convertSourceType(event.source)));
    this.addManagedPropertyListener("pivotMode", (event) => this.setPivotMode(this.gos.get("pivotMode"), convertSourceType(event.source)));
    this.addManagedListener(this.eventService, Events.EVENT_FIRST_DATA_RENDERED, () => this.onFirstDataRendered());
  }
  buildAutoGroupColumns(source) {
    if (!this.columnDefs) {
      return;
    }
    this.autoGroupsNeedBuilding = true;
    this.forceRecreateAutoGroups = true;
    this.updateGridColumns();
    this.updateDisplayedColumns(source);
  }
  onAutoGroupColumnDefChanged(source) {
    if (this.groupAutoColumns) {
      this.autoGroupColService.updateAutoGroupColumns(this.groupAutoColumns, source);
    }
  }
  onSharedColDefChanged(source) {
    if (!this.gridColumns) {
      return;
    }
    if (this.groupAutoColumns) {
      this.autoGroupColService.updateAutoGroupColumns(this.groupAutoColumns, source);
    }
    this.createColumnsFromColumnDefs(true, source);
  }
  setColumnDefs(columnDefs, source) {
    const colsPreviouslyExisted = !!this.columnDefs;
    this.columnDefs = columnDefs;
    this.createColumnsFromColumnDefs(colsPreviouslyExisted, source);
  }
  recreateColumnDefs(source) {
    this.onSharedColDefChanged(source);
  }
  destroyOldColumns(oldTree, newTree) {
    const oldObjectsById = {};
    if (!oldTree) {
      return;
    }
    depthFirstOriginalTreeSearch(null, oldTree, (child) => {
      oldObjectsById[child.getInstanceId()] = child;
    });
    if (newTree) {
      depthFirstOriginalTreeSearch(null, newTree, (child) => {
        oldObjectsById[child.getInstanceId()] = null;
      });
    }
    const colsToDestroy = Object.values(oldObjectsById).filter((item) => item != null);
    this.destroyBeans(colsToDestroy);
  }
  destroyColumns() {
    this.destroyOldColumns(this.primaryColumnTree);
    this.destroyOldColumns(this.secondaryBalancedTree);
    this.destroyOldColumns(this.groupAutoColsBalancedTree);
  }
  createColumnsFromColumnDefs(colsPreviouslyExisted, source) {
    const dispatchEventsFunc = colsPreviouslyExisted ? this.compareColumnStatesAndDispatchEvents(source) : void 0;
    this.valueCache.expire();
    this.autoGroupsNeedBuilding = true;
    const oldPrimaryColumns = this.primaryColumns;
    const oldPrimaryTree = this.primaryColumnTree;
    const balancedTreeResult = this.columnFactory.createColumnTree(this.columnDefs, true, oldPrimaryTree, source);
    this.destroyOldColumns(this.primaryColumnTree, balancedTreeResult.columnTree);
    this.primaryColumnTree = balancedTreeResult.columnTree;
    this.primaryHeaderRowCount = balancedTreeResult.treeDept + 1;
    this.primaryColumns = this.getColumnsFromTree(this.primaryColumnTree);
    this.primaryColumnsMap = {};
    this.primaryColumns.forEach((col) => this.primaryColumnsMap[col.getId()] = col);
    this.extractRowGroupColumns(source, oldPrimaryColumns);
    this.extractPivotColumns(source, oldPrimaryColumns);
    this.extractValueColumns(source, oldPrimaryColumns);
    this.ready = true;
    const gridColsNotProcessed = this.gridColsArePrimary === void 0;
    const processGridCols = this.gridColsArePrimary || gridColsNotProcessed || this.autoGroupsNeedBuilding;
    if (processGridCols) {
      this.updateGridColumns();
      if (colsPreviouslyExisted && this.gridColsArePrimary && !this.gos.get("maintainColumnOrder")) {
        this.orderGridColumnsLikePrimary();
      }
      this.updateDisplayedColumns(source);
      this.checkViewportColumns();
    }
    this.dispatchEverythingChanged(source);
    this.changeEventsDispatching = true;
    if (dispatchEventsFunc) {
      dispatchEventsFunc();
    }
    this.changeEventsDispatching = false;
    this.dispatchNewColumnsLoaded(source);
  }
  shouldRowModelIgnoreRefresh() {
    return this.changeEventsDispatching;
  }
  dispatchNewColumnsLoaded(source) {
    const newColumnsLoadedEvent = {
      type: Events.EVENT_NEW_COLUMNS_LOADED,
      source
    };
    this.eventService.dispatchEvent(newColumnsLoadedEvent);
    if (source === "gridInitializing") {
      this.onColumnsReady();
    }
  }
  // this event is legacy, no grid code listens to it. instead the grid listens to New Columns Loaded
  dispatchEverythingChanged(source) {
    const eventEverythingChanged = {
      type: Events.EVENT_COLUMN_EVERYTHING_CHANGED,
      source
    };
    this.eventService.dispatchEvent(eventEverythingChanged);
  }
  orderGridColumnsLikePrimary() {
    const primaryColumns = this.primaryColumns;
    if (!primaryColumns) {
      return;
    }
    const primaryColsOrdered = primaryColumns.filter((col) => this.gridColumns.indexOf(col) >= 0);
    const otherCols = this.gridColumns.filter((col) => primaryColsOrdered.indexOf(col) < 0);
    this.gridColumns = [...otherCols, ...primaryColsOrdered];
    this.gridColumns = this.placeLockedColumns(this.gridColumns);
  }
  getAllDisplayedAutoHeightCols() {
    return this.displayedAutoHeightCols;
  }
  setViewport() {
    if (this.gos.get("enableRtl")) {
      this.viewportLeft = this.bodyWidth - this.scrollPosition - this.scrollWidth;
      this.viewportRight = this.bodyWidth - this.scrollPosition;
    } else {
      this.viewportLeft = this.scrollPosition;
      this.viewportRight = this.scrollWidth + this.scrollPosition;
    }
  }
  // checks what columns are currently displayed due to column virtualisation. dispatches an event
  // if the list of columns has changed.
  // + setColumnWidth(), setViewportPosition(), setColumnDefs(), sizeColumnsToFit()
  checkViewportColumns(afterScroll = false) {
    if (this.displayedColumnsCenter == null) {
      return;
    }
    const viewportColumnsChanged = this.extractViewport();
    if (!viewportColumnsChanged) {
      return;
    }
    const event = {
      type: Events.EVENT_VIRTUAL_COLUMNS_CHANGED,
      afterScroll
    };
    this.eventService.dispatchEvent(event);
  }
  setViewportPosition(scrollWidth, scrollPosition, afterScroll = false) {
    if (scrollWidth !== this.scrollWidth || scrollPosition !== this.scrollPosition || this.bodyWidthDirty) {
      this.scrollWidth = scrollWidth;
      this.scrollPosition = scrollPosition;
      this.bodyWidthDirty = true;
      this.setViewport();
      if (this.ready) {
        this.checkViewportColumns(afterScroll);
      }
    }
  }
  isPivotMode() {
    return this.pivotMode;
  }
  isPivotSettingAllowed(pivot) {
    if (pivot && this.gos.get("treeData")) {
      warnOnce("Pivot mode not available with treeData.");
      return false;
    }
    return true;
  }
  setPivotMode(pivotMode, source) {
    if (pivotMode === this.pivotMode || !this.isPivotSettingAllowed(this.pivotMode)) {
      return;
    }
    this.pivotMode = pivotMode;
    if (!this.gridColumns) {
      return;
    }
    this.autoGroupsNeedBuilding = true;
    this.updateGridColumns();
    this.updateDisplayedColumns(source);
    const event = {
      type: Events.EVENT_COLUMN_PIVOT_MODE_CHANGED
    };
    this.eventService.dispatchEvent(event);
  }
  getSecondaryPivotColumn(pivotKeys, valueColKey) {
    if (missing(this.secondaryColumns)) {
      return null;
    }
    const valueColumnToFind = this.getPrimaryColumn(valueColKey);
    let foundColumn = null;
    this.secondaryColumns.forEach((column) => {
      const thisPivotKeys = column.getColDef().pivotKeys;
      const pivotValueColumn = column.getColDef().pivotValueColumn;
      const pivotKeyMatches = areEqual(thisPivotKeys, pivotKeys);
      const pivotValueMatches = pivotValueColumn === valueColumnToFind;
      if (pivotKeyMatches && pivotValueMatches) {
        foundColumn = column;
      }
    });
    return foundColumn;
  }
  setBeans(loggerFactory) {
    this.logger = loggerFactory.create("columnModel");
  }
  setFirstRightAndLastLeftPinned(source) {
    let lastLeft;
    let firstRight;
    if (this.gos.get("enableRtl")) {
      lastLeft = this.displayedColumnsLeft ? this.displayedColumnsLeft[0] : null;
      firstRight = this.displayedColumnsRight ? last(this.displayedColumnsRight) : null;
    } else {
      lastLeft = this.displayedColumnsLeft ? last(this.displayedColumnsLeft) : null;
      firstRight = this.displayedColumnsRight ? this.displayedColumnsRight[0] : null;
    }
    this.gridColumns.forEach((column) => {
      column.setLastLeftPinned(column === lastLeft, source);
      column.setFirstRightPinned(column === firstRight, source);
    });
  }
  autoSizeColumns(params) {
    if (this.shouldQueueResizeOperations) {
      this.resizeOperationQueue.push(() => this.autoSizeColumns(params));
      return;
    }
    const { columns, skipHeader, skipHeaderGroups, stopAtGroup, source = "api" } = params;
    this.animationFrameService.flushAllFrames();
    const columnsAutosized = [];
    let changesThisTimeAround = -1;
    const shouldSkipHeader = skipHeader != null ? skipHeader : this.gos.get("skipHeaderOnAutoSize");
    const shouldSkipHeaderGroups = skipHeaderGroups != null ? skipHeaderGroups : shouldSkipHeader;
    while (changesThisTimeAround !== 0) {
      changesThisTimeAround = 0;
      this.actionOnGridColumns(columns, (column) => {
        if (columnsAutosized.indexOf(column) >= 0) {
          return false;
        }
        const preferredWidth = this.autoWidthCalculator.getPreferredWidthForColumn(column, shouldSkipHeader);
        if (preferredWidth > 0) {
          const newWidth = this.normaliseColumnWidth(column, preferredWidth);
          column.setActualWidth(newWidth, source);
          columnsAutosized.push(column);
          changesThisTimeAround++;
        }
        return true;
      }, source);
    }
    if (!shouldSkipHeaderGroups) {
      this.autoSizeColumnGroupsByColumns(columns, source, stopAtGroup);
    }
    this.dispatchColumnResizedEvent(columnsAutosized, true, "autosizeColumns");
  }
  dispatchColumnResizedEvent(columns, finished, source, flexColumns = null) {
    if (columns && columns.length) {
      const event = {
        type: Events.EVENT_COLUMN_RESIZED,
        columns,
        column: columns.length === 1 ? columns[0] : null,
        flexColumns,
        finished,
        source
      };
      this.eventService.dispatchEvent(event);
    }
  }
  dispatchColumnChangedEvent(type, columns, source) {
    const event = {
      type,
      columns,
      column: columns && columns.length == 1 ? columns[0] : null,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  dispatchColumnMovedEvent(params) {
    const { movedColumns, source, toIndex, finished } = params;
    const event = {
      type: Events.EVENT_COLUMN_MOVED,
      columns: movedColumns,
      column: movedColumns && movedColumns.length === 1 ? movedColumns[0] : null,
      toIndex,
      finished,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  dispatchColumnPinnedEvent(changedColumns, source) {
    if (!changedColumns.length) {
      return;
    }
    const column = changedColumns.length === 1 ? changedColumns[0] : null;
    const pinned = this.getCommonValue(changedColumns, (col) => col.getPinned());
    const event = {
      type: Events.EVENT_COLUMN_PINNED,
      // mistake in typing, 'undefined' should be allowed, as 'null' means 'not pinned'
      pinned: pinned != null ? pinned : null,
      columns: changedColumns,
      column,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  dispatchColumnVisibleEvent(changedColumns, source) {
    if (!changedColumns.length) {
      return;
    }
    const column = changedColumns.length === 1 ? changedColumns[0] : null;
    const visible = this.getCommonValue(changedColumns, (col) => col.isVisible());
    const event = {
      type: Events.EVENT_COLUMN_VISIBLE,
      visible,
      columns: changedColumns,
      column,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  autoSizeColumn(key, source, skipHeader) {
    if (key) {
      this.autoSizeColumns({ columns: [key], skipHeader, skipHeaderGroups: true, source });
    }
  }
  autoSizeColumnGroupsByColumns(keys2, source, stopAtGroup) {
    const columnGroups = /* @__PURE__ */ new Set();
    const columns = this.getGridColumns(keys2);
    columns.forEach((col) => {
      let parent = col.getParent();
      while (parent && parent != stopAtGroup) {
        if (!parent.isPadding()) {
          columnGroups.add(parent);
        }
        parent = parent.getParent();
      }
    });
    let headerGroupCtrl;
    const resizedColumns = [];
    for (const columnGroup of columnGroups) {
      for (const headerContainerCtrl of this.ctrlsService.getHeaderRowContainerCtrls()) {
        headerGroupCtrl = headerContainerCtrl.getHeaderCtrlForColumn(columnGroup);
        if (headerGroupCtrl) {
          break;
        }
      }
      if (headerGroupCtrl) {
        headerGroupCtrl.resizeLeafColumnsToFit(source);
      }
    }
    return resizedColumns;
  }
  autoSizeAllColumns(source, skipHeader) {
    if (this.shouldQueueResizeOperations) {
      this.resizeOperationQueue.push(() => this.autoSizeAllColumns(source, skipHeader));
      return;
    }
    const allDisplayedColumns = this.getAllDisplayedColumns();
    this.autoSizeColumns({ columns: allDisplayedColumns, skipHeader, source });
  }
  // Possible candidate for reuse (alot of recursive traversal duplication)
  getColumnsFromTree(rootColumns) {
    const result = [];
    const recursiveFindColumns = (childColumns) => {
      for (let i = 0; i < childColumns.length; i++) {
        const child = childColumns[i];
        if (child instanceof Column) {
          result.push(child);
        } else if (child instanceof ProvidedColumnGroup) {
          recursiveFindColumns(child.getChildren());
        }
      }
    };
    recursiveFindColumns(rootColumns);
    return result;
  }
  getAllDisplayedTrees() {
    if (this.displayedTreeLeft && this.displayedTreeRight && this.displayedTreeCentre) {
      return this.displayedTreeLeft.concat(this.displayedTreeCentre).concat(this.displayedTreeRight);
    }
    return null;
  }
  // + columnSelectPanel
  getPrimaryColumnTree() {
    return this.primaryColumnTree;
  }
  // + gridPanel -> for resizing the body and setting top margin
  getHeaderRowCount() {
    return this.gridHeaderRowCount;
  }
  // + headerRenderer -> setting pinned body width
  getDisplayedTreeLeft() {
    return this.displayedTreeLeft;
  }
  // + headerRenderer -> setting pinned body width
  getDisplayedTreeRight() {
    return this.displayedTreeRight;
  }
  // + headerRenderer -> setting pinned body width
  getDisplayedTreeCentre() {
    return this.displayedTreeCentre;
  }
  // gridPanel -> ensureColumnVisible
  isColumnDisplayed(column) {
    return this.getAllDisplayedColumns().indexOf(column) >= 0;
  }
  // + csvCreator
  getAllDisplayedColumns() {
    return this.displayedColumns;
  }
  getViewportColumns() {
    return this.viewportColumns;
  }
  getDisplayedLeftColumnsForRow(rowNode) {
    if (!this.colSpanActive) {
      return this.displayedColumnsLeft;
    }
    return this.getDisplayedColumnsForRow(rowNode, this.displayedColumnsLeft);
  }
  getDisplayedRightColumnsForRow(rowNode) {
    if (!this.colSpanActive) {
      return this.displayedColumnsRight;
    }
    return this.getDisplayedColumnsForRow(rowNode, this.displayedColumnsRight);
  }
  isColSpanActive() {
    return this.colSpanActive;
  }
  getDisplayedColumnsForRow(rowNode, displayedColumns, filterCallback, emptySpaceBeforeColumn) {
    const result = [];
    let lastConsideredCol = null;
    for (let i = 0; i < displayedColumns.length; i++) {
      const col = displayedColumns[i];
      const maxAllowedColSpan = displayedColumns.length - i;
      const colSpan = Math.min(col.getColSpan(rowNode), maxAllowedColSpan);
      const columnsToCheckFilter = [col];
      if (colSpan > 1) {
        const colsToRemove = colSpan - 1;
        for (let j = 1; j <= colsToRemove; j++) {
          columnsToCheckFilter.push(displayedColumns[i + j]);
        }
        i += colsToRemove;
      }
      let filterPasses;
      if (filterCallback) {
        filterPasses = false;
        columnsToCheckFilter.forEach((colForFilter) => {
          if (filterCallback(colForFilter)) {
            filterPasses = true;
          }
        });
      } else {
        filterPasses = true;
      }
      if (filterPasses) {
        if (result.length === 0 && lastConsideredCol) {
          const gapBeforeColumn = emptySpaceBeforeColumn ? emptySpaceBeforeColumn(col) : false;
          if (gapBeforeColumn) {
            result.push(lastConsideredCol);
          }
        }
        result.push(col);
      }
      lastConsideredCol = col;
    }
    return result;
  }
  // + rowRenderer
  // if we are not column spanning, this just returns back the virtual centre columns,
  // however if we are column spanning, then different rows can have different virtual
  // columns, so we have to work out the list for each individual row.
  getViewportCenterColumnsForRow(rowNode) {
    if (!this.colSpanActive) {
      return this.viewportColumnsCenter;
    }
    const emptySpaceBeforeColumn = (col) => {
      const left = col.getLeft();
      return exists(left) && left > this.viewportLeft;
    };
    const filterCallback = this.isColumnVirtualisationSuppressed() ? null : this.isColumnInRowViewport.bind(this);
    return this.getDisplayedColumnsForRow(
      rowNode,
      this.displayedColumnsCenter,
      filterCallback,
      emptySpaceBeforeColumn
    );
  }
  isColumnAtEdge(col, edge) {
    const allColumns = this.getAllDisplayedColumns();
    if (!allColumns.length) {
      return false;
    }
    const isFirst = edge === "first";
    let columnToCompare;
    if (col instanceof ColumnGroup) {
      const leafColumns = col.getDisplayedLeafColumns();
      if (!leafColumns.length) {
        return false;
      }
      columnToCompare = isFirst ? leafColumns[0] : last(leafColumns);
    } else {
      columnToCompare = col;
    }
    return (isFirst ? allColumns[0] : last(allColumns)) === columnToCompare;
  }
  getAriaColumnIndex(col) {
    let targetColumn;
    if (col instanceof ColumnGroup) {
      targetColumn = col.getLeafColumns()[0];
    } else {
      targetColumn = col;
    }
    return this.ariaOrderColumns.indexOf(targetColumn) + 1;
  }
  isColumnInHeaderViewport(col) {
    if (col.isAutoHeaderHeight()) {
      return true;
    }
    return this.isColumnInRowViewport(col);
  }
  isColumnInRowViewport(col) {
    if (col.isAutoHeight()) {
      return true;
    }
    const columnLeft = col.getLeft() || 0;
    const columnRight = columnLeft + col.getActualWidth();
    const leftBounds = this.viewportLeft - 200;
    const rightBounds = this.viewportRight + 200;
    const columnToMuchLeft = columnLeft < leftBounds && columnRight < leftBounds;
    const columnToMuchRight = columnLeft > rightBounds && columnRight > rightBounds;
    return !columnToMuchLeft && !columnToMuchRight;
  }
  // used by:
  // + angularGrid -> setting pinned body width
  // note: this should be cached
  getDisplayedColumnsLeftWidth() {
    return this.getWidthOfColsInList(this.displayedColumnsLeft);
  }
  // note: this should be cached
  getDisplayedColumnsRightWidth() {
    return this.getWidthOfColsInList(this.displayedColumnsRight);
  }
  updatePrimaryColumnList(keys2, masterList, actionIsAdd, columnCallback, eventType, source) {
    if (!keys2 || missingOrEmpty(keys2)) {
      return;
    }
    let atLeastOne = false;
    keys2.forEach((key) => {
      if (!key) {
        return;
      }
      const columnToAdd = this.getPrimaryColumn(key);
      if (!columnToAdd) {
        return;
      }
      if (actionIsAdd) {
        if (masterList.indexOf(columnToAdd) >= 0) {
          return;
        }
        masterList.push(columnToAdd);
      } else {
        if (masterList.indexOf(columnToAdd) < 0) {
          return;
        }
        removeFromArray(masterList, columnToAdd);
      }
      columnCallback(columnToAdd);
      atLeastOne = true;
    });
    if (!atLeastOne) {
      return;
    }
    if (this.autoGroupsNeedBuilding) {
      this.updateGridColumns();
    }
    this.updateDisplayedColumns(source);
    const event = {
      type: eventType,
      columns: masterList,
      column: masterList.length === 1 ? masterList[0] : null,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  setRowGroupColumns(colKeys, source) {
    this.autoGroupsNeedBuilding = true;
    this.setPrimaryColumnList(
      colKeys,
      this.rowGroupColumns,
      Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
      true,
      this.setRowGroupActive.bind(this),
      source
    );
  }
  setRowGroupActive(active, column, source) {
    if (active === column.isRowGroupActive()) {
      return;
    }
    column.setRowGroupActive(active, source);
    if (active && !this.gos.get("suppressRowGroupHidesColumns")) {
      this.setColumnsVisible([column], false, source);
    }
    if (!active && !this.gos.get("suppressMakeColumnVisibleAfterUnGroup")) {
      this.setColumnsVisible([column], true, source);
    }
  }
  addRowGroupColumns(keys2, source) {
    this.autoGroupsNeedBuilding = true;
    this.updatePrimaryColumnList(
      keys2,
      this.rowGroupColumns,
      true,
      this.setRowGroupActive.bind(this, true),
      Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
      source
    );
  }
  removeRowGroupColumns(keys2, source) {
    this.autoGroupsNeedBuilding = true;
    this.updatePrimaryColumnList(
      keys2,
      this.rowGroupColumns,
      false,
      this.setRowGroupActive.bind(this, false),
      Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
      source
    );
  }
  addPivotColumns(keys2, source) {
    this.updatePrimaryColumnList(
      keys2,
      this.pivotColumns,
      true,
      (column) => column.setPivotActive(true, source),
      Events.EVENT_COLUMN_PIVOT_CHANGED,
      source
    );
  }
  setPivotColumns(colKeys, source) {
    this.setPrimaryColumnList(
      colKeys,
      this.pivotColumns,
      Events.EVENT_COLUMN_PIVOT_CHANGED,
      true,
      (added, column) => {
        column.setPivotActive(added, source);
      },
      source
    );
  }
  removePivotColumns(keys2, source) {
    this.updatePrimaryColumnList(
      keys2,
      this.pivotColumns,
      false,
      (column) => column.setPivotActive(false, source),
      Events.EVENT_COLUMN_PIVOT_CHANGED,
      source
    );
  }
  setPrimaryColumnList(colKeys, masterList, eventName, detectOrderChange, columnCallback, source) {
    if (!this.gridColumns) {
      return;
    }
    const changes = /* @__PURE__ */ new Map();
    masterList.forEach((col, idx) => changes.set(col, idx));
    masterList.length = 0;
    if (exists(colKeys)) {
      colKeys.forEach((key) => {
        const column = this.getPrimaryColumn(key);
        if (column) {
          masterList.push(column);
        }
      });
    }
    masterList.forEach((col, idx) => {
      const oldIndex = changes.get(col);
      if (oldIndex === void 0) {
        changes.set(col, 0);
        return;
      }
      if (detectOrderChange && oldIndex !== idx) {
        return;
      }
      changes.delete(col);
    });
    (this.primaryColumns || []).forEach((column) => {
      const added = masterList.indexOf(column) >= 0;
      columnCallback(added, column);
    });
    if (this.autoGroupsNeedBuilding) {
      this.updateGridColumns();
    }
    this.updateDisplayedColumns(source);
    this.dispatchColumnChangedEvent(eventName, [...changes.keys()], source);
  }
  setValueColumns(colKeys, source) {
    this.setPrimaryColumnList(
      colKeys,
      this.valueColumns,
      Events.EVENT_COLUMN_VALUE_CHANGED,
      false,
      this.setValueActive.bind(this),
      source
    );
  }
  setValueActive(active, column, source) {
    if (active === column.isValueActive()) {
      return;
    }
    column.setValueActive(active, source);
    if (active && !column.getAggFunc() && this.aggFuncService) {
      const initialAggFunc = this.aggFuncService.getDefaultAggFunc(column);
      column.setAggFunc(initialAggFunc);
    }
  }
  addValueColumns(keys2, source) {
    this.updatePrimaryColumnList(
      keys2,
      this.valueColumns,
      true,
      this.setValueActive.bind(this, true),
      Events.EVENT_COLUMN_VALUE_CHANGED,
      source
    );
  }
  removeValueColumns(keys2, source) {
    this.updatePrimaryColumnList(
      keys2,
      this.valueColumns,
      false,
      this.setValueActive.bind(this, false),
      Events.EVENT_COLUMN_VALUE_CHANGED,
      source
    );
  }
  // returns the width we can set to this col, taking into consideration min and max widths
  normaliseColumnWidth(column, newWidth) {
    const minWidth = column.getMinWidth();
    if (exists(minWidth) && newWidth < minWidth) {
      newWidth = minWidth;
    }
    const maxWidth = column.getMaxWidth();
    if (exists(maxWidth) && column.isGreaterThanMax(newWidth)) {
      newWidth = maxWidth;
    }
    return newWidth;
  }
  getPrimaryOrGridColumn(key) {
    const column = this.getPrimaryColumn(key);
    return column || this.getGridColumn(key);
  }
  setColumnWidths(columnWidths, shiftKey, finished, source) {
    const sets = [];
    columnWidths.forEach((columnWidth) => {
      const col = this.getPrimaryOrGridColumn(columnWidth.key);
      if (!col) {
        return;
      }
      sets.push({
        width: columnWidth.newWidth,
        ratios: [1],
        columns: [col]
      });
      const defaultIsShift = this.gos.get("colResizeDefault") === "shift";
      if (defaultIsShift) {
        shiftKey = !shiftKey;
      }
      if (shiftKey) {
        const otherCol = this.getDisplayedColAfter(col);
        if (!otherCol) {
          return;
        }
        const widthDiff = col.getActualWidth() - columnWidth.newWidth;
        const otherColWidth = otherCol.getActualWidth() + widthDiff;
        sets.push({
          width: otherColWidth,
          ratios: [1],
          columns: [otherCol]
        });
      }
    });
    if (sets.length === 0) {
      return;
    }
    this.resizeColumnSets({
      resizeSets: sets,
      finished,
      source
    });
  }
  checkMinAndMaxWidthsForSet(columnResizeSet) {
    const { columns, width } = columnResizeSet;
    let minWidthAccumulated = 0;
    let maxWidthAccumulated = 0;
    let maxWidthActive = true;
    columns.forEach((col) => {
      const minWidth = col.getMinWidth();
      minWidthAccumulated += minWidth || 0;
      const maxWidth = col.getMaxWidth();
      if (exists(maxWidth) && maxWidth > 0) {
        maxWidthAccumulated += maxWidth;
      } else {
        maxWidthActive = false;
      }
    });
    const minWidthPasses = width >= minWidthAccumulated;
    const maxWidthPasses = !maxWidthActive || width <= maxWidthAccumulated;
    return minWidthPasses && maxWidthPasses;
  }
  // method takes sets of columns and resizes them. either all sets will be resized, or nothing
  // be resized. this is used for example when user tries to resize a group and holds shift key,
  // then both the current group (grows), and the adjacent group (shrinks), will get resized,
  // so that's two sets for this method.
  resizeColumnSets(params) {
    const { resizeSets, finished, source } = params;
    const passMinMaxCheck = !resizeSets || resizeSets.every((columnResizeSet) => this.checkMinAndMaxWidthsForSet(columnResizeSet));
    if (!passMinMaxCheck) {
      if (finished) {
        const columns = resizeSets && resizeSets.length > 0 ? resizeSets[0].columns : null;
        this.dispatchColumnResizedEvent(columns, finished, source);
      }
      return;
    }
    const changedCols = [];
    const allResizedCols = [];
    resizeSets.forEach((set) => {
      const { width, columns, ratios } = set;
      const newWidths = {};
      const finishedCols = {};
      columns.forEach((col) => allResizedCols.push(col));
      let finishedColsGrew = true;
      let loopCount = 0;
      while (finishedColsGrew) {
        loopCount++;
        if (loopCount > 1e3) {
          console.error("AG Grid: infinite loop in resizeColumnSets");
          break;
        }
        finishedColsGrew = false;
        const subsetCols = [];
        let subsetRatioTotal = 0;
        let pixelsToDistribute = width;
        columns.forEach((col, index) => {
          const thisColFinished = finishedCols[col.getId()];
          if (thisColFinished) {
            pixelsToDistribute -= newWidths[col.getId()];
          } else {
            subsetCols.push(col);
            const ratioThisCol = ratios[index];
            subsetRatioTotal += ratioThisCol;
          }
        });
        const ratioScale = 1 / subsetRatioTotal;
        subsetCols.forEach((col, index) => {
          const lastCol = index === subsetCols.length - 1;
          let colNewWidth;
          if (lastCol) {
            colNewWidth = pixelsToDistribute;
          } else {
            colNewWidth = Math.round(ratios[index] * width * ratioScale);
            pixelsToDistribute -= colNewWidth;
          }
          const minWidth = col.getMinWidth();
          const maxWidth = col.getMaxWidth();
          if (exists(minWidth) && colNewWidth < minWidth) {
            colNewWidth = minWidth;
            finishedCols[col.getId()] = true;
            finishedColsGrew = true;
          } else if (exists(maxWidth) && maxWidth > 0 && colNewWidth > maxWidth) {
            colNewWidth = maxWidth;
            finishedCols[col.getId()] = true;
            finishedColsGrew = true;
          }
          newWidths[col.getId()] = colNewWidth;
        });
      }
      columns.forEach((col) => {
        const newWidth = newWidths[col.getId()];
        const actualWidth = col.getActualWidth();
        if (actualWidth !== newWidth) {
          col.setActualWidth(newWidth, source);
          changedCols.push(col);
        }
      });
    });
    const atLeastOneColChanged = changedCols.length > 0;
    let flexedCols = [];
    if (atLeastOneColChanged) {
      flexedCols = this.refreshFlexedColumns({ resizingCols: allResizedCols, skipSetLeft: true });
      this.setLeftValues(source);
      this.updateBodyWidths();
      this.checkViewportColumns();
    }
    const colsForEvent = allResizedCols.concat(flexedCols);
    if (atLeastOneColChanged || finished) {
      this.dispatchColumnResizedEvent(colsForEvent, finished, source, flexedCols);
    }
  }
  setColumnAggFunc(key, aggFunc, source) {
    if (!key) {
      return;
    }
    const column = this.getPrimaryColumn(key);
    if (!column) {
      return;
    }
    column.setAggFunc(aggFunc);
    this.dispatchColumnChangedEvent(Events.EVENT_COLUMN_VALUE_CHANGED, [column], source);
  }
  moveRowGroupColumn(fromIndex, toIndex, source) {
    if (this.isRowGroupEmpty()) {
      return;
    }
    const column = this.rowGroupColumns[fromIndex];
    const impactedColumns = this.rowGroupColumns.slice(fromIndex, toIndex);
    this.rowGroupColumns.splice(fromIndex, 1);
    this.rowGroupColumns.splice(toIndex, 0, column);
    const event = {
      type: Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
      columns: impactedColumns,
      column: impactedColumns.length === 1 ? impactedColumns[0] : null,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  moveColumns(columnsToMoveKeys, toIndex, source, finished = true) {
    if (!this.gridColumns) {
      return;
    }
    this.columnAnimationService.start();
    if (toIndex > this.gridColumns.length - columnsToMoveKeys.length) {
      console.warn("AG Grid: tried to insert columns in invalid location, toIndex = " + toIndex);
      console.warn("AG Grid: remember that you should not count the moving columns when calculating the new index");
      return;
    }
    const movedColumns = this.getGridColumns(columnsToMoveKeys);
    const failedRules = !this.doesMovePassRules(movedColumns, toIndex);
    if (failedRules) {
      return;
    }
    moveInArray(this.gridColumns, movedColumns, toIndex);
    this.updateDisplayedColumns(source);
    this.dispatchColumnMovedEvent({ movedColumns, source, toIndex, finished });
    this.columnAnimationService.finish();
  }
  doesMovePassRules(columnsToMove, toIndex) {
    const proposedColumnOrder = this.getProposedColumnOrder(columnsToMove, toIndex);
    return this.doesOrderPassRules(proposedColumnOrder);
  }
  doesOrderPassRules(gridOrder) {
    if (!this.doesMovePassMarryChildren(gridOrder)) {
      return false;
    }
    if (!this.doesMovePassLockedPositions(gridOrder)) {
      return false;
    }
    return true;
  }
  getProposedColumnOrder(columnsToMove, toIndex) {
    const proposedColumnOrder = this.gridColumns.slice();
    moveInArray(proposedColumnOrder, columnsToMove, toIndex);
    return proposedColumnOrder;
  }
  // returns the provided cols sorted in same order as they appear in grid columns. eg if grid columns
  // contains [a,b,c,d,e] and col passed is [e,a] then the passed cols are sorted into [a,e]
  sortColumnsLikeGridColumns(cols) {
    if (!cols || cols.length <= 1) {
      return;
    }
    const notAllColsInGridColumns = cols.filter((c) => this.gridColumns.indexOf(c) < 0).length > 0;
    if (notAllColsInGridColumns) {
      return;
    }
    cols.sort((a, b) => {
      const indexA = this.gridColumns.indexOf(a);
      const indexB = this.gridColumns.indexOf(b);
      return indexA - indexB;
    });
  }
  doesMovePassLockedPositions(proposedColumnOrder) {
    let lastPlacement = 0;
    let rulePassed = true;
    const lockPositionToPlacement = (position) => {
      if (!position) {
        return 1;
      }
      if (position === true) {
        return 0;
      }
      return position === "left" ? 0 : 2;
    };
    proposedColumnOrder.forEach((col) => {
      const placement = lockPositionToPlacement(col.getColDef().lockPosition);
      if (placement < lastPlacement) {
        rulePassed = false;
      }
      lastPlacement = placement;
    });
    return rulePassed;
  }
  doesMovePassMarryChildren(allColumnsCopy) {
    let rulePassed = true;
    depthFirstOriginalTreeSearch(null, this.gridBalancedTree, (child) => {
      if (!(child instanceof ProvidedColumnGroup)) {
        return;
      }
      const columnGroup = child;
      const colGroupDef = columnGroup.getColGroupDef();
      const marryChildren = colGroupDef && colGroupDef.marryChildren;
      if (!marryChildren) {
        return;
      }
      const newIndexes = [];
      columnGroup.getLeafColumns().forEach((col) => {
        const newColIndex = allColumnsCopy.indexOf(col);
        newIndexes.push(newColIndex);
      });
      const maxIndex = Math.max.apply(Math, newIndexes);
      const minIndex = Math.min.apply(Math, newIndexes);
      const spread = maxIndex - minIndex;
      const maxSpread = columnGroup.getLeafColumns().length - 1;
      if (spread > maxSpread) {
        rulePassed = false;
      }
    });
    return rulePassed;
  }
  moveColumnByIndex(fromIndex, toIndex, source) {
    if (!this.gridColumns) {
      return;
    }
    const column = this.gridColumns[fromIndex];
    this.moveColumns([column], toIndex, source);
  }
  getColumnDefs() {
    if (!this.primaryColumns) {
      return;
    }
    const cols = this.primaryColumns.slice();
    if (this.gridColsArePrimary) {
      cols.sort((a, b) => this.gridColumns.indexOf(a) - this.gridColumns.indexOf(b));
    } else if (this.lastPrimaryOrder) {
      cols.sort((a, b) => this.lastPrimaryOrder.indexOf(a) - this.lastPrimaryOrder.indexOf(b));
    }
    return this.columnDefFactory.buildColumnDefs(cols, this.rowGroupColumns, this.pivotColumns);
  }
  // used by:
  // + angularGrid -> for setting body width
  // + rowController -> setting main row widths (when inserting and resizing)
  // need to cache this
  getBodyContainerWidth() {
    return this.bodyWidth;
  }
  getContainerWidth(pinned) {
    switch (pinned) {
      case "left":
        return this.leftWidth;
      case "right":
        return this.rightWidth;
      default:
        return this.bodyWidth;
    }
  }
  // after setColumnWidth or updateGroupsAndDisplayedColumns
  updateBodyWidths() {
    const newBodyWidth = this.getWidthOfColsInList(this.displayedColumnsCenter);
    const newLeftWidth = this.getWidthOfColsInList(this.displayedColumnsLeft);
    const newRightWidth = this.getWidthOfColsInList(this.displayedColumnsRight);
    this.bodyWidthDirty = this.bodyWidth !== newBodyWidth;
    const atLeastOneChanged = this.bodyWidth !== newBodyWidth || this.leftWidth !== newLeftWidth || this.rightWidth !== newRightWidth;
    if (atLeastOneChanged) {
      this.bodyWidth = newBodyWidth;
      this.leftWidth = newLeftWidth;
      this.rightWidth = newRightWidth;
      const evt = {
        type: Events.EVENT_COLUMN_CONTAINER_WIDTH_CHANGED
      };
      this.eventService.dispatchEvent(evt);
      const event = {
        type: Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED
      };
      this.eventService.dispatchEvent(event);
    }
  }
  // + rowController
  getValueColumns() {
    return this.valueColumns ? this.valueColumns : [];
  }
  // + rowController
  getPivotColumns() {
    return this.pivotColumns ? this.pivotColumns : [];
  }
  // + clientSideRowModel
  isPivotActive() {
    return this.pivotColumns && this.pivotColumns.length > 0 && this.pivotMode;
  }
  // + toolPanel
  getRowGroupColumns() {
    return this.rowGroupColumns ? this.rowGroupColumns : [];
  }
  // + rowController -> while inserting rows
  getDisplayedCenterColumns() {
    return this.displayedColumnsCenter;
  }
  // + rowController -> while inserting rows
  getDisplayedLeftColumns() {
    return this.displayedColumnsLeft;
  }
  getDisplayedRightColumns() {
    return this.displayedColumnsRight;
  }
  // used by:
  // + clientSideRowController -> sorting, building quick filter text
  // + headerRenderer -> sorting (clearing icon)
  getAllPrimaryColumns() {
    return this.primaryColumns ? this.primaryColumns : null;
  }
  getSecondaryColumns() {
    return this.secondaryColumns ? this.secondaryColumns : null;
  }
  getAllColumnsForQuickFilter() {
    return this.columnsForQuickFilter;
  }
  // + moveColumnController
  getAllGridColumns() {
    var _a;
    return (_a = this.gridColumns) != null ? _a : [];
  }
  isRowGroupEmpty() {
    return missingOrEmpty(this.rowGroupColumns);
  }
  setColumnsVisible(keys2, visible = false, source) {
    this.applyColumnState({
      state: keys2.map(
        (key) => ({
          colId: typeof key === "string" ? key : key.getColId(),
          hide: !visible
        })
      )
    }, source);
  }
  setColumnsPinned(keys2, pinned, source) {
    if (!this.gridColumns) {
      return;
    }
    if (this.gos.isDomLayout("print")) {
      console.warn(`AG Grid: Changing the column pinning status is not allowed with domLayout='print'`);
      return;
    }
    this.columnAnimationService.start();
    let actualPinned;
    if (pinned === true || pinned === "left") {
      actualPinned = "left";
    } else if (pinned === "right") {
      actualPinned = "right";
    } else {
      actualPinned = null;
    }
    this.actionOnGridColumns(keys2, (col) => {
      if (col.getPinned() !== actualPinned) {
        col.setPinned(actualPinned);
        return true;
      }
      return false;
    }, source, () => {
      const event = {
        type: Events.EVENT_COLUMN_PINNED,
        pinned: actualPinned,
        column: null,
        columns: null,
        source
      };
      return event;
    });
    this.columnAnimationService.finish();
  }
  // does an action on a set of columns. provides common functionality for looking up the
  // columns based on key, getting a list of effected columns, and then updated the event
  // with either one column (if it was just one col) or a list of columns
  // used by: autoResize, setVisible, setPinned
  actionOnGridColumns(keys2, action, source, createEvent) {
    if (missingOrEmpty(keys2)) {
      return;
    }
    const updatedColumns = [];
    keys2.forEach((key) => {
      if (!key) {
        return;
      }
      const column = this.getGridColumn(key);
      if (!column) {
        return;
      }
      const resultOfAction = action(column);
      if (resultOfAction !== false) {
        updatedColumns.push(column);
      }
    });
    if (!updatedColumns.length) {
      return;
    }
    this.updateDisplayedColumns(source);
    if (exists(createEvent) && createEvent) {
      const event = createEvent();
      event.columns = updatedColumns;
      event.column = updatedColumns.length === 1 ? updatedColumns[0] : null;
      this.eventService.dispatchEvent(event);
    }
  }
  getDisplayedColBefore(col) {
    const allDisplayedColumns = this.getAllDisplayedColumns();
    const oldIndex = allDisplayedColumns.indexOf(col);
    if (oldIndex > 0) {
      return allDisplayedColumns[oldIndex - 1];
    }
    return null;
  }
  // used by:
  // + rowRenderer -> for navigation
  getDisplayedColAfter(col) {
    const allDisplayedColumns = this.getAllDisplayedColumns();
    const oldIndex = allDisplayedColumns.indexOf(col);
    if (oldIndex < allDisplayedColumns.length - 1) {
      return allDisplayedColumns[oldIndex + 1];
    }
    return null;
  }
  getDisplayedGroupAtDirection(columnGroup, direction) {
    const requiredLevel = columnGroup.getProvidedColumnGroup().getLevel() + columnGroup.getPaddingLevel();
    const colGroupLeafColumns = columnGroup.getDisplayedLeafColumns();
    const col = direction === "After" ? last(colGroupLeafColumns) : colGroupLeafColumns[0];
    const getDisplayColMethod = `getDisplayedCol${direction}`;
    while (true) {
      const column = this[getDisplayColMethod](col);
      if (!column) {
        return null;
      }
      const groupPointer = this.getColumnGroupAtLevel(column, requiredLevel);
      if (groupPointer !== columnGroup) {
        return groupPointer;
      }
    }
  }
  getColumnGroupAtLevel(column, level) {
    let groupPointer = column.getParent();
    let originalGroupLevel;
    let groupPointerLevel;
    while (true) {
      const groupPointerProvidedColumnGroup = groupPointer.getProvidedColumnGroup();
      originalGroupLevel = groupPointerProvidedColumnGroup.getLevel();
      groupPointerLevel = groupPointer.getPaddingLevel();
      if (originalGroupLevel + groupPointerLevel <= level) {
        break;
      }
      groupPointer = groupPointer.getParent();
    }
    return groupPointer;
  }
  isPinningLeft() {
    return this.displayedColumnsLeft.length > 0;
  }
  isPinningRight() {
    return this.displayedColumnsRight.length > 0;
  }
  getPrimaryAndSecondaryAndAutoColumns() {
    return [].concat(...[
      this.primaryColumns || [],
      this.groupAutoColumns || [],
      this.secondaryColumns || []
    ]);
  }
  createStateItemFromColumn(column) {
    const rowGroupIndex = column.isRowGroupActive() ? this.rowGroupColumns.indexOf(column) : null;
    const pivotIndex = column.isPivotActive() ? this.pivotColumns.indexOf(column) : null;
    const aggFunc = column.isValueActive() ? column.getAggFunc() : null;
    const sort = column.getSort() != null ? column.getSort() : null;
    const sortIndex = column.getSortIndex() != null ? column.getSortIndex() : null;
    const flex = column.getFlex() != null && column.getFlex() > 0 ? column.getFlex() : null;
    const res = {
      colId: column.getColId(),
      width: column.getActualWidth(),
      hide: !column.isVisible(),
      pinned: column.getPinned(),
      sort,
      sortIndex,
      aggFunc,
      rowGroup: column.isRowGroupActive(),
      rowGroupIndex,
      pivot: column.isPivotActive(),
      pivotIndex,
      flex
    };
    return res;
  }
  getColumnState() {
    if (missing(this.primaryColumns) || !this.isAlive()) {
      return [];
    }
    const colsForState = this.getPrimaryAndSecondaryAndAutoColumns();
    const res = colsForState.map(this.createStateItemFromColumn.bind(this));
    this.orderColumnStateList(res);
    return res;
  }
  orderColumnStateList(columnStateList) {
    const colIdToGridIndexMap = convertToMap(this.gridColumns.map((col, index) => [col.getColId(), index]));
    columnStateList.sort((itemA, itemB) => {
      const posA = colIdToGridIndexMap.has(itemA.colId) ? colIdToGridIndexMap.get(itemA.colId) : -1;
      const posB = colIdToGridIndexMap.has(itemB.colId) ? colIdToGridIndexMap.get(itemB.colId) : -1;
      return posA - posB;
    });
  }
  resetColumnState(source) {
    if (missingOrEmpty(this.primaryColumns)) {
      return;
    }
    const primaryColumns = this.getColumnsFromTree(this.primaryColumnTree);
    const columnStates = [];
    let letRowGroupIndex = 1e3;
    let letPivotIndex = 1e3;
    let colsToProcess = [];
    if (this.groupAutoColumns) {
      colsToProcess = colsToProcess.concat(this.groupAutoColumns);
    }
    if (primaryColumns) {
      colsToProcess = colsToProcess.concat(primaryColumns);
    }
    colsToProcess.forEach((column) => {
      const stateItem = this.getColumnStateFromColDef(column);
      if (missing(stateItem.rowGroupIndex) && stateItem.rowGroup) {
        stateItem.rowGroupIndex = letRowGroupIndex++;
      }
      if (missing(stateItem.pivotIndex) && stateItem.pivot) {
        stateItem.pivotIndex = letPivotIndex++;
      }
      columnStates.push(stateItem);
    });
    this.applyColumnState({ state: columnStates, applyOrder: true }, source);
  }
  getColumnStateFromColDef(column) {
    const getValueOrNull = (a, b) => a != null ? a : b != null ? b : null;
    const colDef = column.getColDef();
    const sort = getValueOrNull(colDef.sort, colDef.initialSort);
    const sortIndex = getValueOrNull(colDef.sortIndex, colDef.initialSortIndex);
    const hide = getValueOrNull(colDef.hide, colDef.initialHide);
    const pinned = getValueOrNull(colDef.pinned, colDef.initialPinned);
    const width = getValueOrNull(colDef.width, colDef.initialWidth);
    const flex = getValueOrNull(colDef.flex, colDef.initialFlex);
    let rowGroupIndex = getValueOrNull(colDef.rowGroupIndex, colDef.initialRowGroupIndex);
    let rowGroup = getValueOrNull(colDef.rowGroup, colDef.initialRowGroup);
    if (rowGroupIndex == null && (rowGroup == null || rowGroup == false)) {
      rowGroupIndex = null;
      rowGroup = null;
    }
    let pivotIndex = getValueOrNull(colDef.pivotIndex, colDef.initialPivotIndex);
    let pivot = getValueOrNull(colDef.pivot, colDef.initialPivot);
    if (pivotIndex == null && (pivot == null || pivot == false)) {
      pivotIndex = null;
      pivot = null;
    }
    const aggFunc = getValueOrNull(colDef.aggFunc, colDef.initialAggFunc);
    return {
      colId: column.getColId(),
      sort,
      sortIndex,
      hide,
      pinned,
      width,
      flex,
      rowGroup,
      rowGroupIndex,
      pivot,
      pivotIndex,
      aggFunc
    };
  }
  applyColumnState(params, source) {
    if (missingOrEmpty(this.primaryColumns)) {
      return false;
    }
    if (params && params.state && !params.state.forEach) {
      console.warn("AG Grid: applyColumnState() - the state attribute should be an array, however an array was not found. Please provide an array of items (one for each col you want to change) for state.");
      return false;
    }
    const applyStates = (states, existingColumns, getById) => {
      const dispatchEventsFunc = this.compareColumnStatesAndDispatchEvents(source);
      this.autoGroupsNeedBuilding = true;
      const columnsWithNoState = existingColumns.slice();
      const rowGroupIndexes = {};
      const pivotIndexes = {};
      const autoGroupColumnStates = [];
      const unmatchedAndAutoStates2 = [];
      let unmatchedCount2 = 0;
      const previousRowGroupCols = this.rowGroupColumns.slice();
      const previousPivotCols = this.pivotColumns.slice();
      states.forEach((state) => {
        const colId = state.colId || "";
        const isAutoGroupColumn = colId.startsWith(GROUP_AUTO_COLUMN_ID);
        if (isAutoGroupColumn) {
          autoGroupColumnStates.push(state);
          unmatchedAndAutoStates2.push(state);
          return;
        }
        const column = getById(colId);
        if (!column) {
          unmatchedAndAutoStates2.push(state);
          unmatchedCount2 += 1;
        } else {
          this.syncColumnWithStateItem(
            column,
            state,
            params.defaultState,
            rowGroupIndexes,
            pivotIndexes,
            false,
            source
          );
          removeFromArray(columnsWithNoState, column);
        }
      });
      const applyDefaultsFunc = (col) => this.syncColumnWithStateItem(
        col,
        null,
        params.defaultState,
        rowGroupIndexes,
        pivotIndexes,
        false,
        source
      );
      columnsWithNoState.forEach(applyDefaultsFunc);
      const comparator = (indexes, oldList, colA, colB) => {
        const indexA = indexes[colA.getId()];
        const indexB = indexes[colB.getId()];
        const aHasIndex = indexA != null;
        const bHasIndex = indexB != null;
        if (aHasIndex && bHasIndex) {
          return indexA - indexB;
        }
        if (aHasIndex) {
          return -1;
        }
        if (bHasIndex) {
          return 1;
        }
        const oldIndexA = oldList.indexOf(colA);
        const oldIndexB = oldList.indexOf(colB);
        const aHasOldIndex = oldIndexA >= 0;
        const bHasOldIndex = oldIndexB >= 0;
        if (aHasOldIndex && bHasOldIndex) {
          return oldIndexA - oldIndexB;
        }
        if (aHasOldIndex) {
          return -1;
        }
        return 1;
      };
      this.rowGroupColumns.sort(comparator.bind(this, rowGroupIndexes, previousRowGroupCols));
      this.pivotColumns.sort(comparator.bind(this, pivotIndexes, previousPivotCols));
      this.updateGridColumns();
      const autoGroupColsCopy = this.groupAutoColumns ? this.groupAutoColumns.slice() : [];
      autoGroupColumnStates.forEach((stateItem) => {
        const autoCol = this.getAutoColumn(stateItem.colId);
        removeFromArray(autoGroupColsCopy, autoCol);
        this.syncColumnWithStateItem(autoCol, stateItem, params.defaultState, null, null, true, source);
      });
      autoGroupColsCopy.forEach(applyDefaultsFunc);
      this.applyOrderAfterApplyState(params);
      this.updateDisplayedColumns(source);
      this.dispatchEverythingChanged(source);
      dispatchEventsFunc();
      return { unmatchedAndAutoStates: unmatchedAndAutoStates2, unmatchedCount: unmatchedCount2 };
    };
    this.columnAnimationService.start();
    let {
      unmatchedAndAutoStates,
      unmatchedCount
    } = applyStates(params.state || [], this.primaryColumns || [], (id) => this.getPrimaryColumn(id));
    if (unmatchedAndAutoStates.length > 0 || exists(params.defaultState)) {
      unmatchedCount = applyStates(
        unmatchedAndAutoStates,
        this.secondaryColumns || [],
        (id) => this.getSecondaryColumn(id)
      ).unmatchedCount;
    }
    this.columnAnimationService.finish();
    return unmatchedCount === 0;
  }
  applyOrderAfterApplyState(params) {
    if (!params.applyOrder || !params.state) {
      return;
    }
    let newOrder = [];
    const processedColIds = {};
    params.state.forEach((item) => {
      if (!item.colId || processedColIds[item.colId]) {
        return;
      }
      const col = this.gridColumnsMap[item.colId];
      if (col) {
        newOrder.push(col);
        processedColIds[item.colId] = true;
      }
    });
    let autoGroupInsertIndex = 0;
    this.gridColumns.forEach((col) => {
      const colId = col.getColId();
      const alreadyProcessed = processedColIds[colId] != null;
      if (alreadyProcessed) {
        return;
      }
      const isAutoGroupCol = colId.startsWith(GROUP_AUTO_COLUMN_ID);
      if (isAutoGroupCol) {
        insertIntoArray(newOrder, col, autoGroupInsertIndex++);
      } else {
        newOrder.push(col);
      }
    });
    newOrder = this.placeLockedColumns(newOrder);
    if (!this.doesMovePassMarryChildren(newOrder)) {
      console.warn("AG Grid: Applying column order broke a group where columns should be married together. Applying new order has been discarded.");
      return;
    }
    this.gridColumns = newOrder;
  }
  compareColumnStatesAndDispatchEvents(source) {
    const startState = {
      rowGroupColumns: this.rowGroupColumns.slice(),
      pivotColumns: this.pivotColumns.slice(),
      valueColumns: this.valueColumns.slice()
    };
    const columnStateBefore = this.getColumnState();
    const columnStateBeforeMap = {};
    columnStateBefore.forEach((col) => {
      columnStateBeforeMap[col.colId] = col;
    });
    return () => {
      const colsForState = this.getPrimaryAndSecondaryAndAutoColumns();
      const dispatchWhenListsDifferent = (eventType, colsBefore, colsAfter, idMapper) => {
        const beforeList = colsBefore.map(idMapper);
        const afterList = colsAfter.map(idMapper);
        const unchanged = areEqual(beforeList, afterList);
        if (unchanged) {
          return;
        }
        const changes = new Set(colsBefore);
        colsAfter.forEach((id) => {
          if (!changes.delete(id)) {
            changes.add(id);
          }
        });
        const changesArr = [...changes];
        const event = {
          type: eventType,
          columns: changesArr,
          column: changesArr.length === 1 ? changesArr[0] : null,
          source
        };
        this.eventService.dispatchEvent(event);
      };
      const getChangedColumns = (changedPredicate) => {
        const changedColumns2 = [];
        colsForState.forEach((column) => {
          const colStateBefore = columnStateBeforeMap[column.getColId()];
          if (colStateBefore && changedPredicate(colStateBefore, column)) {
            changedColumns2.push(column);
          }
        });
        return changedColumns2;
      };
      const columnIdMapper = (c) => c.getColId();
      dispatchWhenListsDifferent(
        Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
        startState.rowGroupColumns,
        this.rowGroupColumns,
        columnIdMapper
      );
      dispatchWhenListsDifferent(
        Events.EVENT_COLUMN_PIVOT_CHANGED,
        startState.pivotColumns,
        this.pivotColumns,
        columnIdMapper
      );
      const valueChangePredicate = (cs, c) => {
        const oldActive = cs.aggFunc != null;
        const activeChanged = oldActive != c.isValueActive();
        const aggFuncChanged = oldActive && cs.aggFunc != c.getAggFunc();
        return activeChanged || aggFuncChanged;
      };
      const changedValues = getChangedColumns(valueChangePredicate);
      if (changedValues.length > 0) {
        this.dispatchColumnChangedEvent(Events.EVENT_COLUMN_VALUE_CHANGED, changedValues, source);
      }
      const resizeChangePredicate = (cs, c) => cs.width != c.getActualWidth();
      this.dispatchColumnResizedEvent(getChangedColumns(resizeChangePredicate), true, source);
      const pinnedChangePredicate = (cs, c) => cs.pinned != c.getPinned();
      this.dispatchColumnPinnedEvent(getChangedColumns(pinnedChangePredicate), source);
      const visibilityChangePredicate = (cs, c) => cs.hide == c.isVisible();
      this.dispatchColumnVisibleEvent(getChangedColumns(visibilityChangePredicate), source);
      const sortChangePredicate = (cs, c) => cs.sort != c.getSort() || cs.sortIndex != c.getSortIndex();
      const changedColumns = getChangedColumns(sortChangePredicate);
      if (changedColumns.length > 0) {
        this.sortController.dispatchSortChangedEvents(source, changedColumns);
      }
      this.normaliseColumnMovedEventForColumnState(columnStateBefore, source);
    };
  }
  getCommonValue(cols, valueGetter) {
    if (!cols || cols.length == 0) {
      return void 0;
    }
    const firstValue = valueGetter(cols[0]);
    for (let i = 1; i < cols.length; i++) {
      if (firstValue !== valueGetter(cols[i])) {
        return void 0;
      }
    }
    return firstValue;
  }
  normaliseColumnMovedEventForColumnState(colStateBefore, source) {
    const colStateAfter = this.getColumnState();
    const colStateAfterMapped = {};
    colStateAfter.forEach((s) => colStateAfterMapped[s.colId] = s);
    const colsIntersectIds = {};
    colStateBefore.forEach((s) => {
      if (colStateAfterMapped[s.colId]) {
        colsIntersectIds[s.colId] = true;
      }
    });
    const beforeFiltered = colStateBefore.filter((c) => colsIntersectIds[c.colId]);
    const afterFiltered = colStateAfter.filter((c) => colsIntersectIds[c.colId]);
    const movedColumns = [];
    afterFiltered.forEach((csAfter, index) => {
      const csBefore = beforeFiltered && beforeFiltered[index];
      if (csBefore && csBefore.colId !== csAfter.colId) {
        const gridCol = this.getGridColumn(csBefore.colId);
        if (gridCol) {
          movedColumns.push(gridCol);
        }
      }
    });
    if (!movedColumns.length) {
      return;
    }
    this.dispatchColumnMovedEvent({ movedColumns, source, finished: true });
  }
  syncColumnWithStateItem(column, stateItem, defaultState, rowGroupIndexes, pivotIndexes, autoCol, source) {
    var _a;
    if (!column) {
      return;
    }
    const getValue = (key1, key2) => {
      const obj = { value1: void 0, value2: void 0 };
      let calculated = false;
      if (stateItem) {
        if (stateItem[key1] !== void 0) {
          obj.value1 = stateItem[key1];
          calculated = true;
        }
        if (exists(key2) && stateItem[key2] !== void 0) {
          obj.value2 = stateItem[key2];
          calculated = true;
        }
      }
      if (!calculated && defaultState) {
        if (defaultState[key1] !== void 0) {
          obj.value1 = defaultState[key1];
        }
        if (exists(key2) && defaultState[key2] !== void 0) {
          obj.value2 = defaultState[key2];
        }
      }
      return obj;
    };
    const hide = getValue("hide").value1;
    if (hide !== void 0) {
      column.setVisible(!hide, source);
    }
    const pinned = getValue("pinned").value1;
    if (pinned !== void 0) {
      column.setPinned(pinned);
    }
    const minColWidth = (_a = column.getColDef().minWidth) != null ? _a : this.environment.getMinColWidth();
    const flex = getValue("flex").value1;
    if (flex !== void 0) {
      column.setFlex(flex);
    }
    if (flex == null) {
      const width = getValue("width").value1;
      if (width != null) {
        if (minColWidth != null && width >= minColWidth) {
          column.setActualWidth(width, source);
        }
      }
    }
    const sort = getValue("sort").value1;
    if (sort !== void 0) {
      if (sort === "desc" || sort === "asc") {
        column.setSort(sort, source);
      } else {
        column.setSort(void 0, source);
      }
    }
    const sortIndex = getValue("sortIndex").value1;
    if (sortIndex !== void 0) {
      column.setSortIndex(sortIndex);
    }
    if (autoCol || !column.isPrimary()) {
      return;
    }
    const aggFunc = getValue("aggFunc").value1;
    if (aggFunc !== void 0) {
      if (typeof aggFunc === "string") {
        column.setAggFunc(aggFunc);
        if (!column.isValueActive()) {
          column.setValueActive(true, source);
          this.valueColumns.push(column);
        }
      } else {
        if (exists(aggFunc)) {
          console.warn("AG Grid: stateItem.aggFunc must be a string. if using your own aggregation functions, register the functions first before using them in get/set state. This is because it is intended for the column state to be stored and retrieved as simple JSON.");
        }
        if (column.isValueActive()) {
          column.setValueActive(false, source);
          removeFromArray(this.valueColumns, column);
        }
      }
    }
    const { value1: rowGroup, value2: rowGroupIndex } = getValue("rowGroup", "rowGroupIndex");
    if (rowGroup !== void 0 || rowGroupIndex !== void 0) {
      if (typeof rowGroupIndex === "number" || rowGroup) {
        if (!column.isRowGroupActive()) {
          column.setRowGroupActive(true, source);
          this.rowGroupColumns.push(column);
        }
        if (rowGroupIndexes && typeof rowGroupIndex === "number") {
          rowGroupIndexes[column.getId()] = rowGroupIndex;
        }
      } else {
        if (column.isRowGroupActive()) {
          column.setRowGroupActive(false, source);
          removeFromArray(this.rowGroupColumns, column);
        }
      }
    }
    const { value1: pivot, value2: pivotIndex } = getValue("pivot", "pivotIndex");
    if (pivot !== void 0 || pivotIndex !== void 0) {
      if (typeof pivotIndex === "number" || pivot) {
        if (!column.isPivotActive()) {
          column.setPivotActive(true, source);
          this.pivotColumns.push(column);
        }
        if (pivotIndexes && typeof pivotIndex === "number") {
          pivotIndexes[column.getId()] = pivotIndex;
        }
      } else {
        if (column.isPivotActive()) {
          column.setPivotActive(false, source);
          removeFromArray(this.pivotColumns, column);
        }
      }
    }
  }
  getGridColumns(keys2) {
    return this.getColumns(keys2, this.getGridColumn.bind(this));
  }
  getColumns(keys2, columnLookupCallback) {
    const foundColumns = [];
    if (keys2) {
      keys2.forEach((key) => {
        const column = columnLookupCallback(key);
        if (column) {
          foundColumns.push(column);
        }
      });
    }
    return foundColumns;
  }
  // used by growGroupPanel
  getColumnWithValidation(key) {
    if (key == null) {
      return null;
    }
    const column = this.getGridColumn(key);
    if (!column) {
      console.warn("AG Grid: could not find column " + key);
    }
    return column;
  }
  getPrimaryColumn(key) {
    if (!this.primaryColumns) {
      return null;
    }
    return this.getColumn(key, this.primaryColumns, this.primaryColumnsMap);
  }
  getGridColumn(key) {
    return this.getColumn(key, this.gridColumns, this.gridColumnsMap);
  }
  lookupGridColumn(key) {
    return this.gridColumnsMap[key];
  }
  getSecondaryColumn(key) {
    if (!this.secondaryColumns) {
      return null;
    }
    return this.getColumn(key, this.secondaryColumns, this.secondaryColumnsMap);
  }
  getColumn(key, columnList, columnMap) {
    if (!key || !columnMap) {
      return null;
    }
    if (typeof key == "string" && columnMap[key]) {
      return columnMap[key];
    }
    for (let i = 0; i < columnList.length; i++) {
      if (this.columnsMatch(columnList[i], key)) {
        return columnList[i];
      }
    }
    return this.getAutoColumn(key);
  }
  getSourceColumnsForGroupColumn(groupCol) {
    const sourceColumnId = groupCol.getColDef().showRowGroup;
    if (!sourceColumnId) {
      return null;
    }
    if (sourceColumnId === true) {
      return this.rowGroupColumns.slice(0);
    }
    const column = this.getPrimaryColumn(sourceColumnId);
    return column ? [column] : null;
  }
  getAutoColumn(key) {
    if (!this.groupAutoColumns || !exists(this.groupAutoColumns) || missing(this.groupAutoColumns)) {
      return null;
    }
    return this.groupAutoColumns.find((groupCol) => this.columnsMatch(groupCol, key)) || null;
  }
  columnsMatch(column, key) {
    const columnMatches = column === key;
    const colDefMatches = column.getColDef() === key;
    const idMatches = column.getColId() == key;
    return columnMatches || colDefMatches || idMatches;
  }
  getDisplayNameForColumn(column, location, includeAggFunc = false) {
    if (!column) {
      return null;
    }
    const headerName = this.getHeaderName(column.getColDef(), column, null, null, location);
    if (includeAggFunc) {
      return this.wrapHeaderNameWithAggFunc(column, headerName);
    }
    return headerName;
  }
  getDisplayNameForProvidedColumnGroup(columnGroup, providedColumnGroup, location) {
    const colGroupDef = providedColumnGroup ? providedColumnGroup.getColGroupDef() : null;
    if (colGroupDef) {
      return this.getHeaderName(colGroupDef, null, columnGroup, providedColumnGroup, location);
    }
    return null;
  }
  getDisplayNameForColumnGroup(columnGroup, location) {
    return this.getDisplayNameForProvidedColumnGroup(columnGroup, columnGroup.getProvidedColumnGroup(), location);
  }
  // location is where the column is going to appear, ie who is calling us
  getHeaderName(colDef, column, columnGroup, providedColumnGroup, location) {
    const headerValueGetter = colDef.headerValueGetter;
    if (headerValueGetter) {
      const params = this.gos.addGridCommonParams({
        colDef,
        column,
        columnGroup,
        providedColumnGroup,
        location
      });
      if (typeof headerValueGetter === "function") {
        return headerValueGetter(params);
      } else if (typeof headerValueGetter === "string") {
        return this.expressionService.evaluate(headerValueGetter, params);
      }
      console.warn("AG Grid: headerValueGetter must be a function or a string");
      return "";
    } else if (colDef.headerName != null) {
      return colDef.headerName;
    } else if (colDef.field) {
      return camelCaseToHumanText(colDef.field);
    }
    return "";
  }
  wrapHeaderNameWithAggFunc(column, headerName) {
    if (this.gos.get("suppressAggFuncInHeader")) {
      return headerName;
    }
    const pivotValueColumn = column.getColDef().pivotValueColumn;
    const pivotActiveOnThisColumn = exists(pivotValueColumn);
    let aggFunc = null;
    let aggFuncFound;
    if (pivotActiveOnThisColumn) {
      const isCollapsedHeaderEnabled = this.gos.get("removePivotHeaderRowWhenSingleValueColumn") && this.valueColumns.length === 1;
      const isTotalColumn = column.getColDef().pivotTotalColumnIds !== void 0;
      if (isCollapsedHeaderEnabled && !isTotalColumn) {
        return headerName;
      }
      aggFunc = pivotValueColumn ? pivotValueColumn.getAggFunc() : null;
      aggFuncFound = true;
    } else {
      const measureActive = column.isValueActive();
      const aggregationPresent = this.pivotMode || !this.isRowGroupEmpty();
      if (measureActive && aggregationPresent) {
        aggFunc = column.getAggFunc();
        aggFuncFound = true;
      } else {
        aggFuncFound = false;
      }
    }
    if (aggFuncFound) {
      const aggFuncString = typeof aggFunc === "string" ? aggFunc : "func";
      const localeTextFunc = this.localeService.getLocaleTextFunc();
      const aggFuncStringTranslated = localeTextFunc(aggFuncString, aggFuncString);
      return `${aggFuncStringTranslated}(${headerName})`;
    }
    return headerName;
  }
  // returns the group with matching colId and instanceId. If instanceId is missing,
  // matches only on the colId.
  getColumnGroup(colId, partId) {
    if (!colId) {
      return null;
    }
    if (colId instanceof ColumnGroup) {
      return colId;
    }
    const allColumnGroups = this.getAllDisplayedTrees();
    const checkPartId = typeof partId === "number";
    let result = null;
    depthFirstAllColumnTreeSearch(allColumnGroups, false, (child) => {
      if (child instanceof ColumnGroup) {
        const columnGroup = child;
        let matched;
        if (checkPartId) {
          matched = colId === columnGroup.getGroupId() && partId === columnGroup.getPartId();
        } else {
          matched = colId === columnGroup.getGroupId();
        }
        if (matched) {
          result = columnGroup;
        }
      }
    });
    return result;
  }
  isReady() {
    return this.ready;
  }
  extractValueColumns(source, oldPrimaryColumns) {
    this.valueColumns = this.extractColumns(
      oldPrimaryColumns,
      this.valueColumns,
      (col, flag) => col.setValueActive(flag, source),
      // aggFunc doesn't have index variant, cos order of value cols doesn't matter, so always return null
      () => void 0,
      () => void 0,
      // aggFunc is a string, so return it's existence
      (colDef) => {
        const aggFunc = colDef.aggFunc;
        if (aggFunc === null || aggFunc === "") {
          return null;
        }
        if (aggFunc === void 0) {
          return;
        }
        return !!aggFunc;
      },
      (colDef) => {
        return colDef.initialAggFunc != null && colDef.initialAggFunc != "";
      }
    );
    this.valueColumns.forEach((col) => {
      const colDef = col.getColDef();
      if (colDef.aggFunc != null && colDef.aggFunc != "") {
        col.setAggFunc(colDef.aggFunc);
      } else {
        if (!col.getAggFunc()) {
          col.setAggFunc(colDef.initialAggFunc);
        }
      }
    });
  }
  extractRowGroupColumns(source, oldPrimaryColumns) {
    this.rowGroupColumns = this.extractColumns(
      oldPrimaryColumns,
      this.rowGroupColumns,
      (col, flag) => col.setRowGroupActive(flag, source),
      (colDef) => colDef.rowGroupIndex,
      (colDef) => colDef.initialRowGroupIndex,
      (colDef) => colDef.rowGroup,
      (colDef) => colDef.initialRowGroup
    );
  }
  extractColumns(oldPrimaryColumns = [], previousCols = [], setFlagFunc, getIndexFunc, getInitialIndexFunc, getValueFunc, getInitialValueFunc) {
    const colsWithIndex = [];
    const colsWithValue = [];
    (this.primaryColumns || []).forEach((col) => {
      const colIsNew = oldPrimaryColumns.indexOf(col) < 0;
      const colDef = col.getColDef();
      const value = attrToBoolean(getValueFunc(colDef));
      const initialValue = attrToBoolean(getInitialValueFunc(colDef));
      const index = attrToNumber(getIndexFunc(colDef));
      const initialIndex = attrToNumber(getInitialIndexFunc(colDef));
      let include;
      const valuePresent = value !== void 0;
      const indexPresent = index !== void 0;
      const initialValuePresent = initialValue !== void 0;
      const initialIndexPresent = initialIndex !== void 0;
      if (valuePresent) {
        include = value;
      } else if (indexPresent) {
        if (index === null) {
          include = false;
        } else {
          include = index >= 0;
        }
      } else {
        if (colIsNew) {
          if (initialValuePresent) {
            include = initialValue;
          } else if (initialIndexPresent) {
            include = initialIndex != null && initialIndex >= 0;
          } else {
            include = false;
          }
        } else {
          include = previousCols.indexOf(col) >= 0;
        }
      }
      if (include) {
        const useIndex = colIsNew ? index != null || initialIndex != null : index != null;
        useIndex ? colsWithIndex.push(col) : colsWithValue.push(col);
      }
    });
    const getIndexForCol = (col) => {
      const index = getIndexFunc(col.getColDef());
      const defaultIndex = getInitialIndexFunc(col.getColDef());
      return index != null ? index : defaultIndex;
    };
    colsWithIndex.sort((colA, colB) => {
      const indexA = getIndexForCol(colA);
      const indexB = getIndexForCol(colB);
      if (indexA === indexB) {
        return 0;
      }
      if (indexA < indexB) {
        return -1;
      }
      return 1;
    });
    const res = [].concat(colsWithIndex);
    previousCols.forEach((col) => {
      if (colsWithValue.indexOf(col) >= 0) {
        res.push(col);
      }
    });
    colsWithValue.forEach((col) => {
      if (res.indexOf(col) < 0) {
        res.push(col);
      }
    });
    previousCols.forEach((col) => {
      if (res.indexOf(col) < 0) {
        setFlagFunc(col, false);
      }
    });
    res.forEach((col) => {
      if (previousCols.indexOf(col) < 0) {
        setFlagFunc(col, true);
      }
    });
    return res;
  }
  extractPivotColumns(source, oldPrimaryColumns) {
    this.pivotColumns = this.extractColumns(
      oldPrimaryColumns,
      this.pivotColumns,
      (col, flag) => col.setPivotActive(flag, source),
      (colDef) => colDef.pivotIndex,
      (colDef) => colDef.initialPivotIndex,
      (colDef) => colDef.pivot,
      (colDef) => colDef.initialPivot
    );
  }
  resetColumnGroupState(source) {
    if (!this.primaryColumnTree) {
      return;
    }
    const stateItems = [];
    depthFirstOriginalTreeSearch(null, this.primaryColumnTree, (child) => {
      if (child instanceof ProvidedColumnGroup) {
        const colGroupDef = child.getColGroupDef();
        const groupState = {
          groupId: child.getGroupId(),
          open: !colGroupDef ? void 0 : colGroupDef.openByDefault
        };
        stateItems.push(groupState);
      }
    });
    this.setColumnGroupState(stateItems, source);
  }
  getColumnGroupState() {
    const columnGroupState = [];
    depthFirstOriginalTreeSearch(null, this.gridBalancedTree, (node) => {
      if (node instanceof ProvidedColumnGroup) {
        columnGroupState.push({
          groupId: node.getGroupId(),
          open: node.isExpanded()
        });
      }
    });
    return columnGroupState;
  }
  setColumnGroupState(stateItems, source) {
    if (!this.gridBalancedTree) {
      return;
    }
    this.columnAnimationService.start();
    const impactedGroups = [];
    stateItems.forEach((stateItem) => {
      const groupKey = stateItem.groupId;
      const newValue = stateItem.open;
      const providedColumnGroup = this.getProvidedColumnGroup(groupKey);
      if (!providedColumnGroup) {
        return;
      }
      if (providedColumnGroup.isExpanded() === newValue) {
        return;
      }
      this.logger.log("columnGroupOpened(" + providedColumnGroup.getGroupId() + "," + newValue + ")");
      providedColumnGroup.setExpanded(newValue);
      impactedGroups.push(providedColumnGroup);
    });
    this.updateGroupsAndDisplayedColumns(source);
    this.setFirstRightAndLastLeftPinned(source);
    if (impactedGroups.length) {
      const event = {
        type: Events.EVENT_COLUMN_GROUP_OPENED,
        columnGroup: ProvidedColumnGroup.length === 1 ? impactedGroups[0] : void 0,
        columnGroups: impactedGroups
      };
      this.eventService.dispatchEvent(event);
    }
    this.columnAnimationService.finish();
  }
  // called by headerRenderer - when a header is opened or closed
  setColumnGroupOpened(key, newValue, source) {
    let keyAsString;
    if (key instanceof ProvidedColumnGroup) {
      keyAsString = key.getId();
    } else {
      keyAsString = key || "";
    }
    this.setColumnGroupState([{ groupId: keyAsString, open: newValue }], source);
  }
  getProvidedColumnGroup(key) {
    if (typeof key !== "string") {
      console.error("AG Grid: group key must be a string");
    }
    let res = null;
    depthFirstOriginalTreeSearch(null, this.gridBalancedTree, (node) => {
      if (node instanceof ProvidedColumnGroup) {
        if (node.getId() === key) {
          res = node;
        }
      }
    });
    return res;
  }
  calculateColumnsForDisplay() {
    let columnsForDisplay;
    if (this.pivotMode && missing(this.secondaryColumns)) {
      columnsForDisplay = this.gridColumns.filter((column) => {
        const isAutoGroupCol = this.groupAutoColumns && includes(this.groupAutoColumns, column);
        const isValueCol = this.valueColumns && includes(this.valueColumns, column);
        return isAutoGroupCol || isValueCol;
      });
    } else {
      columnsForDisplay = this.gridColumns.filter((column) => {
        const isAutoGroupCol = this.groupAutoColumns && includes(this.groupAutoColumns, column);
        return isAutoGroupCol || column.isVisible();
      });
    }
    return columnsForDisplay;
  }
  checkColSpanActiveInCols(columns) {
    let result = false;
    columns.forEach((col) => {
      if (exists(col.getColDef().colSpan)) {
        result = true;
      }
    });
    return result;
  }
  calculateColumnsForGroupDisplay() {
    this.groupDisplayColumns = [];
    this.groupDisplayColumnsMap = {};
    const checkFunc = (col) => {
      const colDef = col.getColDef();
      const underlyingColumn = colDef.showRowGroup;
      if (colDef && exists(underlyingColumn)) {
        this.groupDisplayColumns.push(col);
        if (typeof underlyingColumn === "string") {
          this.groupDisplayColumnsMap[underlyingColumn] = col;
        } else if (underlyingColumn === true) {
          this.getRowGroupColumns().forEach((rowGroupCol) => {
            this.groupDisplayColumnsMap[rowGroupCol.getId()] = col;
          });
        }
      }
    };
    this.gridColumns.forEach(checkFunc);
  }
  getGroupDisplayColumns() {
    return this.groupDisplayColumns;
  }
  getGroupDisplayColumnForGroup(rowGroupColumnId) {
    return this.groupDisplayColumnsMap[rowGroupColumnId];
  }
  updateDisplayedColumns(source) {
    const columnsForDisplay = this.calculateColumnsForDisplay();
    this.buildDisplayedTrees(columnsForDisplay);
    this.updateGroupsAndDisplayedColumns(source);
    this.setFirstRightAndLastLeftPinned(source);
  }
  isSecondaryColumnsPresent() {
    return exists(this.secondaryColumns);
  }
  setSecondaryColumns(colDefs, source) {
    if (!this.gridColumns) {
      return;
    }
    const newColsPresent = colDefs;
    if (!newColsPresent && missing(this.secondaryColumns)) {
      return;
    }
    if (newColsPresent) {
      this.processSecondaryColumnDefinitions(colDefs);
      const balancedTreeResult = this.columnFactory.createColumnTree(
        colDefs,
        false,
        this.secondaryBalancedTree || this.previousSecondaryColumns || void 0,
        source
      );
      this.destroyOldColumns(this.secondaryBalancedTree, balancedTreeResult.columnTree);
      this.secondaryBalancedTree = balancedTreeResult.columnTree;
      this.secondaryHeaderRowCount = balancedTreeResult.treeDept + 1;
      this.secondaryColumns = this.getColumnsFromTree(this.secondaryBalancedTree);
      this.secondaryColumnsMap = {};
      this.secondaryColumns.forEach((col) => this.secondaryColumnsMap[col.getId()] = col);
      this.previousSecondaryColumns = null;
    } else {
      this.previousSecondaryColumns = this.secondaryBalancedTree;
      this.secondaryBalancedTree = null;
      this.secondaryHeaderRowCount = -1;
      this.secondaryColumns = null;
      this.secondaryColumnsMap = {};
    }
    this.updateGridColumns();
    this.updateDisplayedColumns(source);
  }
  processSecondaryColumnDefinitions(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 = exists(abstractColDef.children);
        if (isGroup) {
          const colGroupDef = abstractColDef;
          if (groupCallback) {
            groupCallback(colGroupDef);
          }
          searchForColDefs(colGroupDef.children);
        } else {
          const colDef = abstractColDef;
          if (columnCallback) {
            columnCallback(colDef);
          }
        }
      });
    };
    if (colDefs) {
      searchForColDefs(colDefs);
    }
  }
  // called from: applyColumnState, setColumnDefs, setSecondaryColumns
  updateGridColumns() {
    const prevGridCols = this.gridBalancedTree;
    if (this.gridColsArePrimary) {
      this.lastPrimaryOrder = this.gridColumns;
    } else {
      this.lastSecondaryOrder = this.gridColumns;
    }
    const areAutoColsChanged = this.createGroupAutoColumnsIfNeeded();
    if (areAutoColsChanged) {
      const groupAutoColsMap = convertToMap(this.groupAutoColumns.map((col) => [col, true]));
      if (this.lastPrimaryOrder) {
        this.lastPrimaryOrder = this.lastPrimaryOrder.filter((col) => !groupAutoColsMap.has(col));
        this.lastPrimaryOrder = [...this.groupAutoColumns, ...this.lastPrimaryOrder];
      }
      if (this.lastSecondaryOrder) {
        this.lastSecondaryOrder = this.lastSecondaryOrder.filter((col) => !groupAutoColsMap.has(col));
        this.lastSecondaryOrder = [...this.groupAutoColumns, ...this.lastSecondaryOrder];
      }
    }
    let sortOrderToRecover;
    if (this.secondaryColumns && this.secondaryBalancedTree) {
      const hasSameColumns = this.secondaryColumns.some((col) => {
        return this.gridColumnsMap[col.getColId()] !== void 0;
      });
      this.gridBalancedTree = this.secondaryBalancedTree.slice();
      this.gridHeaderRowCount = this.secondaryHeaderRowCount;
      this.gridColumns = this.secondaryColumns.slice();
      this.gridColsArePrimary = false;
      if (hasSameColumns) {
        sortOrderToRecover = this.lastSecondaryOrder;
      }
    } else if (this.primaryColumns) {
      this.gridBalancedTree = this.primaryColumnTree.slice();
      this.gridHeaderRowCount = this.primaryHeaderRowCount;
      this.gridColumns = this.primaryColumns.slice();
      this.gridColsArePrimary = true;
      sortOrderToRecover = this.lastPrimaryOrder;
    }
    this.addAutoGroupToGridColumns();
    this.orderGridColsLike(sortOrderToRecover);
    this.gridColumns = this.placeLockedColumns(this.gridColumns);
    this.calculateColumnsForGroupDisplay();
    this.refreshQuickFilterColumns();
    this.clearDisplayedAndViewportColumns();
    this.colSpanActive = this.checkColSpanActiveInCols(this.gridColumns);
    this.gridColumnsMap = {};
    this.gridColumns.forEach((col) => this.gridColumnsMap[col.getId()] = col);
    this.setAutoHeightActive();
    if (!areEqual(prevGridCols, this.gridBalancedTree)) {
      const event = {
        type: Events.EVENT_GRID_COLUMNS_CHANGED
      };
      this.eventService.dispatchEvent(event);
    }
  }
  setAutoHeightActive() {
    this.autoHeightActive = this.gridColumns.filter((col) => col.isAutoHeight()).length > 0;
    if (this.autoHeightActive) {
      this.autoHeightActiveAtLeastOnce = true;
      const supportedRowModel = this.gos.isRowModelType("clientSide") || this.gos.isRowModelType("serverSide");
      if (!supportedRowModel) {
        warnOnce("autoHeight columns only work with Client Side Row Model and Server Side Row Model.");
      }
    }
  }
  orderGridColsLike(colsOrder) {
    if (missing(colsOrder)) {
      return;
    }
    const lastOrderMapped = convertToMap(colsOrder.map((col, index) => [col, index]));
    let noColsFound = true;
    this.gridColumns.forEach((col) => {
      if (lastOrderMapped.has(col)) {
        noColsFound = false;
      }
    });
    if (noColsFound) {
      return;
    }
    const gridColsMap = convertToMap(this.gridColumns.map((col) => [col, true]));
    const oldColsOrdered = colsOrder.filter((col) => gridColsMap.has(col));
    const oldColsMap = convertToMap(oldColsOrdered.map((col) => [col, true]));
    const newColsOrdered = this.gridColumns.filter((col) => !oldColsMap.has(col));
    const newGridColumns = oldColsOrdered.slice();
    newColsOrdered.forEach((newCol) => {
      let parent = newCol.getOriginalParent();
      if (!parent) {
        newGridColumns.push(newCol);
        return;
      }
      const siblings = [];
      while (!siblings.length && parent) {
        const leafCols = parent.getLeafColumns();
        leafCols.forEach((leafCol) => {
          const presentInNewGriColumns = newGridColumns.indexOf(leafCol) >= 0;
          const noYetInSiblings = siblings.indexOf(leafCol) < 0;
          if (presentInNewGriColumns && noYetInSiblings) {
            siblings.push(leafCol);
          }
        });
        parent = parent.getOriginalParent();
      }
      if (!siblings.length) {
        newGridColumns.push(newCol);
        return;
      }
      const indexes = siblings.map((col) => newGridColumns.indexOf(col));
      const lastIndex = Math.max(...indexes);
      insertIntoArray(newGridColumns, newCol, lastIndex + 1);
    });
    this.gridColumns = newGridColumns;
  }
  isPrimaryColumnGroupsPresent() {
    return this.primaryHeaderRowCount > 1;
  }
  // if we are using autoGroupCols, then they should be included for quick filter. this covers the
  // following scenarios:
  // a) user provides 'field' into autoGroupCol of normal grid, so now because a valid col to filter leafs on
  // b) using tree data and user depends on autoGroupCol for first col, and we also want to filter on this
  //    (tree data is a bit different, as parent rows can be filtered on, unlike row grouping)
  refreshQuickFilterColumns() {
    var _a;
    let columnsForQuickFilter = (_a = this.isPivotMode() && !this.gos.get("applyQuickFilterBeforePivotOrAgg") ? this.secondaryColumns : this.primaryColumns) != null ? _a : [];
    if (this.groupAutoColumns) {
      columnsForQuickFilter = columnsForQuickFilter.concat(this.groupAutoColumns);
    }
    this.columnsForQuickFilter = this.gos.get("includeHiddenColumnsInQuickFilter") ? columnsForQuickFilter : columnsForQuickFilter.filter((col) => col.isVisible() || col.isRowGroupActive());
  }
  placeLockedColumns(cols) {
    const left = [];
    const normal = [];
    const right = [];
    cols.forEach((col) => {
      const position = col.getColDef().lockPosition;
      if (position === "right") {
        right.push(col);
      } else if (position === "left" || position === true) {
        left.push(col);
      } else {
        normal.push(col);
      }
    });
    return [...left, ...normal, ...right];
  }
  addAutoGroupToGridColumns() {
    if (missing(this.groupAutoColumns)) {
      this.destroyOldColumns(this.groupAutoColsBalancedTree);
      this.groupAutoColsBalancedTree = null;
      return;
    }
    this.gridColumns = this.groupAutoColumns ? this.groupAutoColumns.concat(this.gridColumns) : this.gridColumns;
    const newAutoColsTree = this.columnFactory.createForAutoGroups(this.groupAutoColumns, this.gridBalancedTree);
    this.destroyOldColumns(this.groupAutoColsBalancedTree, newAutoColsTree);
    this.groupAutoColsBalancedTree = newAutoColsTree;
    this.gridBalancedTree = newAutoColsTree.concat(this.gridBalancedTree);
  }
  // gets called after we copy down grid columns, to make sure any part of the gui
  // that tries to draw, eg the header, it will get empty lists of columns rather
  // than stale columns. for example, the header will received gridColumnsChanged
  // event, so will try and draw, but it will draw successfully when it acts on the
  // virtualColumnsChanged event
  clearDisplayedAndViewportColumns() {
    this.viewportRowLeft = {};
    this.viewportRowRight = {};
    this.viewportRowCenter = {};
    this.displayedColumnsLeft = [];
    this.displayedColumnsRight = [];
    this.displayedColumnsCenter = [];
    this.displayedColumns = [];
    this.ariaOrderColumns = [];
    this.viewportColumns = [];
    this.headerViewportColumns = [];
    this.viewportColumnsHash = "";
  }
  updateGroupsAndDisplayedColumns(source) {
    this.updateOpenClosedVisibilityInColumnGroups();
    this.deriveDisplayedColumns(source);
    this.refreshFlexedColumns();
    this.extractViewport();
    this.updateBodyWidths();
    const event = {
      type: Events.EVENT_DISPLAYED_COLUMNS_CHANGED
    };
    this.eventService.dispatchEvent(event);
  }
  deriveDisplayedColumns(source) {
    this.derivedDisplayedColumnsFromDisplayedTree(this.displayedTreeLeft, this.displayedColumnsLeft);
    this.derivedDisplayedColumnsFromDisplayedTree(this.displayedTreeCentre, this.displayedColumnsCenter);
    this.derivedDisplayedColumnsFromDisplayedTree(this.displayedTreeRight, this.displayedColumnsRight);
    this.joinColumnsAriaOrder();
    this.joinDisplayedColumns();
    this.setLeftValues(source);
    this.displayedAutoHeightCols = this.displayedColumns.filter((col) => col.isAutoHeight());
  }
  isAutoRowHeightActive() {
    return this.autoHeightActive;
  }
  wasAutoRowHeightEverActive() {
    return this.autoHeightActiveAtLeastOnce;
  }
  joinColumnsAriaOrder() {
    const allColumns = this.getAllGridColumns();
    const pinnedLeft = [];
    const center = [];
    const pinnedRight = [];
    for (const col of allColumns) {
      const pinned = col.getPinned();
      if (!pinned) {
        center.push(col);
      } else if (pinned === true || pinned === "left") {
        pinnedLeft.push(col);
      } else {
        pinnedRight.push(col);
      }
    }
    this.ariaOrderColumns = pinnedLeft.concat(center).concat(pinnedRight);
  }
  joinDisplayedColumns() {
    if (this.gos.get("enableRtl")) {
      this.displayedColumns = this.displayedColumnsRight.concat(this.displayedColumnsCenter).concat(this.displayedColumnsLeft);
    } else {
      this.displayedColumns = this.displayedColumnsLeft.concat(this.displayedColumnsCenter).concat(this.displayedColumnsRight);
    }
  }
  // sets the left pixel position of each column
  setLeftValues(source) {
    this.setLeftValuesOfColumns(source);
    this.setLeftValuesOfGroups();
  }
  setLeftValuesOfColumns(source) {
    if (!this.primaryColumns) {
      return;
    }
    const allColumns = this.getPrimaryAndSecondaryAndAutoColumns().slice(0);
    const doingRtl = this.gos.get("enableRtl");
    [
      this.displayedColumnsLeft,
      this.displayedColumnsRight,
      this.displayedColumnsCenter
    ].forEach((columns) => {
      if (doingRtl) {
        let left = this.getWidthOfColsInList(columns);
        columns.forEach((column) => {
          left -= column.getActualWidth();
          column.setLeft(left, source);
        });
      } else {
        let left = 0;
        columns.forEach((column) => {
          column.setLeft(left, source);
          left += column.getActualWidth();
        });
      }
      removeAllFromUnorderedArray(allColumns, columns);
    });
    allColumns.forEach((column) => {
      column.setLeft(null, source);
    });
  }
  setLeftValuesOfGroups() {
    [
      this.displayedTreeLeft,
      this.displayedTreeRight,
      this.displayedTreeCentre
    ].forEach((columns) => {
      columns.forEach((column) => {
        if (column instanceof ColumnGroup) {
          const columnGroup = column;
          columnGroup.checkLeft();
        }
      });
    });
  }
  derivedDisplayedColumnsFromDisplayedTree(tree, columns) {
    columns.length = 0;
    depthFirstAllColumnTreeSearch(tree, true, (child) => {
      if (child instanceof Column) {
        columns.push(child);
      }
    });
  }
  isColumnVirtualisationSuppressed() {
    return this.suppressColumnVirtualisation || this.viewportRight === 0;
  }
  extractViewportColumns() {
    if (this.isColumnVirtualisationSuppressed()) {
      this.viewportColumnsCenter = this.displayedColumnsCenter;
      this.headerViewportColumnsCenter = this.displayedColumnsCenter;
    } else {
      this.viewportColumnsCenter = this.displayedColumnsCenter.filter(this.isColumnInRowViewport.bind(this));
      this.headerViewportColumnsCenter = this.displayedColumnsCenter.filter(this.isColumnInHeaderViewport.bind(this));
    }
    this.viewportColumns = this.viewportColumnsCenter.concat(this.displayedColumnsLeft).concat(this.displayedColumnsRight);
    this.headerViewportColumns = this.headerViewportColumnsCenter.concat(this.displayedColumnsLeft).concat(this.displayedColumnsRight);
  }
  getVirtualHeaderGroupRow(type, dept) {
    let result;
    switch (type) {
      case "left":
        result = this.viewportRowLeft[dept];
        break;
      case "right":
        result = this.viewportRowRight[dept];
        break;
      default:
        result = this.viewportRowCenter[dept];
        break;
    }
    if (missing(result)) {
      result = [];
    }
    return result;
  }
  calculateHeaderRows() {
    this.viewportRowLeft = {};
    this.viewportRowRight = {};
    this.viewportRowCenter = {};
    const virtualColIds = {};
    this.headerViewportColumns.forEach((col) => virtualColIds[col.getId()] = true);
    const testGroup = (children, result, dept) => {
      let returnValue = false;
      for (let i = 0; i < children.length; i++) {
        const child = children[i];
        let addThisItem = false;
        if (child instanceof Column) {
          addThisItem = virtualColIds[child.getId()] === true;
        } else {
          const columnGroup = child;
          const displayedChildren = columnGroup.getDisplayedChildren();
          if (displayedChildren) {
            addThisItem = testGroup(displayedChildren, result, dept + 1);
          }
        }
        if (addThisItem) {
          returnValue = true;
          if (!result[dept]) {
            result[dept] = [];
          }
          result[dept].push(child);
        }
      }
      return returnValue;
    };
    testGroup(this.displayedTreeLeft, this.viewportRowLeft, 0);
    testGroup(this.displayedTreeRight, this.viewportRowRight, 0);
    testGroup(this.displayedTreeCentre, this.viewportRowCenter, 0);
  }
  extractViewport() {
    const hashColumn = (c) => `${c.getId()}-${c.getPinned() || "normal"}`;
    this.extractViewportColumns();
    const newHash = this.viewportColumns.map(hashColumn).join("#");
    const changed = this.viewportColumnsHash !== newHash;
    if (changed) {
      this.viewportColumnsHash = newHash;
      this.calculateHeaderRows();
    }
    return changed;
  }
  refreshFlexedColumns(params = {}) {
    var _a;
    const source = params.source ? params.source : "flex";
    if (params.viewportWidth != null) {
      this.flexViewportWidth = params.viewportWidth;
    }
    if (!this.flexViewportWidth) {
      return [];
    }
    let flexAfterDisplayIndex = -1;
    if (params.resizingCols) {
      const allResizingCols = new Set(params.resizingCols);
      let displayedCols = this.displayedColumnsCenter;
      for (let i = displayedCols.length - 1; i >= 0; i--) {
        if (allResizingCols.has(displayedCols[i])) {
          flexAfterDisplayIndex = i;
          break;
        }
      }
    }
    let knownColumnsWidth = 0;
    let flexingColumns = [];
    let minimumFlexedWidth = 0;
    let totalFlex = 0;
    for (let i = 0; i < this.displayedColumnsCenter.length; i++) {
      const isFlex = this.displayedColumnsCenter[i].getFlex() && i > flexAfterDisplayIndex;
      if (isFlex) {
        flexingColumns.push(this.displayedColumnsCenter[i]);
        totalFlex += this.displayedColumnsCenter[i].getFlex();
        minimumFlexedWidth += (_a = this.displayedColumnsCenter[i].getMinWidth()) != null ? _a : 0;
      } else {
        knownColumnsWidth += this.displayedColumnsCenter[i].getActualWidth();
      }
    }
    ;
    if (!flexingColumns.length) {
      return [];
    }
    let changedColumns = [];
    if (knownColumnsWidth + minimumFlexedWidth > this.flexViewportWidth) {
      flexingColumns.forEach((col) => {
        var _a2;
        return col.setActualWidth((_a2 = col.getMinWidth()) != null ? _a2 : 0, source);
      });
      changedColumns = flexingColumns;
      flexingColumns = [];
    }
    const flexingColumnSizes = [];
    let spaceForFlexingColumns;
    outer:
      while (true) {
        spaceForFlexingColumns = this.flexViewportWidth - knownColumnsWidth;
        const spacePerFlex = spaceForFlexingColumns / totalFlex;
        for (let i = 0; i < flexingColumns.length; i++) {
          const col = flexingColumns[i];
          const widthByFlexRule = spacePerFlex * col.getFlex();
          let constrainedWidth = 0;
          const minWidth = col.getMinWidth();
          const maxWidth = col.getMaxWidth();
          if (exists(minWidth) && widthByFlexRule < minWidth) {
            constrainedWidth = minWidth;
          } else if (exists(maxWidth) && widthByFlexRule > maxWidth) {
            constrainedWidth = maxWidth;
          }
          if (constrainedWidth) {
            col.setActualWidth(constrainedWidth, source);
            removeFromUnorderedArray(flexingColumns, col);
            totalFlex -= col.getFlex();
            changedColumns.push(col);
            knownColumnsWidth += col.getActualWidth();
            continue outer;
          }
          flexingColumnSizes[i] = Math.round(widthByFlexRule);
        }
        break;
      }
    let remainingSpace = spaceForFlexingColumns;
    flexingColumns.forEach((col, i) => {
      col.setActualWidth(Math.min(flexingColumnSizes[i], remainingSpace), source);
      changedColumns.push(col);
      remainingSpace -= flexingColumnSizes[i];
    });
    if (!params.skipSetLeft) {
      this.setLeftValues(source);
    }
    if (params.updateBodyWidths) {
      this.updateBodyWidths();
    }
    if (params.fireResizedEvent) {
      this.dispatchColumnResizedEvent(changedColumns, true, source, flexingColumns);
    }
    return flexingColumns;
  }
  // called from api
  sizeColumnsToFit(gridWidth, source = "sizeColumnsToFit", silent, params) {
    var _c, _d, _e, _f, _g;
    if (this.shouldQueueResizeOperations) {
      this.resizeOperationQueue.push(() => this.sizeColumnsToFit(gridWidth, source, silent, params));
      return;
    }
    const limitsMap = {};
    if (params) {
      (_c = params == null ? void 0 : params.columnLimits) == null ? void 0 : _c.forEach((_a) => {
        var _b = _a, { key } = _b, dimensions = __objRest(_b, ["key"]);
        limitsMap[typeof key === "string" ? key : key.getColId()] = dimensions;
      });
    }
    const allDisplayedColumns = this.getAllDisplayedColumns();
    const doColumnsAlreadyFit = gridWidth === this.getWidthOfColsInList(allDisplayedColumns);
    if (gridWidth <= 0 || !allDisplayedColumns.length || doColumnsAlreadyFit) {
      return;
    }
    const colsToSpread = [];
    const colsToNotSpread = [];
    allDisplayedColumns.forEach((column) => {
      if (column.getColDef().suppressSizeToFit === true) {
        colsToNotSpread.push(column);
      } else {
        colsToSpread.push(column);
      }
    });
    const colsToDispatchEventFor = colsToSpread.slice(0);
    let finishedResizing = false;
    const moveToNotSpread = (column) => {
      removeFromArray(colsToSpread, column);
      colsToNotSpread.push(column);
    };
    colsToSpread.forEach((column) => {
      var _a, _b;
      column.resetActualWidth(source);
      const widthOverride = limitsMap == null ? void 0 : limitsMap[column.getId()];
      const minOverride = (_a = widthOverride == null ? void 0 : widthOverride.minWidth) != null ? _a : params == null ? void 0 : params.defaultMinWidth;
      const maxOverride = (_b = widthOverride == null ? void 0 : widthOverride.maxWidth) != null ? _b : params == null ? void 0 : params.defaultMaxWidth;
      const colWidth = column.getActualWidth();
      if (typeof minOverride === "number" && colWidth < minOverride) {
        column.setActualWidth(minOverride, source, true);
      } else if (typeof maxOverride === "number" && colWidth > maxOverride) {
        column.setActualWidth(maxOverride, source, true);
      }
    });
    while (!finishedResizing) {
      finishedResizing = true;
      const availablePixels = gridWidth - this.getWidthOfColsInList(colsToNotSpread);
      if (availablePixels <= 0) {
        colsToSpread.forEach((column) => {
          var _a, _b;
          const widthOverride = (_b = (_a = limitsMap == null ? void 0 : limitsMap[column.getId()]) == null ? void 0 : _a.minWidth) != null ? _b : params == null ? void 0 : params.defaultMinWidth;
          if (typeof widthOverride === "number") {
            column.setActualWidth(widthOverride, source, true);
            return;
          }
          column.setMinimum(source);
        });
      } else {
        const scale = availablePixels / this.getWidthOfColsInList(colsToSpread);
        let pixelsForLastCol = availablePixels;
        for (let i = colsToSpread.length - 1; i >= 0; i--) {
          const column = colsToSpread[i];
          const widthOverride = limitsMap == null ? void 0 : limitsMap[column.getId()];
          const minOverride = (_d = widthOverride == null ? void 0 : widthOverride.minWidth) != null ? _d : params == null ? void 0 : params.defaultMinWidth;
          const maxOverride = (_e = widthOverride == null ? void 0 : widthOverride.maxWidth) != null ? _e : params == null ? void 0 : params.defaultMaxWidth;
          const colMinWidth = (_f = column.getMinWidth()) != null ? _f : 0;
          const colMaxWidth = (_g = column.getMaxWidth()) != null ? _g : Number.MAX_VALUE;
          const minWidth = typeof minOverride === "number" && minOverride > colMinWidth ? minOverride : column.getMinWidth();
          const maxWidth = typeof maxOverride === "number" && maxOverride < colMaxWidth ? maxOverride : column.getMaxWidth();
          let newWidth = Math.round(column.getActualWidth() * scale);
          if (exists(minWidth) && newWidth < minWidth) {
            newWidth = minWidth;
            moveToNotSpread(column);
            finishedResizing = false;
          } else if (exists(maxWidth) && newWidth > maxWidth) {
            newWidth = maxWidth;
            moveToNotSpread(column);
            finishedResizing = false;
          } else if (i === 0) {
            newWidth = pixelsForLastCol;
          }
          column.setActualWidth(newWidth, source, true);
          pixelsForLastCol -= newWidth;
        }
      }
    }
    colsToDispatchEventFor.forEach((col) => {
      col.fireColumnWidthChangedEvent(source);
    });
    this.setLeftValues(source);
    this.updateBodyWidths();
    if (silent) {
      return;
    }
    this.dispatchColumnResizedEvent(colsToDispatchEventFor, true, source);
  }
  buildDisplayedTrees(visibleColumns) {
    const leftVisibleColumns = [];
    const rightVisibleColumns = [];
    const centerVisibleColumns = [];
    visibleColumns.forEach((column) => {
      switch (column.getPinned()) {
        case "left":
          leftVisibleColumns.push(column);
          break;
        case "right":
          rightVisibleColumns.push(column);
          break;
        default:
          centerVisibleColumns.push(column);
          break;
      }
    });
    const groupInstanceIdCreator = new GroupInstanceIdCreator();
    this.displayedTreeLeft = this.displayedGroupCreator.createDisplayedGroups(
      leftVisibleColumns,
      groupInstanceIdCreator,
      "left",
      this.displayedTreeLeft
    );
    this.displayedTreeRight = this.displayedGroupCreator.createDisplayedGroups(
      rightVisibleColumns,
      groupInstanceIdCreator,
      "right",
      this.displayedTreeRight
    );
    this.displayedTreeCentre = this.displayedGroupCreator.createDisplayedGroups(
      centerVisibleColumns,
      groupInstanceIdCreator,
      null,
      this.displayedTreeCentre
    );
    this.updateDisplayedMap();
  }
  updateDisplayedMap() {
    this.displayedColumnsAndGroupsMap = {};
    const func = (child) => {
      this.displayedColumnsAndGroupsMap[child.getUniqueId()] = child;
    };
    depthFirstAllColumnTreeSearch(this.displayedTreeCentre, false, func);
    depthFirstAllColumnTreeSearch(this.displayedTreeLeft, false, func);
    depthFirstAllColumnTreeSearch(this.displayedTreeRight, false, func);
  }
  isDisplayed(item) {
    const fromMap = this.displayedColumnsAndGroupsMap[item.getUniqueId()];
    return fromMap === item;
  }
  updateOpenClosedVisibilityInColumnGroups() {
    const allColumnGroups = this.getAllDisplayedTrees();
    depthFirstAllColumnTreeSearch(allColumnGroups, false, (child) => {
      if (child instanceof ColumnGroup) {
        child.calculateDisplayedColumns();
      }
    });
  }
  getGroupAutoColumns() {
    return this.groupAutoColumns;
  }
  /**
   * Creates new auto group columns if required
   * @returns whether auto cols have changed
   */
  createGroupAutoColumnsIfNeeded() {
    const forceRecreateAutoGroups = this.forceRecreateAutoGroups;
    this.forceRecreateAutoGroups = false;
    if (!this.autoGroupsNeedBuilding) {
      return false;
    }
    this.autoGroupsNeedBuilding = false;
    const groupFullWidthRow = this.gos.isGroupUseEntireRow(this.pivotMode);
    const suppressAutoColumn = this.pivotMode ? this.gos.get("pivotSuppressAutoColumn") : this.isGroupSuppressAutoColumn();
    const groupingActive = this.rowGroupColumns.length > 0 || this.gos.get("treeData");
    const needAutoColumns = groupingActive && !suppressAutoColumn && !groupFullWidthRow;
    if (needAutoColumns) {
      const newAutoGroupCols = this.autoGroupColService.createAutoGroupColumns(this.rowGroupColumns);
      const autoColsDifferent = !this.autoColsEqual(newAutoGroupCols, this.groupAutoColumns);
      if (autoColsDifferent || forceRecreateAutoGroups) {
        this.groupAutoColumns = newAutoGroupCols;
        return true;
      }
    } else {
      this.groupAutoColumns = null;
    }
    return false;
  }
  isGroupSuppressAutoColumn() {
    const groupDisplayType = this.gos.get("groupDisplayType");
    const isCustomRowGroups = groupDisplayType === "custom";
    if (isCustomRowGroups) {
      return true;
    }
    const treeDataDisplayType = this.gos.get("treeDataDisplayType");
    return treeDataDisplayType === "custom";
  }
  autoColsEqual(colsA, colsB) {
    return areEqual(colsA, colsB, (a, b) => a.getColId() === b.getColId());
  }
  getWidthOfColsInList(columnList) {
    return columnList.reduce((width, col) => width + col.getActualWidth(), 0);
  }
  getFirstDisplayedColumn() {
    const isRtl = this.gos.get("enableRtl");
    const queryOrder = [
      "getDisplayedLeftColumns",
      "getDisplayedCenterColumns",
      "getDisplayedRightColumns"
    ];
    if (isRtl) {
      queryOrder.reverse();
    }
    for (let i = 0; i < queryOrder.length; i++) {
      const container = this[queryOrder[i]]();
      if (container.length) {
        return isRtl ? last(container) : container[0];
      }
    }
    return null;
  }
  setColumnHeaderHeight(col, height) {
    const changed = col.setAutoHeaderHeight(height);
    if (changed) {
      const event = {
        type: Events.EVENT_COLUMN_HEADER_HEIGHT_CHANGED,
        column: col,
        columns: [col],
        source: "autosizeColumnHeaderHeight"
      };
      this.eventService.dispatchEvent(event);
    }
  }
  getColumnGroupHeaderRowHeight() {
    if (this.isPivotMode()) {
      return this.getPivotGroupHeaderHeight();
    }
    return this.getGroupHeaderHeight();
  }
  getColumnHeaderRowHeight() {
    const defaultHeight = this.isPivotMode() ? this.getPivotHeaderHeight() : this.getHeaderHeight();
    const displayedHeights = this.getAllDisplayedColumns().filter((col) => col.isAutoHeaderHeight()).map((col) => col.getAutoHeaderHeight() || 0);
    return Math.max(defaultHeight, ...displayedHeights);
  }
  getHeaderHeight() {
    var _a;
    return (_a = this.gos.get("headerHeight")) != null ? _a : this.environment.getFromTheme(25, "headerHeight");
  }
  getFloatingFiltersHeight() {
    var _a;
    return (_a = this.gos.get("floatingFiltersHeight")) != null ? _a : this.getHeaderHeight();
  }
  getGroupHeaderHeight() {
    var _a;
    return (_a = this.gos.get("groupHeaderHeight")) != null ? _a : this.getHeaderHeight();
  }
  getPivotHeaderHeight() {
    var _a;
    return (_a = this.gos.get("pivotHeaderHeight")) != null ? _a : this.getHeaderHeight();
  }
  getPivotGroupHeaderHeight() {
    var _a;
    return (_a = this.gos.get("pivotGroupHeaderHeight")) != null ? _a : this.getGroupHeaderHeight();
  }
  queueResizeOperations() {
    this.shouldQueueResizeOperations = true;
  }
  processResizeOperations() {
    this.shouldQueueResizeOperations = false;
    this.resizeOperationQueue.forEach((resizeOperation) => resizeOperation());
    this.resizeOperationQueue = [];
  }
  resetColumnDefIntoColumn(column, source) {
    const userColDef = column.getUserProvidedColDef();
    if (!userColDef) {
      return false;
    }
    const newColDef = this.columnFactory.addColumnDefaultAndTypes(userColDef, column.getColId());
    column.setColDef(newColDef, userColDef, source);
    return true;
  }
  isColumnGroupingLocked(column) {
    const groupLockGroupColumns = this.gos.get("groupLockGroupColumns");
    if (!column.isRowGroupActive() || groupLockGroupColumns === 0) {
      return false;
    }
    if (groupLockGroupColumns === -1) {
      return true;
    }
    const colIndex = this.rowGroupColumns.findIndex((groupCol) => groupCol.getColId() === column.getColId());
    return groupLockGroupColumns > colIndex;
  }
  generateColumnStateForRowGroupAndPivotIndexes(updatedRowGroupColumnState, updatedPivotColumnState) {
    let existingColumnStateUpdates = {};
    const orderColumns = (updatedColumnState, colList, enableProp, initialEnableProp, indexProp, initialIndexProp) => {
      if (!colList.length || !this.primaryColumns) {
        return [];
      }
      const updatedColIdArray = Object.keys(updatedColumnState);
      const updatedColIds = new Set(updatedColIdArray);
      const newColIds = new Set(updatedColIdArray);
      const allColIds = new Set(colList.map((column) => {
        const colId = column.getColId();
        newColIds.delete(colId);
        return colId;
      }).concat(updatedColIdArray));
      const colIdsInOriginalOrder = [];
      const originalOrderMap = {};
      let orderIndex = 0;
      for (let i = 0; i < this.primaryColumns.length; i++) {
        const colId = this.primaryColumns[i].getColId();
        if (allColIds.has(colId)) {
          colIdsInOriginalOrder.push(colId);
          originalOrderMap[colId] = orderIndex++;
        }
      }
      let index = 1e3;
      let hasAddedNewCols = false;
      let lastIndex = 0;
      const processPrecedingNewCols = (colId) => {
        const originalOrderIndex = originalOrderMap[colId];
        for (let i = lastIndex; i < originalOrderIndex; i++) {
          const newColId = colIdsInOriginalOrder[i];
          if (newColIds.has(newColId)) {
            updatedColumnState[newColId][indexProp] = index++;
            newColIds.delete(newColId);
          }
        }
        lastIndex = originalOrderIndex;
      };
      colList.forEach((column) => {
        const colId = column.getColId();
        if (updatedColIds.has(colId)) {
          processPrecedingNewCols(colId);
          updatedColumnState[colId][indexProp] = index++;
        } else {
          const colDef = column.getColDef();
          const missingIndex = colDef[indexProp] === null || colDef[indexProp] === void 0 && colDef[initialIndexProp] == null;
          if (missingIndex) {
            if (!hasAddedNewCols) {
              const propEnabled = colDef[enableProp] || colDef[enableProp] === void 0 && colDef[initialEnableProp];
              if (propEnabled) {
                processPrecedingNewCols(colId);
              } else {
                newColIds.forEach((newColId) => {
                  updatedColumnState[newColId][indexProp] = index + originalOrderMap[newColId];
                });
                index += colIdsInOriginalOrder.length;
                hasAddedNewCols = true;
              }
            }
            if (!existingColumnStateUpdates[colId]) {
              existingColumnStateUpdates[colId] = { colId };
            }
            existingColumnStateUpdates[colId][indexProp] = index++;
          }
        }
      });
    };
    orderColumns(updatedRowGroupColumnState, this.rowGroupColumns, "rowGroup", "initialRowGroup", "rowGroupIndex", "initialRowGroupIndex");
    orderColumns(updatedPivotColumnState, this.pivotColumns, "pivot", "initialPivot", "pivotIndex", "initialPivotIndex");
    return Object.values(existingColumnStateUpdates);
  }
  onColumnsReady() {
    const autoSizeStrategy = this.gos.get("autoSizeStrategy");
    if (!autoSizeStrategy) {
      return;
    }
    const { type } = autoSizeStrategy;
    setTimeout(() => {
      if (type === "fitGridWidth") {
        const { columnLimits: propColumnLimits, defaultMinWidth, defaultMaxWidth } = autoSizeStrategy;
        const columnLimits = propColumnLimits == null ? void 0 : propColumnLimits.map(({ colId: key, minWidth, maxWidth }) => ({
          key,
          minWidth,
          maxWidth
        }));
        this.ctrlsService.getGridBodyCtrl().sizeColumnsToFit({
          defaultMinWidth,
          defaultMaxWidth,
          columnLimits
        });
      } else if (type === "fitProvidedWidth") {
        this.sizeColumnsToFit(autoSizeStrategy.width, "sizeColumnsToFit");
      }
    });
  }
  onFirstDataRendered() {
    const autoSizeStrategy = this.gos.get("autoSizeStrategy");
    if ((autoSizeStrategy == null ? void 0 : autoSizeStrategy.type) !== "fitCellContents") {
      return;
    }
    const { colIds: columns, skipHeader } = autoSizeStrategy;
    setTimeout(() => {
      if (columns) {
        this.autoSizeColumns({
          columns,
          skipHeader,
          source: "autosizeColumns"
        });
      } else {
        this.autoSizeAllColumns("autosizeColumns", skipHeader);
      }
    });
  }
};
__decorateClass([
  Autowired("expressionService")
], ColumnModel.prototype, "expressionService", 2);
__decorateClass([
  Autowired("columnFactory")
], ColumnModel.prototype, "columnFactory", 2);
__decorateClass([
  Autowired("displayedGroupCreator")
], ColumnModel.prototype, "displayedGroupCreator", 2);
__decorateClass([
  Autowired("ctrlsService")
], ColumnModel.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("autoWidthCalculator")
], ColumnModel.prototype, "autoWidthCalculator", 2);
__decorateClass([
  Autowired("columnAnimationService")
], ColumnModel.prototype, "columnAnimationService", 2);
__decorateClass([
  Autowired("autoGroupColService")
], ColumnModel.prototype, "autoGroupColService", 2);
__decorateClass([
  Autowired("valueCache")
], ColumnModel.prototype, "valueCache", 2);
__decorateClass([
  Autowired("animationFrameService")
], ColumnModel.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("sortController")
], ColumnModel.prototype, "sortController", 2);
__decorateClass([
  Autowired("columnDefFactory")
], ColumnModel.prototype, "columnDefFactory", 2);
__decorateClass([
  Optional("aggFuncService")
], ColumnModel.prototype, "aggFuncService", 2);
__decorateClass([
  PostConstruct
], ColumnModel.prototype, "init", 1);
__decorateClass([
  PreDestroy
], ColumnModel.prototype, "destroyColumns", 1);
__decorateClass([
  __decorateParam(0, Qualifier("loggerFactory"))
], ColumnModel.prototype, "setBeans", 1);
ColumnModel = __decorateClass([
  Bean("columnModel")
], ColumnModel);
function convertSourceType(source) {
  return source === "gridOptionsUpdated" ? "gridOptionsChanged" : source;
}
function depthFirstAllColumnTreeSearch(tree, useDisplayedChildren, callback) {
  if (!tree) {
    return;
  }
  for (let i = 0; i < tree.length; i++) {
    const child = tree[i];
    if (child instanceof ColumnGroup) {
      const childTree = useDisplayedChildren ? child.getDisplayedChildren() : child.getChildren();
      depthFirstAllColumnTreeSearch(childTree, useDisplayedChildren, callback);
    }
    callback(child);
  }
}

// community-modules/core/src/columns/displayedGroupCreator.ts
var DisplayedGroupCreator = class extends BeanStub {
  createDisplayedGroups(sortedVisibleColumns, groupInstanceIdCreator, pinned, oldDisplayedGroups) {
    const oldColumnsMapped = this.mapOldGroupsById(oldDisplayedGroups);
    const topLevelResultCols = [];
    let groupsOrColsAtCurrentLevel = sortedVisibleColumns;
    while (groupsOrColsAtCurrentLevel.length) {
      const currentlyIterating = groupsOrColsAtCurrentLevel;
      groupsOrColsAtCurrentLevel = [];
      let lastGroupedColIdx = 0;
      const createGroupToIndex = (to) => {
        const from = lastGroupedColIdx;
        lastGroupedColIdx = to;
        const previousNode = currentlyIterating[from];
        const previousNodeProvided = previousNode instanceof ColumnGroup ? previousNode.getProvidedColumnGroup() : previousNode;
        const previousNodeParent = previousNodeProvided.getOriginalParent();
        if (previousNodeParent == null) {
          for (let i = from; i < to; i++) {
            topLevelResultCols.push(currentlyIterating[i]);
          }
          return;
        }
        const newGroup = this.createColumnGroup(
          previousNodeParent,
          groupInstanceIdCreator,
          oldColumnsMapped,
          pinned
        );
        for (let i = from; i < to; i++) {
          newGroup.addChild(currentlyIterating[i]);
        }
        groupsOrColsAtCurrentLevel.push(newGroup);
      };
      for (let i = 1; i < currentlyIterating.length; i++) {
        const thisNode = currentlyIterating[i];
        const thisNodeProvided = thisNode instanceof ColumnGroup ? thisNode.getProvidedColumnGroup() : thisNode;
        const thisNodeParent = thisNodeProvided.getOriginalParent();
        const previousNode = currentlyIterating[lastGroupedColIdx];
        const previousNodeProvided = previousNode instanceof ColumnGroup ? previousNode.getProvidedColumnGroup() : previousNode;
        const previousNodeParent = previousNodeProvided.getOriginalParent();
        if (thisNodeParent !== previousNodeParent) {
          createGroupToIndex(i);
        }
      }
      if (lastGroupedColIdx < currentlyIterating.length) {
        createGroupToIndex(currentlyIterating.length);
      }
    }
    this.setupParentsIntoColumns(topLevelResultCols, null);
    return topLevelResultCols;
  }
  createColumnGroup(providedGroup, groupInstanceIdCreator, oldColumnsMapped, pinned) {
    const groupId = providedGroup.getGroupId();
    const instanceId = groupInstanceIdCreator.getInstanceIdForKey(groupId);
    const uniqueId = ColumnGroup.createUniqueId(groupId, instanceId);
    let columnGroup = oldColumnsMapped[uniqueId];
    if (columnGroup && columnGroup.getProvidedColumnGroup() !== providedGroup) {
      columnGroup = null;
    }
    if (exists(columnGroup)) {
      columnGroup.reset();
    } else {
      columnGroup = new ColumnGroup(providedGroup, groupId, instanceId, pinned);
      this.context.createBean(columnGroup);
    }
    return columnGroup;
  }
  // returns back a 2d map of ColumnGroup as follows: groupId -> instanceId -> ColumnGroup
  mapOldGroupsById(displayedGroups) {
    const result = {};
    const recursive = (columnsOrGroups) => {
      columnsOrGroups.forEach((columnOrGroup) => {
        if (columnOrGroup instanceof ColumnGroup) {
          const columnGroup = columnOrGroup;
          result[columnOrGroup.getUniqueId()] = columnGroup;
          recursive(columnGroup.getChildren());
        }
      });
    };
    if (displayedGroups) {
      recursive(displayedGroups);
    }
    return result;
  }
  setupParentsIntoColumns(columnsOrGroups, parent) {
    columnsOrGroups.forEach((columnsOrGroup) => {
      columnsOrGroup.setParent(parent);
      if (columnsOrGroup instanceof ColumnGroup) {
        const columnGroup = columnsOrGroup;
        this.setupParentsIntoColumns(columnGroup.getChildren(), columnGroup);
      }
    });
  }
};
DisplayedGroupCreator = __decorateClass([
  Bean("displayedGroupCreator")
], DisplayedGroupCreator);

// community-modules/core/src/propertyKeys.ts
var INITIAL_GRID_OPTION_KEYS = {
  enableBrowserTooltips: true,
  tooltipTrigger: true,
  tooltipMouseTrack: true,
  tooltipShowMode: true,
  tooltipInteraction: true,
  defaultColGroupDef: true,
  suppressAutoSize: true,
  skipHeaderOnAutoSize: true,
  autoSizeStrategy: true,
  components: true,
  stopEditingWhenCellsLoseFocus: true,
  undoRedoCellEditing: true,
  undoRedoCellEditingLimit: true,
  excelStyles: true,
  cacheQuickFilter: true,
  excludeHiddenColumnsFromQuickFilter: true,
  advancedFilterModel: true,
  customChartThemes: true,
  chartThemeOverrides: true,
  enableChartToolPanelsButton: true,
  suppressChartToolPanelsButton: true,
  chartToolPanelsDef: true,
  loadingCellRendererSelector: true,
  localeText: true,
  keepDetailRows: true,
  keepDetailRowsCount: true,
  detailRowHeight: true,
  detailRowAutoHeight: true,
  tabIndex: true,
  valueCache: true,
  valueCacheNeverExpires: true,
  enableCellExpressions: true,
  suppressParentsInRowNodes: true,
  suppressTouch: true,
  suppressAsyncEvents: true,
  suppressBrowserResizeObserver: true,
  suppressPropertyNamesCheck: true,
  debug: true,
  loadingOverlayComponent: true,
  suppressLoadingOverlay: true,
  noRowsOverlayComponent: true,
  paginationPageSizeSelector: true,
  paginateChildRows: true,
  pivotPanelShow: true,
  pivotSuppressAutoColumn: true,
  suppressExpandablePivotGroups: true,
  aggFuncs: true,
  suppressAggFuncInHeader: true,
  suppressAggAtRootLevel: true,
  removePivotHeaderRowWhenSingleValueColumn: true,
  allowShowChangeAfterFilter: true,
  ensureDomOrder: true,
  enableRtl: true,
  suppressColumnVirtualisation: true,
  suppressMaxRenderedRowRestriction: true,
  suppressRowVirtualisation: true,
  rowDragText: true,
  suppressGroupMaintainValueType: true,
  groupLockGroupColumns: true,
  rowGroupPanelSuppressSort: true,
  suppressGroupRowsSticky: true,
  rowModelType: true,
  cacheOverflowSize: true,
  infiniteInitialRowCount: true,
  serverSideInitialRowCount: true,
  suppressServerSideInfiniteScroll: true,
  maxBlocksInCache: true,
  maxConcurrentDatasourceRequests: true,
  blockLoadDebounceMillis: true,
  serverSideOnlyRefreshFilteredGroups: true,
  serverSidePivotResultFieldSeparator: true,
  viewportRowModelPageSize: true,
  viewportRowModelBufferSize: true,
  debounceVerticalScrollbar: true,
  suppressAnimationFrame: true,
  suppressPreventDefaultOnMouseWheel: true,
  scrollbarWidth: true,
  icons: true,
  suppressRowTransform: true,
  gridId: true,
  functionsPassive: true,
  enableGroupEdit: true,
  initialState: true,
  processUnpinnedColumns: true,
  createChartContainer: true,
  getLocaleText: true,
  getRowId: true,
  reactiveCustomComponents: true,
  columnMenu: true
};
var _PropertyKeys = class _PropertyKeys {
};
_PropertyKeys.STRING_PROPERTIES = [
  "rowSelection",
  "overlayLoadingTemplate",
  "overlayNoRowsTemplate",
  "gridId",
  "quickFilterText",
  "rowModelType",
  "editType",
  "domLayout",
  "clipboardDelimiter",
  "rowGroupPanelShow",
  "multiSortKey",
  "pivotColumnGroupTotals",
  "pivotRowTotals",
  "pivotPanelShow",
  "fillHandleDirection",
  "groupDisplayType",
  "treeDataDisplayType",
  "colResizeDefault",
  "tooltipTrigger",
  "serverSidePivotResultFieldSeparator",
  "columnMenu",
  "tooltipShowMode",
  "grandTotalRow"
];
_PropertyKeys.OBJECT_PROPERTIES = [
  "components",
  "rowStyle",
  "context",
  "autoGroupColumnDef",
  "localeText",
  "icons",
  "datasource",
  "serverSideDatasource",
  "viewportDatasource",
  "groupRowRendererParams",
  "aggFuncs",
  "fullWidthCellRendererParams",
  "defaultColGroupDef",
  "defaultColDef",
  "defaultCsvExportParams",
  "defaultExcelExportParams",
  "columnTypes",
  "rowClassRules",
  "detailCellRendererParams",
  "loadingCellRendererParams",
  "loadingOverlayComponentParams",
  "noRowsOverlayComponentParams",
  "popupParent",
  "statusBar",
  "sideBar",
  "chartThemeOverrides",
  "customChartThemes",
  "chartToolPanelsDef",
  "dataTypeDefinitions",
  "advancedFilterModel",
  "advancedFilterParent",
  "advancedFilterBuilderParams",
  "initialState",
  "autoSizeStrategy"
];
_PropertyKeys.ARRAY_PROPERTIES = [
  "sortingOrder",
  "alignedGrids",
  "rowData",
  "columnDefs",
  "excelStyles",
  "pinnedTopRowData",
  "pinnedBottomRowData",
  "chartThemes",
  "rowClass",
  "paginationPageSizeSelector"
];
// These properties are coerced at runtime, do not do union types
_PropertyKeys.NUMBER_PROPERTIES = [
  "rowHeight",
  "detailRowHeight",
  "rowBuffer",
  "headerHeight",
  "groupHeaderHeight",
  "groupLockGroupColumns",
  "floatingFiltersHeight",
  "pivotHeaderHeight",
  "pivotGroupHeaderHeight",
  "groupDefaultExpanded",
  "pivotDefaultExpanded",
  "viewportRowModelPageSize",
  "viewportRowModelBufferSize",
  "autoSizePadding",
  "maxBlocksInCache",
  "maxConcurrentDatasourceRequests",
  "tooltipShowDelay",
  "tooltipHideDelay",
  "cacheOverflowSize",
  "paginationPageSize",
  "cacheBlockSize",
  "infiniteInitialRowCount",
  "serverSideInitialRowCount",
  "scrollbarWidth",
  "asyncTransactionWaitMillis",
  "blockLoadDebounceMillis",
  "keepDetailRowsCount",
  "undoRedoCellEditingLimit",
  "cellFlashDelay",
  "cellFadeDelay",
  "cellFlashDuration",
  "cellFadeDuration",
  "tabIndex",
  "pivotMaxGeneratedColumns"
];
// These properties are coerced at runtime, do not do union types
_PropertyKeys.BOOLEAN_PROPERTIES = [
  "suppressMakeColumnVisibleAfterUnGroup",
  "suppressRowClickSelection",
  "suppressCellFocus",
  "suppressHeaderFocus",
  "suppressHorizontalScroll",
  "groupSelectsChildren",
  "alwaysShowHorizontalScroll",
  "alwaysShowVerticalScroll",
  "debug",
  "enableBrowserTooltips",
  "enableCellExpressions",
  "groupIncludeTotalFooter",
  "groupSuppressBlankHeader",
  "suppressMenuHide",
  "suppressRowDeselection",
  "unSortIcon",
  "suppressMultiSort",
  "alwaysMultiSort",
  "singleClickEdit",
  "suppressLoadingOverlay",
  "suppressNoRowsOverlay",
  "suppressAutoSize",
  "skipHeaderOnAutoSize",
  "suppressParentsInRowNodes",
  "suppressColumnMoveAnimation",
  "suppressMovableColumns",
  "suppressFieldDotNotation",
  "enableRangeSelection",
  "enableRangeHandle",
  "enableFillHandle",
  "suppressClearOnFillReduction",
  "deltaSort",
  "suppressTouch",
  "suppressAsyncEvents",
  "allowContextMenuWithControlKey",
  "suppressContextMenu",
  "enableCellChangeFlash",
  "suppressDragLeaveHidesColumns",
  "suppressRowGroupHidesColumns",
  "suppressMiddleClickScrolls",
  "suppressPreventDefaultOnMouseWheel",
  "suppressCopyRowsToClipboard",
  "copyHeadersToClipboard",
  "copyGroupHeadersToClipboard",
  "pivotMode",
  "suppressAggFuncInHeader",
  "suppressColumnVirtualisation",
  "alwaysAggregateAtRootLevel",
  "suppressAggAtRootLevel",
  "suppressFocusAfterRefresh",
  "functionsPassive",
  "functionsReadOnly",
  "animateRows",
  "groupSelectsFiltered",
  "groupRemoveSingleChildren",
  "groupRemoveLowestSingleChildren",
  "enableRtl",
  "suppressClickEdit",
  "rowDragEntireRow",
  "rowDragManaged",
  "suppressRowDrag",
  "suppressMoveWhenRowDragging",
  "rowDragMultiRow",
  "enableGroupEdit",
  "embedFullWidthRows",
  "suppressPaginationPanel",
  "groupHideOpenParents",
  "groupAllowUnbalanced",
  "pagination",
  "paginationAutoPageSize",
  "suppressScrollOnNewData",
  "suppressScrollWhenPopupsAreOpen",
  "purgeClosedRowNodes",
  "cacheQuickFilter",
  "includeHiddenColumnsInQuickFilter",
  "excludeHiddenColumnsFromQuickFilter",
  "ensureDomOrder",
  "accentedSort",
  "suppressChangeDetection",
  "valueCache",
  "valueCacheNeverExpires",
  "aggregateOnlyChangedColumns",
  "suppressAnimationFrame",
  "suppressExcelExport",
  "suppressCsvExport",
  "includeHiddenColumnsInAdvancedFilter",
  "suppressMultiRangeSelection",
  "enterMovesDown",
  "enterMovesDownAfterEdit",
  "enterNavigatesVerticallyAfterEdit",
  "enterNavigatesVertically",
  "suppressPropertyNamesCheck",
  "rowMultiSelectWithClick",
  "suppressRowHoverHighlight",
  "suppressRowTransform",
  "suppressClipboardPaste",
  "suppressLastEmptyLineOnPaste",
  "enableCharts",
  "enableChartToolPanelsButton",
  "suppressChartToolPanelsButton",
  "suppressMaintainUnsortedOrder",
  "enableCellTextSelection",
  "suppressBrowserResizeObserver",
  "suppressMaxRenderedRowRestriction",
  "excludeChildrenWhenTreeDataFiltering",
  "tooltipMouseTrack",
  "tooltipInteraction",
  "keepDetailRows",
  "paginateChildRows",
  "preventDefaultOnContextMenu",
  "undoRedoCellEditing",
  "allowDragFromColumnsToolPanel",
  "pivotSuppressAutoColumn",
  "suppressExpandablePivotGroups",
  "debounceVerticalScrollbar",
  "detailRowAutoHeight",
  "serverSideFilterAllLevels",
  "serverSideSortAllLevels",
  "serverSideEnableClientSideSort",
  "serverSideOnlyRefreshFilteredGroups",
  "serverSideSortOnServer",
  "serverSideFilterOnServer",
  "suppressAggFilteredOnly",
  "showOpenedGroup",
  "suppressClipboardApi",
  "suppressModelUpdateAfterUpdateTransaction",
  "stopEditingWhenCellsLoseFocus",
  "maintainColumnOrder",
  "groupMaintainOrder",
  "columnHoverHighlight",
  "readOnlyEdit",
  "suppressRowVirtualisation",
  "enableCellEditingOnBackspace",
  "resetRowDataOnUpdate",
  "removePivotHeaderRowWhenSingleValueColumn",
  "suppressCopySingleCellRanges",
  "suppressGroupRowsSticky",
  "suppressCutToClipboard",
  "suppressServerSideInfiniteScroll",
  "rowGroupPanelSuppressSort",
  "allowShowChangeAfterFilter",
  "enableAdvancedFilter",
  "masterDetail",
  "treeData",
  "suppressGroupMaintainValueType",
  "reactiveCustomComponents",
  "applyQuickFilterBeforePivotOrAgg",
  "suppressServerSideFullWidthLoadingRow",
  "suppressAdvancedFilterEval"
];
// If property does not fit above, i.e union that should not be coerced.
_PropertyKeys.OTHER_PROPERTIES = [
  "suppressStickyTotalRow"
];
/** You do not need to include event callbacks in this list, as they are generated automatically. */
_PropertyKeys.FUNCTIONAL_PROPERTIES = [
  "doesExternalFilterPass",
  "processPivotResultColDef",
  "processPivotResultColGroupDef",
  "getBusinessKeyForNode",
  "isRowSelectable",
  "rowDragText",
  "groupRowRenderer",
  "fullWidthCellRenderer",
  "loadingCellRenderer",
  "loadingOverlayComponent",
  "noRowsOverlayComponent",
  "detailCellRenderer",
  "quickFilterParser",
  "quickFilterMatcher"
];
/** These callbacks extend AgGridCommon interface */
_PropertyKeys.CALLBACK_PROPERTIES = [
  "getLocaleText",
  "isExternalFilterPresent",
  "getRowHeight",
  "getRowClass",
  "getRowStyle",
  "getContextMenuItems",
  "getMainMenuItems",
  "processRowPostCreate",
  "processCellForClipboard",
  "getGroupRowAgg",
  "isFullWidthRow",
  "sendToClipboard",
  "navigateToNextHeader",
  "tabToNextHeader",
  "navigateToNextCell",
  "tabToNextCell",
  "processCellFromClipboard",
  "getDocument",
  "postProcessPopup",
  "getChildCount",
  "getDataPath",
  "isRowMaster",
  "postSortRows",
  "processHeaderForClipboard",
  "processUnpinnedColumns",
  "processGroupHeaderForClipboard",
  "paginationNumberFormatter",
  "processDataFromClipboard",
  "getServerSideGroupKey",
  "isServerSideGroup",
  "createChartContainer",
  "getChartToolbarItems",
  "fillOperation",
  "isApplyServerSideTransaction",
  "getServerSideGroupLevelParams",
  "isServerSideGroupOpenByDefault",
  "isGroupOpenByDefault",
  "initialGroupOrderComparator",
  "groupIncludeFooter",
  "loadingCellRendererSelector",
  "getRowId",
  "groupAggFiltering",
  "chartMenuItems",
  "groupTotalRow"
];
_PropertyKeys.FUNCTION_PROPERTIES = [
  ..._PropertyKeys.FUNCTIONAL_PROPERTIES,
  ..._PropertyKeys.CALLBACK_PROPERTIES
];
_PropertyKeys.ALL_PROPERTIES = [
  ..._PropertyKeys.ARRAY_PROPERTIES,
  ..._PropertyKeys.OBJECT_PROPERTIES,
  ..._PropertyKeys.STRING_PROPERTIES,
  ..._PropertyKeys.NUMBER_PROPERTIES,
  ..._PropertyKeys.FUNCTION_PROPERTIES,
  ..._PropertyKeys.BOOLEAN_PROPERTIES,
  ..._PropertyKeys.OTHER_PROPERTIES
];
var PropertyKeys = _PropertyKeys;

// community-modules/core/src/components/componentUtil.ts
var _ComponentUtil = class _ComponentUtil {
  static getCallbackForEvent(eventName) {
    if (!eventName || eventName.length < 2) {
      return eventName;
    }
    return "on" + eventName[0].toUpperCase() + eventName.substring(1);
  }
  static getGridOptionKeys() {
    return this.ALL_PROPERTIES_AND_CALLBACKS;
  }
  /** Combines component props / attributes with the provided gridOptions returning a new combined gridOptions object */
  static combineAttributesAndGridOptions(gridOptions, component) {
    if (typeof gridOptions !== "object") {
      gridOptions = {};
    }
    const mergedOptions = __spreadValues({}, gridOptions);
    const keys2 = _ComponentUtil.getGridOptionKeys();
    keys2.forEach((key) => {
      const value = component[key];
      if (typeof value !== "undefined" && value !== _ComponentUtil.VUE_OMITTED_PROPERTY) {
        mergedOptions[key] = value;
      }
    });
    return mergedOptions;
  }
  static processOnChange(changes, api, isVue) {
    if (!changes) {
      return;
    }
    const gridChanges = {};
    let hasChanges = false;
    Object.keys(changes).filter((key) => _ComponentUtil.ALL_PROPERTIES_AND_CALLBACKS_SET.has(key)).forEach((key) => {
      gridChanges[key] = changes[key];
      hasChanges = true;
    });
    if (!hasChanges) {
      return;
    }
    api.__internalUpdateGridOptions(gridChanges, true);
    const event = {
      type: Events.EVENT_COMPONENT_STATE_CHANGED
    };
    iterateObject(gridChanges, (key, value) => {
      event[key] = value;
    });
    api.dispatchEvent(event);
  }
};
// all events
_ComponentUtil.EVENTS = values(Events);
_ComponentUtil.VUE_OMITTED_PROPERTY = "AG-VUE-OMITTED-PROPERTY";
// events that are internal to AG Grid and should not be exposed to users via documentation or generated framework components
/** Exclude the following internal events from code generation to prevent exposing these events via framework components */
_ComponentUtil.EXCLUDED_INTERNAL_EVENTS = [
  Events.EVENT_SCROLLBAR_WIDTH_CHANGED,
  Events.EVENT_CHECKBOX_CHANGED,
  Events.EVENT_HEIGHT_SCALE_CHANGED,
  Events.EVENT_BODY_HEIGHT_CHANGED,
  Events.EVENT_COLUMN_CONTAINER_WIDTH_CHANGED,
  Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,
  Events.EVENT_SCROLL_VISIBILITY_CHANGED,
  Events.EVENT_COLUMN_HOVER_CHANGED,
  Events.EVENT_FLASH_CELLS,
  Events.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED,
  Events.EVENT_DISPLAYED_ROWS_CHANGED,
  Events.EVENT_LEFT_PINNED_WIDTH_CHANGED,
  Events.EVENT_RIGHT_PINNED_WIDTH_CHANGED,
  Events.EVENT_ROW_CONTAINER_HEIGHT_CHANGED,
  Events.EVENT_STORE_UPDATED,
  Events.EVENT_COLUMN_PANEL_ITEM_DRAG_START,
  Events.EVENT_COLUMN_PANEL_ITEM_DRAG_END,
  Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_START,
  Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_END,
  Events.EVENT_FULL_WIDTH_ROW_FOCUSED,
  Events.EVENT_HEADER_HEIGHT_CHANGED,
  Events.EVENT_COLUMN_HEADER_HEIGHT_CHANGED,
  Events.EVENT_CELL_FOCUS_CLEARED,
  Events.EVENT_GRID_STYLES_CHANGED,
  Events.EVENT_FILTER_DESTROYED,
  Events.EVENT_ROW_DATA_UPDATE_STARTED,
  Events.EVENT_ADVANCED_FILTER_ENABLED_CHANGED,
  Events.EVENT_DATA_TYPES_INFERRED,
  Events.EVENT_FIELD_VALUE_CHANGED,
  Events.EVENT_FIELD_PICKER_VALUE_SELECTED,
  Events.EVENT_SUPPRESS_COLUMN_MOVE_CHANGED,
  Events.EVENT_SUPPRESS_MENU_HIDE_CHANGED,
  Events.EVENT_SUPPRESS_FIELD_DOT_NOTATION,
  Events.EVENT_ROW_COUNT_READY,
  Events.EVENT_SIDE_BAR_UPDATED
];
// events that are available for use by users of AG Grid and so should be documented
/** EVENTS that should be exposed via code generation for the framework components.  */
_ComponentUtil.PUBLIC_EVENTS = _ComponentUtil.EVENTS.filter((e) => !includes(_ComponentUtil.EXCLUDED_INTERNAL_EVENTS, e));
// onXXX methods, based on the above events
_ComponentUtil.EVENT_CALLBACKS = _ComponentUtil.EVENTS.map((event) => _ComponentUtil.getCallbackForEvent(event));
_ComponentUtil.BOOLEAN_PROPERTIES = PropertyKeys.BOOLEAN_PROPERTIES;
_ComponentUtil.ALL_PROPERTIES = PropertyKeys.ALL_PROPERTIES;
_ComponentUtil.ALL_PROPERTIES_AND_CALLBACKS = [..._ComponentUtil.ALL_PROPERTIES, ..._ComponentUtil.EVENT_CALLBACKS];
_ComponentUtil.ALL_PROPERTIES_AND_CALLBACKS_SET = new Set(_ComponentUtil.ALL_PROPERTIES_AND_CALLBACKS);
var ComponentUtil = _ComponentUtil;

// community-modules/core/src/components/agStackComponentsRegistry.ts
var AgStackComponentsRegistry = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.componentsMappedByName = {};
  }
  setupComponents(components) {
    if (components) {
      components.forEach((componentMeta) => this.addComponent(componentMeta));
    }
  }
  addComponent(componentMeta) {
    const classEscaped = componentMeta.componentName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
    const classUpperCase = classEscaped.toUpperCase();
    this.componentsMappedByName[classUpperCase] = componentMeta.componentClass;
  }
  getComponentClass(htmlTag) {
    return this.componentsMappedByName[htmlTag];
  }
};
AgStackComponentsRegistry = __decorateClass([
  Bean("agStackComponentsRegistry")
], AgStackComponentsRegistry);

// community-modules/core/src/utils/aria.ts
var aria_exports = {};
__export(aria_exports, {
  getAriaCheckboxStateName: () => getAriaCheckboxStateName,
  getAriaLabel: () => getAriaLabel,
  getAriaLevel: () => getAriaLevel,
  getAriaPosInSet: () => getAriaPosInSet,
  getAriaSortState: () => getAriaSortState,
  removeAriaExpanded: () => removeAriaExpanded,
  removeAriaSort: () => removeAriaSort,
  setAriaActiveDescendant: () => setAriaActiveDescendant,
  setAriaAtomic: () => setAriaAtomic,
  setAriaChecked: () => setAriaChecked,
  setAriaColCount: () => setAriaColCount,
  setAriaColIndex: () => setAriaColIndex,
  setAriaColSpan: () => setAriaColSpan,
  setAriaControls: () => setAriaControls,
  setAriaDescribedBy: () => setAriaDescribedBy,
  setAriaDisabled: () => setAriaDisabled,
  setAriaExpanded: () => setAriaExpanded,
  setAriaHidden: () => setAriaHidden,
  setAriaLabel: () => setAriaLabel,
  setAriaLabelledBy: () => setAriaLabelledBy,
  setAriaLevel: () => setAriaLevel,
  setAriaLive: () => setAriaLive,
  setAriaMultiSelectable: () => setAriaMultiSelectable,
  setAriaPosInSet: () => setAriaPosInSet,
  setAriaRelevant: () => setAriaRelevant,
  setAriaRole: () => setAriaRole,
  setAriaRowCount: () => setAriaRowCount,
  setAriaRowIndex: () => setAriaRowIndex,
  setAriaSelected: () => setAriaSelected,
  setAriaSetSize: () => setAriaSetSize,
  setAriaSort: () => setAriaSort
});
function toggleAriaAttribute(element, attribute, value) {
  if (value == null || typeof value === "string" && value == "") {
    removeAriaAttribute(element, attribute);
  } else {
    setAriaAttribute(element, attribute, value);
  }
}
function setAriaAttribute(element, attribute, value) {
  element.setAttribute(ariaAttributeName(attribute), value.toString());
}
function removeAriaAttribute(element, attribute) {
  element.removeAttribute(ariaAttributeName(attribute));
}
function ariaAttributeName(attribute) {
  return `aria-${attribute}`;
}
function setAriaRole(element, role) {
  if (role) {
    element.setAttribute("role", role);
  } else {
    element.removeAttribute("role");
  }
}
function getAriaSortState(sortDirection) {
  let sort;
  if (sortDirection === "asc") {
    sort = "ascending";
  } else if (sortDirection === "desc") {
    sort = "descending";
  } else if (sortDirection === "mixed") {
    sort = "other";
  } else {
    sort = "none";
  }
  return sort;
}
function getAriaLevel(element) {
  return parseInt(element.getAttribute("aria-level"), 10);
}
function getAriaPosInSet(element) {
  return parseInt(element.getAttribute("aria-posinset"), 10);
}
function getAriaLabel(element) {
  return element.getAttribute("aria-label");
}
function setAriaLabel(element, label) {
  toggleAriaAttribute(element, "label", label);
}
function setAriaLabelledBy(element, labelledBy) {
  toggleAriaAttribute(element, "labelledby", labelledBy);
}
function setAriaDescribedBy(element, describedby) {
  toggleAriaAttribute(element, "describedby", describedby);
}
function setAriaLive(element, live) {
  toggleAriaAttribute(element, "live", live);
}
function setAriaAtomic(element, atomic) {
  toggleAriaAttribute(element, "atomic", atomic);
}
function setAriaRelevant(element, relevant) {
  toggleAriaAttribute(element, "relevant", relevant);
}
function setAriaLevel(element, level) {
  toggleAriaAttribute(element, "level", level);
}
function setAriaDisabled(element, disabled) {
  toggleAriaAttribute(element, "disabled", disabled);
}
function setAriaHidden(element, hidden) {
  toggleAriaAttribute(element, "hidden", hidden);
}
function setAriaActiveDescendant(element, descendantId) {
  toggleAriaAttribute(element, "activedescendant", descendantId);
}
function setAriaExpanded(element, expanded) {
  setAriaAttribute(element, "expanded", expanded);
}
function removeAriaExpanded(element) {
  removeAriaAttribute(element, "expanded");
}
function setAriaSetSize(element, setsize) {
  setAriaAttribute(element, "setsize", setsize);
}
function setAriaPosInSet(element, position) {
  setAriaAttribute(element, "posinset", position);
}
function setAriaMultiSelectable(element, multiSelectable) {
  setAriaAttribute(element, "multiselectable", multiSelectable);
}
function setAriaRowCount(element, rowCount) {
  setAriaAttribute(element, "rowcount", rowCount);
}
function setAriaRowIndex(element, rowIndex) {
  setAriaAttribute(element, "rowindex", rowIndex);
}
function setAriaColCount(element, colCount) {
  setAriaAttribute(element, "colcount", colCount);
}
function setAriaColIndex(element, colIndex) {
  setAriaAttribute(element, "colindex", colIndex);
}
function setAriaColSpan(element, colSpan) {
  setAriaAttribute(element, "colspan", colSpan);
}
function setAriaSort(element, sort) {
  setAriaAttribute(element, "sort", sort);
}
function removeAriaSort(element) {
  removeAriaAttribute(element, "sort");
}
function setAriaSelected(element, selected) {
  toggleAriaAttribute(element, "selected", selected);
}
function setAriaChecked(element, checked) {
  setAriaAttribute(element, "checked", checked === void 0 ? "mixed" : checked);
}
function setAriaControls(controllerElement, controlledElement) {
  toggleAriaAttribute(controllerElement, "controls", controlledElement.id);
  setAriaLabelledBy(controlledElement, controllerElement.id);
}
function getAriaCheckboxStateName(translate, state) {
  return state === void 0 ? translate("ariaIndeterminate", "indeterminate") : state === true ? translate("ariaChecked", "checked") : translate("ariaUnchecked", "unchecked");
}

// community-modules/core/src/utils/browser.ts
var browser_exports = {};
__export(browser_exports, {
  browserSupportsPreventScroll: () => browserSupportsPreventScroll,
  getBodyHeight: () => getBodyHeight,
  getBodyWidth: () => getBodyWidth,
  getMaxDivHeight: () => getMaxDivHeight,
  getSafariVersion: () => getSafariVersion,
  getScrollbarWidth: () => getScrollbarWidth,
  getTabIndex: () => getTabIndex,
  isBrowserChrome: () => isBrowserChrome,
  isBrowserFirefox: () => isBrowserFirefox,
  isBrowserSafari: () => isBrowserSafari,
  isIOSUserAgent: () => isIOSUserAgent,
  isInvisibleScrollbar: () => isInvisibleScrollbar,
  isMacOsUserAgent: () => isMacOsUserAgent
});
var isSafari;
var safariVersion;
var isChrome;
var isFirefox;
var isMacOs;
var isIOS;
var invisibleScrollbar;
var browserScrollbarWidth;
function isBrowserSafari() {
  if (isSafari === void 0) {
    isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  }
  return isSafari;
}
function getSafariVersion() {
  if (safariVersion === void 0) {
    if (isBrowserSafari()) {
      const versionMatch = navigator.userAgent.match(/version\/(\d+)/i);
      if (versionMatch) {
        safariVersion = versionMatch[1] != null ? parseFloat(versionMatch[1]) : 0;
      }
    } else {
      safariVersion = 0;
    }
  }
  return safariVersion;
}
function isBrowserChrome() {
  if (isChrome === void 0) {
    const win = window;
    isChrome = !!win.chrome && (!!win.chrome.webstore || !!win.chrome.runtime) || /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
  }
  return isChrome;
}
function isBrowserFirefox() {
  if (isFirefox === void 0) {
    isFirefox = /(firefox)/i.test(navigator.userAgent);
  }
  return isFirefox;
}
function isMacOsUserAgent() {
  if (isMacOs === void 0) {
    isMacOs = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
  }
  return isMacOs;
}
function isIOSUserAgent() {
  if (isIOS === void 0) {
    isIOS = /iPad|iPhone|iPod/.test(navigator.platform) || // eslint-disable-next-line
    navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
  }
  return isIOS;
}
function browserSupportsPreventScroll() {
  return !isBrowserSafari() || getSafariVersion() >= 15;
}
function getTabIndex(el) {
  if (!el) {
    return null;
  }
  const numberTabIndex = el.tabIndex;
  const tabIndex = el.getAttribute("tabIndex");
  if (numberTabIndex === -1 && (tabIndex === null || tabIndex === "" && !isBrowserFirefox())) {
    return null;
  }
  return numberTabIndex.toString();
}
function getMaxDivHeight() {
  if (!document.body) {
    return -1;
  }
  let res = 1e6;
  const testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6e6 : 1e9;
  const div = document.createElement("div");
  document.body.appendChild(div);
  while (true) {
    const test = res * 2;
    div.style.height = test + "px";
    if (test > testUpTo || div.clientHeight !== test) {
      break;
    } else {
      res = test;
    }
  }
  document.body.removeChild(div);
  return res;
}
function getBodyWidth() {
  var _a, _b, _c;
  return (_c = (_a = document.body) == null ? void 0 : _a.clientWidth) != null ? _c : window.innerHeight || ((_b = document.documentElement) == null ? void 0 : _b.clientWidth) || -1;
}
function getBodyHeight() {
  var _a, _b, _c;
  return (_c = (_a = document.body) == null ? void 0 : _a.clientHeight) != null ? _c : window.innerHeight || ((_b = document.documentElement) == null ? void 0 : _b.clientHeight) || -1;
}
function getScrollbarWidth() {
  if (browserScrollbarWidth == null) {
    initScrollbarWidthAndVisibility();
  }
  return browserScrollbarWidth;
}
function initScrollbarWidthAndVisibility() {
  const body = document.body;
  const div = document.createElement("div");
  div.style.width = div.style.height = "100px";
  div.style.opacity = "0";
  div.style.overflow = "scroll";
  div.style.msOverflowStyle = "scrollbar";
  div.style.position = "absolute";
  body.appendChild(div);
  let width = div.offsetWidth - div.clientWidth;
  if (width === 0 && div.clientWidth === 0) {
    width = null;
  }
  if (div.parentNode) {
    div.parentNode.removeChild(div);
  }
  if (width != null) {
    browserScrollbarWidth = width;
    invisibleScrollbar = width === 0;
  }
}
function isInvisibleScrollbar() {
  if (invisibleScrollbar == null) {
    initScrollbarWidthAndVisibility();
  }
  return invisibleScrollbar;
}

// community-modules/core/src/utils/date.ts
var date_exports = {};
__export(date_exports, {
  dateToFormattedString: () => dateToFormattedString,
  parseDateTimeFromString: () => parseDateTimeFromString,
  serialiseDate: () => serialiseDate
});

// community-modules/core/src/utils/number.ts
var number_exports = {};
__export(number_exports, {
  cleanNumber: () => cleanNumber,
  createArrayOfNumbers: () => createArrayOfNumbers,
  decToHex: () => decToHex,
  formatNumberCommas: () => formatNumberCommas,
  formatNumberTwoDecimalPlacesAndCommas: () => formatNumberTwoDecimalPlacesAndCommas,
  padStartWidthZeros: () => padStartWidthZeros,
  sum: () => sum
});
function padStartWidthZeros(value, totalStringSize) {
  return value.toString().padStart(totalStringSize, "0");
}
function createArrayOfNumbers(first, last2) {
  const result = [];
  for (let i = first; i <= last2; i++) {
    result.push(i);
  }
  return result;
}
function cleanNumber(value) {
  if (typeof value === "string") {
    value = parseInt(value, 10);
  }
  if (typeof value === "number") {
    return Math.floor(value);
  }
  return null;
}
function decToHex(number, bytes) {
  let hex = "";
  for (let i = 0; i < bytes; i++) {
    hex += String.fromCharCode(number & 255);
    number >>>= 8;
  }
  return hex;
}
function formatNumberTwoDecimalPlacesAndCommas(value, thousandSeparator, decimalSeparator) {
  if (typeof value !== "number") {
    return "";
  }
  return formatNumberCommas(Math.round(value * 100) / 100, thousandSeparator, decimalSeparator);
}
function formatNumberCommas(value, thousandSeparator, decimalSeparator) {
  if (typeof value !== "number") {
    return "";
  }
  return value.toString().replace(".", decimalSeparator).replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandSeparator}`);
}
function sum(values2) {
  return values2 == null ? null : values2.reduce((total, value) => total + value, 0);
}

// community-modules/core/src/utils/date.ts
function serialiseDate(date, includeTime = true, separator = "-") {
  if (!date) {
    return null;
  }
  let serialised = [date.getFullYear(), date.getMonth() + 1, date.getDate()].map((part) => padStartWidthZeros(part, 2)).join(separator);
  if (includeTime) {
    serialised += " " + [date.getHours(), date.getMinutes(), date.getSeconds()].map((part) => padStartWidthZeros(part, 2)).join(":");
  }
  return serialised;
}
var calculateOrdinal = (value) => {
  if (value > 3 && value < 21) {
    return "th";
  }
  const remainder = value % 10;
  switch (remainder) {
    case 1:
      return "st";
    case 2:
      return "nd";
    case 3:
      return "rd";
  }
  return "th";
};
function dateToFormattedString(date, format = "YYYY-MM-DD") {
  const fullYear = padStartWidthZeros(date.getFullYear(), 4);
  const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ];
  const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  const replace = {
    YYYY: () => fullYear.slice(fullYear.length - 4, fullYear.length),
    YY: () => fullYear.slice(fullYear.length - 2, fullYear.length),
    Y: () => `${date.getFullYear()}`,
    MMMM: () => months[date.getMonth()],
    MMM: () => months[date.getMonth()].slice(0, 3),
    MM: () => padStartWidthZeros(date.getMonth() + 1, 2),
    Mo: () => `${date.getMonth() + 1}${calculateOrdinal(date.getMonth() + 1)}`,
    M: () => `${date.getMonth() + 1}`,
    Do: () => `${date.getDate()}${calculateOrdinal(date.getDate())}`,
    DD: () => padStartWidthZeros(date.getDate(), 2),
    D: () => `${date.getDate()}`,
    dddd: () => days[date.getDay()],
    ddd: () => days[date.getDay()].slice(0, 3),
    dd: () => days[date.getDay()].slice(0, 2),
    do: () => `${date.getDay()}${calculateOrdinal(date.getDay())}`,
    d: () => `${date.getDay()}`
  };
  const regexp = new RegExp(Object.keys(replace).join("|"), "g");
  return format.replace(regexp, (match) => {
    if (match in replace) {
      return replace[match]();
    }
    return match;
  });
}
function parseDateTimeFromString(value) {
  if (!value) {
    return null;
  }
  const [dateStr, timeStr] = value.split(" ");
  if (!dateStr) {
    return null;
  }
  const fields = dateStr.split("-").map((f) => parseInt(f, 10));
  if (fields.filter((f) => !isNaN(f)).length !== 3) {
    return null;
  }
  const [year, month, day] = fields;
  const date = new Date(year, month - 1, day);
  if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
    return null;
  }
  if (!timeStr || timeStr === "00:00:00") {
    return date;
  }
  const [hours, minutes, seconds] = timeStr.split(":").map((part) => parseInt(part, 10));
  if (hours >= 0 && hours < 24) {
    date.setHours(hours);
  }
  if (minutes >= 0 && minutes < 60) {
    date.setMinutes(minutes);
  }
  if (seconds >= 0 && seconds < 60) {
    date.setSeconds(seconds);
  }
  return date;
}

// community-modules/core/src/utils/dom.ts
var dom_exports = {};
__export(dom_exports, {
  FOCUSABLE_EXCLUDE: () => FOCUSABLE_EXCLUDE,
  FOCUSABLE_SELECTOR: () => FOCUSABLE_SELECTOR,
  addOrRemoveAttribute: () => addOrRemoveAttribute,
  addStylesToElement: () => addStylesToElement,
  bindCellRendererToHtmlElement: () => bindCellRendererToHtmlElement,
  clearElement: () => clearElement,
  copyNodeList: () => copyNodeList,
  ensureDomOrder: () => ensureDomOrder,
  formatSize: () => formatSize,
  getAbsoluteHeight: () => getAbsoluteHeight,
  getAbsoluteWidth: () => getAbsoluteWidth,
  getElementRectWithOffset: () => getElementRectWithOffset,
  getElementSize: () => getElementSize,
  getInnerHeight: () => getInnerHeight,
  getInnerWidth: () => getInnerWidth,
  getScrollLeft: () => getScrollLeft,
  insertWithDomOrder: () => insertWithDomOrder,
  isElementChildOfClass: () => isElementChildOfClass,
  isFocusableFormField: () => isFocusableFormField,
  isHorizontalScrollShowing: () => isHorizontalScrollShowing,
  isInDOM: () => isInDOM,
  isNodeOrElement: () => isNodeOrElement,
  isRtlNegativeScroll: () => isRtlNegativeScroll,
  isVerticalScrollShowing: () => isVerticalScrollShowing,
  isVisible: () => isVisible,
  iterateNamedNodeMap: () => iterateNamedNodeMap,
  loadTemplate: () => loadTemplate,
  nodeListForEach: () => nodeListForEach,
  radioCssClass: () => radioCssClass,
  removeFromParent: () => removeFromParent,
  setDisabled: () => setDisabled,
  setDisplayed: () => setDisplayed,
  setDomChildOrder: () => setDomChildOrder,
  setElementHeight: () => setElementHeight,
  setElementWidth: () => setElementWidth,
  setFixedHeight: () => setFixedHeight,
  setFixedWidth: () => setFixedWidth,
  setScrollLeft: () => setScrollLeft,
  setVisible: () => setVisible
});
var rtlNegativeScroll;
function radioCssClass(element, elementClass, otherElementClass) {
  const parent = element.parentElement;
  let sibling = parent && parent.firstChild;
  while (sibling) {
    if (elementClass) {
      sibling.classList.toggle(elementClass, sibling === element);
    }
    if (otherElementClass) {
      sibling.classList.toggle(otherElementClass, sibling !== element);
    }
    sibling = sibling.nextSibling;
  }
}
var FOCUSABLE_SELECTOR = "[tabindex], input, select, button, textarea, [href]";
var FOCUSABLE_EXCLUDE = "[disabled], .ag-disabled:not(.ag-button), .ag-disabled *";
function isFocusableFormField(element) {
  const matches = Element.prototype.matches || Element.prototype.msMatchesSelector;
  const inputSelector = "input, select, button, textarea";
  const isFocusable = matches.call(element, inputSelector);
  const isNotFocusable = matches.call(element, FOCUSABLE_EXCLUDE);
  const isElementVisible = isVisible(element);
  const focusable = isFocusable && !isNotFocusable && isElementVisible;
  return focusable;
}
function setDisplayed(element, displayed, options = {}) {
  const { skipAriaHidden } = options;
  element.classList.toggle("ag-hidden", !displayed);
  if (!skipAriaHidden) {
    setAriaHidden(element, !displayed);
  }
}
function setVisible(element, visible, options = {}) {
  const { skipAriaHidden } = options;
  element.classList.toggle("ag-invisible", !visible);
  if (!skipAriaHidden) {
    setAriaHidden(element, !visible);
  }
}
function setDisabled(element, disabled) {
  const attributeName = "disabled";
  const addOrRemoveDisabledAttribute = disabled ? (e) => e.setAttribute(attributeName, "") : (e) => e.removeAttribute(attributeName);
  addOrRemoveDisabledAttribute(element);
  nodeListForEach(element.querySelectorAll("input"), (input) => addOrRemoveDisabledAttribute(input));
}
function isElementChildOfClass(element, cls, maxNest) {
  let counter = 0;
  while (element) {
    if (element.classList.contains(cls)) {
      return true;
    }
    element = element.parentElement;
    if (typeof maxNest == "number") {
      if (++counter > maxNest) {
        break;
      }
    } else if (element === maxNest) {
      break;
    }
  }
  return false;
}
function getElementSize(el) {
  const {
    height,
    width,
    borderTopWidth,
    borderRightWidth,
    borderBottomWidth,
    borderLeftWidth,
    paddingTop,
    paddingRight,
    paddingBottom,
    paddingLeft,
    marginTop,
    marginRight,
    marginBottom,
    marginLeft,
    boxSizing
  } = window.getComputedStyle(el);
  return {
    height: parseFloat(height || "0"),
    width: parseFloat(width || "0"),
    borderTopWidth: parseFloat(borderTopWidth || "0"),
    borderRightWidth: parseFloat(borderRightWidth || "0"),
    borderBottomWidth: parseFloat(borderBottomWidth || "0"),
    borderLeftWidth: parseFloat(borderLeftWidth || "0"),
    paddingTop: parseFloat(paddingTop || "0"),
    paddingRight: parseFloat(paddingRight || "0"),
    paddingBottom: parseFloat(paddingBottom || "0"),
    paddingLeft: parseFloat(paddingLeft || "0"),
    marginTop: parseFloat(marginTop || "0"),
    marginRight: parseFloat(marginRight || "0"),
    marginBottom: parseFloat(marginBottom || "0"),
    marginLeft: parseFloat(marginLeft || "0"),
    boxSizing
  };
}
function getInnerHeight(el) {
  const size = getElementSize(el);
  if (size.boxSizing === "border-box") {
    return size.height - size.paddingTop - size.paddingBottom;
  }
  return size.height;
}
function getInnerWidth(el) {
  const size = getElementSize(el);
  if (size.boxSizing === "border-box") {
    return size.width - size.paddingLeft - size.paddingRight;
  }
  return size.width;
}
function getAbsoluteHeight(el) {
  const size = getElementSize(el);
  const marginRight = size.marginBottom + size.marginTop;
  return Math.ceil(el.offsetHeight + marginRight);
}
function getAbsoluteWidth(el) {
  const size = getElementSize(el);
  const marginWidth = size.marginLeft + size.marginRight;
  return Math.ceil(el.offsetWidth + marginWidth);
}
function getElementRectWithOffset(el) {
  const offsetElementRect = el.getBoundingClientRect();
  const { borderTopWidth, borderLeftWidth, borderRightWidth, borderBottomWidth } = getElementSize(el);
  return {
    top: offsetElementRect.top + (borderTopWidth || 0),
    left: offsetElementRect.left + (borderLeftWidth || 0),
    right: offsetElementRect.right + (borderRightWidth || 0),
    bottom: offsetElementRect.bottom + (borderBottomWidth || 0)
  };
}
function isRtlNegativeScroll() {
  if (typeof rtlNegativeScroll === "boolean") {
    return rtlNegativeScroll;
  }
  const template = document.createElement("div");
  template.style.direction = "rtl";
  template.style.width = "1px";
  template.style.height = "1px";
  template.style.position = "fixed";
  template.style.top = "0px";
  template.style.overflow = "hidden";
  template.dir = "rtl";
  template.innerHTML = /* html */
  `<div style="width: 2px">
            <span style="display: inline-block; width: 1px"></span>
            <span style="display: inline-block; width: 1px"></span>
        </div>`;
  document.body.appendChild(template);
  template.scrollLeft = 1;
  rtlNegativeScroll = Math.floor(template.scrollLeft) === 0;
  document.body.removeChild(template);
  return rtlNegativeScroll;
}
function getScrollLeft(element, rtl) {
  let scrollLeft = element.scrollLeft;
  if (rtl) {
    scrollLeft = Math.abs(scrollLeft);
    if (isBrowserChrome() && !isRtlNegativeScroll()) {
      scrollLeft = element.scrollWidth - element.clientWidth - scrollLeft;
    }
  }
  return scrollLeft;
}
function setScrollLeft(element, value, rtl) {
  if (rtl) {
    if (isRtlNegativeScroll()) {
      value *= -1;
    } else if (isBrowserSafari() || isBrowserChrome()) {
      value = element.scrollWidth - element.clientWidth - value;
    }
  }
  element.scrollLeft = value;
}
function clearElement(el) {
  while (el && el.firstChild) {
    el.removeChild(el.firstChild);
  }
}
function removeFromParent(node) {
  if (node && node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
function isInDOM(element) {
  return !!element.offsetParent;
}
function isVisible(element) {
  const el = element;
  if (el.checkVisibility) {
    return el.checkVisibility({ checkVisibilityCSS: true });
  }
  const isHidden = !isInDOM(element) || window.getComputedStyle(element).visibility !== "visible";
  return !isHidden;
}
function loadTemplate(template) {
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = (template || "").trim();
  return tempDiv.firstChild;
}
function ensureDomOrder(eContainer, eChild, eChildBefore) {
  if (eChildBefore && eChildBefore.nextSibling === eChild) {
    return;
  }
  if (eChildBefore) {
    if (eChildBefore.nextSibling) {
      eContainer.insertBefore(eChild, eChildBefore.nextSibling);
    } else {
      eContainer.appendChild(eChild);
    }
  } else {
    if (eContainer.firstChild && eContainer.firstChild !== eChild) {
      eContainer.insertAdjacentElement("afterbegin", eChild);
    }
  }
}
function setDomChildOrder(eContainer, orderedChildren) {
  for (let i = 0; i < orderedChildren.length; i++) {
    const correctCellAtIndex = orderedChildren[i];
    const actualCellAtIndex = eContainer.children[i];
    if (actualCellAtIndex !== correctCellAtIndex) {
      eContainer.insertBefore(correctCellAtIndex, actualCellAtIndex);
    }
  }
}
function insertWithDomOrder(eContainer, eToInsert, eChildBefore) {
  if (eChildBefore) {
    eChildBefore.insertAdjacentElement("afterend", eToInsert);
  } else {
    if (eContainer.firstChild) {
      eContainer.insertAdjacentElement("afterbegin", eToInsert);
    } else {
      eContainer.appendChild(eToInsert);
    }
  }
}
function addStylesToElement(eElement, styles) {
  if (!styles) {
    return;
  }
  for (const [key, value] of Object.entries(styles)) {
    if (!key || !key.length || value == null) {
      continue;
    }
    const parsedKey = camelCaseToHyphenated(key);
    const valueAsString = value.toString();
    const parsedValue = valueAsString.replace(/\s*!important/g, "");
    const priority = parsedValue.length != valueAsString.length ? "important" : void 0;
    eElement.style.setProperty(parsedKey, parsedValue, priority);
  }
}
function isHorizontalScrollShowing(element) {
  return element.clientWidth < element.scrollWidth;
}
function isVerticalScrollShowing(element) {
  return element.clientHeight < element.scrollHeight;
}
function setElementWidth(element, width) {
  if (width === "flex") {
    element.style.removeProperty("width");
    element.style.removeProperty("minWidth");
    element.style.removeProperty("maxWidth");
    element.style.flex = "1 1 auto";
  } else {
    setFixedWidth(element, width);
  }
}
function setFixedWidth(element, width) {
  width = formatSize(width);
  element.style.width = width.toString();
  element.style.maxWidth = width.toString();
  element.style.minWidth = width.toString();
}
function setElementHeight(element, height) {
  if (height === "flex") {
    element.style.removeProperty("height");
    element.style.removeProperty("minHeight");
    element.style.removeProperty("maxHeight");
    element.style.flex = "1 1 auto";
  } else {
    setFixedHeight(element, height);
  }
}
function setFixedHeight(element, height) {
  height = formatSize(height);
  element.style.height = height.toString();
  element.style.maxHeight = height.toString();
  element.style.minHeight = height.toString();
}
function formatSize(size) {
  if (typeof size === "number") {
    return `${size}px`;
  }
  return size;
}
function isNodeOrElement(o) {
  return o instanceof Node || o instanceof HTMLElement;
}
function copyNodeList(nodeList) {
  if (nodeList == null) {
    return [];
  }
  const result = [];
  nodeListForEach(nodeList, (node) => result.push(node));
  return result;
}
function iterateNamedNodeMap(map, callback) {
  if (!map) {
    return;
  }
  for (let i = 0; i < map.length; i++) {
    const attr = map[i];
    callback(attr.name, attr.value);
  }
}
function addOrRemoveAttribute(element, name, value) {
  if (value == null) {
    element.removeAttribute(name);
  } else {
    element.setAttribute(name, value.toString());
  }
}
function nodeListForEach(nodeList, action) {
  if (nodeList == null) {
    return;
  }
  for (let i = 0; i < nodeList.length; i++) {
    action(nodeList[i]);
  }
}
function bindCellRendererToHtmlElement(cellRendererPromise, eTarget) {
  cellRendererPromise.then((cellRenderer) => {
    const gui = cellRenderer.getGui();
    if (gui != null) {
      if (typeof gui === "object") {
        eTarget.appendChild(gui);
      } else {
        eTarget.innerHTML = gui;
      }
    }
  });
}

// community-modules/core/src/utils/fuzzyMatch.ts
var fuzzyMatch_exports = {};
__export(fuzzyMatch_exports, {
  fuzzyCheckStrings: () => fuzzyCheckStrings,
  fuzzySuggestions: () => fuzzySuggestions
});
function fuzzyCheckStrings(inputValues, validValues, allSuggestions) {
  const fuzzyMatches = {};
  const invalidInputs = inputValues.filter(
    (inputValue) => !validValues.some(
      (validValue) => validValue === inputValue
    )
  );
  if (invalidInputs.length > 0) {
    invalidInputs.forEach(
      (invalidInput) => fuzzyMatches[invalidInput] = fuzzySuggestions(invalidInput, allSuggestions).values
    );
  }
  return fuzzyMatches;
}
function fuzzySuggestions(inputValue, allSuggestions, hideIrrelevant, filterByPercentageOfBestMatch) {
  let thisSuggestions = allSuggestions.map((text, idx) => ({
    value: text,
    relevance: stringWeightedDistances(inputValue.toLowerCase(), text.toLocaleLowerCase()),
    idx
  }));
  thisSuggestions.sort((a, b) => b.relevance - a.relevance);
  if (hideIrrelevant) {
    thisSuggestions = thisSuggestions.filter((suggestion) => suggestion.relevance !== 0);
  }
  if (thisSuggestions.length > 0 && filterByPercentageOfBestMatch && filterByPercentageOfBestMatch > 0) {
    const bestMatch = thisSuggestions[0].relevance;
    const limit = bestMatch * filterByPercentageOfBestMatch;
    thisSuggestions = thisSuggestions.filter((suggestion) => limit - suggestion.relevance < 0);
  }
  const values2 = [];
  const indices = [];
  for (const suggestion of thisSuggestions) {
    values2.push(suggestion.value);
    indices.push(suggestion.idx);
  }
  return { values: values2, indices };
}
function stringWeightedDistances(str1, str2) {
  const a = str1.replace(/\s/g, "");
  const b = str2.replace(/\s/g, "");
  let weight = 0;
  let lastIndex = -1;
  for (let i = 0; i < a.length; i++) {
    const idx = b.indexOf(a[i], lastIndex + 1);
    if (idx === -1) {
      continue;
    }
    lastIndex = idx;
    weight += 100 - lastIndex * 100 / 1e4 * 100;
  }
  return weight;
}

// community-modules/core/src/utils/icon.ts
var icon_exports = {};
__export(icon_exports, {
  createIcon: () => createIcon,
  createIconNoSpan: () => createIconNoSpan,
  iconNameClassMap: () => iconNameClassMap
});
var iconNameClassMap = {
  // header column group shown when expanded (click to contract)
  columnGroupOpened: "expanded",
  // header column group shown when contracted (click to expand)
  columnGroupClosed: "contracted",
  // tool panel column group contracted (click to expand)
  columnSelectClosed: "tree-closed",
  // tool panel column group expanded (click to contract)
  columnSelectOpen: "tree-open",
  // column tool panel header expand/collapse all button, shown when some children are expanded and
  //     others are collapsed
  columnSelectIndeterminate: "tree-indeterminate",
  // shown on ghost icon while dragging column to the side of the grid to pin
  columnMovePin: "pin",
  // shown on ghost icon while dragging over part of the page that is not a drop zone
  columnMoveHide: "eye-slash",
  // shown on ghost icon while dragging columns to reorder
  columnMoveMove: "arrows",
  // animating icon shown when dragging a column to the right of the grid causes horizontal scrolling
  columnMoveLeft: "left",
  // animating icon shown when dragging a column to the left of the grid causes horizontal scrolling
  columnMoveRight: "right",
  // shown on ghost icon while dragging over Row Groups drop zone
  columnMoveGroup: "group",
  // shown on ghost icon while dragging over Values drop zone
  columnMoveValue: "aggregation",
  // shown on ghost icon while dragging over pivot drop zone
  columnMovePivot: "pivot",
  // shown on ghost icon while dragging over drop zone that doesn't support it, e.g.
  //     string column over aggregation drop zone
  dropNotAllowed: "not-allowed",
  // shown on row group when contracted (click to expand)
  groupContracted: "tree-closed",
  // shown on row group when expanded (click to contract)
  groupExpanded: "tree-open",
  // 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",
  // context menu chart item
  chart: "chart",
  // chart window title bar
  close: "cross",
  // X (remove) on column 'pill' after adding it to a drop zone list
  cancel: "cancel",
  // indicates the currently active pin state in the "Pin column" sub-menu of the column menu
  check: "tick",
  // "go to first" button in pagination controls
  first: "first",
  // "go to previous" button in pagination controls
  previous: "previous",
  // "go to next" button in pagination controls
  next: "next",
  // "go to last" button in pagination controls
  last: "last",
  // shown on top right of chart when chart is linked to range data (click to unlink)
  linked: "linked",
  // shown on top right of chart when chart is not linked to range data (click to link)
  unlinked: "unlinked",
  // "Choose colour" button on chart settings tab
  colorPicker: "color-picker",
  // rotating spinner shown by the loading cell renderer
  groupLoading: "loading",
  // button to launch enterprise column menu
  menu: "menu",
  menuAlt: "menu-alt",
  // filter tool panel tab
  filter: "filter",
  // column tool panel tab
  columns: "columns",
  // button in chart regular size window title bar (click to maximise)
  maximize: "maximize",
  // button in chart maximised window title bar (click to make regular size)
  minimize: "minimize",
  // "Pin column" item in column header menu
  menuPin: "pin",
  // "Value aggregation" column menu item (shown on numeric columns when grouping is active)"
  menuValue: "aggregation",
  // "Group by {column-name}" item in column header menu
  menuAddRowGroup: "group",
  // "Un-Group by {column-name}" item in column header menu
  menuRemoveRowGroup: "group",
  // context menu copy item
  clipboardCopy: "copy",
  // context menu cut item
  clipboardCut: "cut",
  // context menu paste item
  clipboardPaste: "paste",
  // identifies the pivot drop zone
  pivotPanel: "pivot",
  // "Row groups" drop zone in column tool panel
  rowGroupPanel: "group",
  // columns tool panel Values drop zone
  valuePanel: "aggregation",
  // drag handle used to pick up draggable columns
  columnDrag: "grip",
  // drag handle used to pick up draggable rows
  rowDrag: "grip",
  // context menu export item
  save: "save",
  // csv export
  csvExport: "csv",
  // excel export,
  excelExport: "excel",
  // icon on dropdown editors
  smallDown: "small-down",
  // version of small-right used in RTL mode
  smallLeft: "small-left",
  // separater between column 'pills' when you add multiple columns to the header drop zone
  smallRight: "small-right",
  smallUp: "small-up",
  // show on column header when column is sorted ascending
  sortAscending: "asc",
  // show on column header when column is sorted descending
  sortDescending: "desc",
  // show on column header when column has no sort, only when enabled with gridOptions.unSortIcon=true
  sortUnSort: "none",
  // 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",
  // 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"
};
function createIcon(iconName, gos, column) {
  const iconContents = createIconNoSpan(iconName, gos, column);
  if (iconContents) {
    const { className } = iconContents;
    if (typeof className === "string" && className.indexOf("ag-icon") > -1 || typeof className === "object" && className["ag-icon"]) {
      return iconContents;
    }
  }
  const eResult = document.createElement("span");
  eResult.appendChild(iconContents);
  return eResult;
}
function createIconNoSpan(iconName, gos, column, forceCreate) {
  let userProvidedIcon = null;
  const icons = column && column.getColDef().icons;
  if (icons) {
    userProvidedIcon = icons[iconName];
  }
  if (gos && !userProvidedIcon) {
    const optionsIcons = gos.get("icons");
    if (optionsIcons) {
      userProvidedIcon = optionsIcons[iconName];
    }
  }
  if (userProvidedIcon) {
    let rendererResult;
    if (typeof userProvidedIcon === "function") {
      rendererResult = userProvidedIcon();
    } else if (typeof userProvidedIcon === "string") {
      rendererResult = userProvidedIcon;
    } else {
      throw new Error("icon from grid options needs to be a string or a function");
    }
    if (typeof rendererResult === "string") {
      return loadTemplate(rendererResult);
    }
    if (isNodeOrElement(rendererResult)) {
      return rendererResult;
    }
    console.warn("AG Grid: iconRenderer should return back a string or a dom object");
  } else {
    const span = document.createElement("span");
    let cssClass = iconNameClassMap[iconName];
    if (!cssClass) {
      if (!forceCreate) {
        console.warn(`AG Grid: Did not find icon ${iconName}`);
        cssClass = "";
      } else {
        cssClass = iconName;
      }
    }
    span.setAttribute("class", `ag-icon ag-icon-${cssClass}`);
    span.setAttribute("unselectable", "on");
    setAriaRole(span, "presentation");
    return span;
  }
}

// community-modules/core/src/utils/keyboard.ts
var keyboard_exports = {};
__export(keyboard_exports, {
  isDeleteKey: () => isDeleteKey,
  isEventFromPrintableCharacter: () => isEventFromPrintableCharacter,
  isUserSuppressingHeaderKeyboardEvent: () => isUserSuppressingHeaderKeyboardEvent,
  isUserSuppressingKeyboardEvent: () => isUserSuppressingKeyboardEvent,
  normaliseQwertyAzerty: () => normaliseQwertyAzerty
});

// community-modules/core/src/constants/keyCode.ts
var KeyCode = class {
};
KeyCode.BACKSPACE = "Backspace";
KeyCode.TAB = "Tab";
KeyCode.ENTER = "Enter";
KeyCode.ESCAPE = "Escape";
KeyCode.SPACE = " ";
KeyCode.LEFT = "ArrowLeft";
KeyCode.UP = "ArrowUp";
KeyCode.RIGHT = "ArrowRight";
KeyCode.DOWN = "ArrowDown";
KeyCode.DELETE = "Delete";
KeyCode.F2 = "F2";
KeyCode.PAGE_UP = "PageUp";
KeyCode.PAGE_DOWN = "PageDown";
KeyCode.PAGE_HOME = "Home";
KeyCode.PAGE_END = "End";
// these should be used with `event.code` instead of `event.key`
// as `event.key` changes when non-latin keyboards are used
KeyCode.A = "KeyA";
KeyCode.C = "KeyC";
KeyCode.D = "KeyD";
KeyCode.V = "KeyV";
KeyCode.X = "KeyX";
KeyCode.Y = "KeyY";
KeyCode.Z = "KeyZ";

// community-modules/core/src/utils/keyboard.ts
var A_KEYCODE = 65;
var C_KEYCODE = 67;
var V_KEYCODE = 86;
var D_KEYCODE = 68;
var Z_KEYCODE = 90;
var Y_KEYCODE = 89;
function isEventFromPrintableCharacter(event) {
  if (event.altKey || event.ctrlKey || event.metaKey) {
    return false;
  }
  const printableCharacter = event.key.length === 1;
  return printableCharacter;
}
function isUserSuppressingKeyboardEvent(gos, keyboardEvent, rowNode, column, editing) {
  const colDefFunc = column ? column.getColDef().suppressKeyboardEvent : void 0;
  if (!colDefFunc) {
    return false;
  }
  const params = gos.addGridCommonParams({
    event: keyboardEvent,
    editing,
    column,
    node: rowNode,
    data: rowNode.data,
    colDef: column.getColDef()
  });
  if (colDefFunc) {
    const colDefFuncResult = colDefFunc(params);
    if (colDefFuncResult) {
      return true;
    }
  }
  return false;
}
function isUserSuppressingHeaderKeyboardEvent(gos, keyboardEvent, headerRowIndex, column) {
  const colDef = column.getDefinition();
  const colDefFunc = colDef && colDef.suppressHeaderKeyboardEvent;
  if (!exists(colDefFunc)) {
    return false;
  }
  const params = gos.addGridCommonParams({
    colDef,
    column,
    headerRowIndex,
    event: keyboardEvent
  });
  return !!colDefFunc(params);
}
function normaliseQwertyAzerty(keyboardEvent) {
  const { keyCode } = keyboardEvent;
  let code;
  switch (keyCode) {
    case A_KEYCODE:
      code = KeyCode.A;
      break;
    case C_KEYCODE:
      code = KeyCode.C;
      break;
    case V_KEYCODE:
      code = KeyCode.V;
      break;
    case D_KEYCODE:
      code = KeyCode.D;
      break;
    case Z_KEYCODE:
      code = KeyCode.Z;
      break;
    case Y_KEYCODE:
      code = KeyCode.Y;
      break;
    default:
      code = keyboardEvent.code;
  }
  return code;
}
function isDeleteKey(key, alwaysReturnFalseOnBackspace = false) {
  if (key === KeyCode.DELETE) {
    return true;
  }
  if (!alwaysReturnFalseOnBackspace && key === KeyCode.BACKSPACE) {
    return isMacOsUserAgent();
  }
  return false;
}

// community-modules/core/src/utils/mouse.ts
var mouse_exports = {};
__export(mouse_exports, {
  areEventsNear: () => areEventsNear
});
function areEventsNear(e1, e2, pixelCount) {
  if (pixelCount === 0) {
    return false;
  }
  const diffX = Math.abs(e1.clientX - e2.clientX);
  const diffY = Math.abs(e1.clientY - e2.clientY);
  return Math.max(diffX, diffY) <= pixelCount;
}

// community-modules/core/src/utils/rowNode.ts
var rowNode_exports = {};
__export(rowNode_exports, {
  sortRowNodesByOrder: () => sortRowNodesByOrder
});
function sortRowNodesByOrder(rowNodes, rowNodeOrder) {
  if (!rowNodes) {
    return false;
  }
  const comparator = (nodeA, nodeB) => {
    const positionA = rowNodeOrder[nodeA.id];
    const positionB = rowNodeOrder[nodeB.id];
    const aHasIndex = positionA !== void 0;
    const bHasIndex = positionB !== void 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;
  };
  let rowNodeA;
  let rowNodeB;
  let atLeastOneOutOfOrder = false;
  for (let i = 0; i < rowNodes.length - 1; i++) {
    rowNodeA = rowNodes[i];
    rowNodeB = rowNodes[i + 1];
    if (comparator(rowNodeA, rowNodeB) > 0) {
      atLeastOneOutOfOrder = true;
      break;
    }
  }
  if (atLeastOneOutOfOrder) {
    rowNodes.sort(comparator);
    return true;
  }
  return false;
}

// community-modules/core/src/utils/set.ts
var set_exports = {};
__export(set_exports, {
  convertToSet: () => convertToSet
});
function convertToSet(list) {
  const set = /* @__PURE__ */ new Set();
  list.forEach((x) => set.add(x));
  return set;
}

// community-modules/core/src/utils/utils.ts
var utils = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, aria_exports), array_exports), browser_exports), date_exports), dom_exports), event_exports), function_exports), fuzzyMatch_exports), generic_exports), icon_exports), keyboard_exports), map_exports), mouse_exports), number_exports), object_exports), rowNode_exports), set_exports), string_exports);
var _ = utils;

// community-modules/core/src/utils/numberSequence.ts
var NumberSequence = class {
  constructor(initValue = 0, step = 1) {
    this.nextValue = initValue;
    this.step = step;
  }
  next() {
    const valToReturn = this.nextValue;
    this.nextValue += this.step;
    return valToReturn;
  }
  peek() {
    return this.nextValue;
  }
  skip(count) {
    this.nextValue += count;
  }
};

// community-modules/core/src/utils/promise.ts
var AgPromiseStatus = /* @__PURE__ */ ((AgPromiseStatus2) => {
  AgPromiseStatus2[AgPromiseStatus2["IN_PROGRESS"] = 0] = "IN_PROGRESS";
  AgPromiseStatus2[AgPromiseStatus2["RESOLVED"] = 1] = "RESOLVED";
  return AgPromiseStatus2;
})(AgPromiseStatus || {});
var AgPromise = class _AgPromise {
  constructor(callback) {
    this.status = 0 /* IN_PROGRESS */;
    this.resolution = null;
    this.waiters = [];
    callback((value) => this.onDone(value), (params) => this.onReject(params));
  }
  static all(promises) {
    return new _AgPromise((resolve) => {
      let remainingToResolve = promises.length;
      const combinedValues = new Array(remainingToResolve);
      promises.forEach((promise, index) => {
        promise.then((value) => {
          combinedValues[index] = value;
          remainingToResolve--;
          if (remainingToResolve === 0) {
            resolve(combinedValues);
          }
        });
      });
    });
  }
  static resolve(value = null) {
    return new _AgPromise((resolve) => resolve(value));
  }
  then(func) {
    return new _AgPromise((resolve) => {
      if (this.status === 1 /* RESOLVED */) {
        resolve(func(this.resolution));
      } else {
        this.waiters.push((value) => resolve(func(value)));
      }
    });
  }
  resolveNow(ifNotResolvedValue, ifResolved) {
    return this.status === 1 /* RESOLVED */ ? ifResolved(this.resolution) : ifNotResolvedValue;
  }
  onDone(value) {
    this.status = 1 /* RESOLVED */;
    this.resolution = value;
    this.waiters.forEach((waiter) => waiter(value));
  }
  onReject(params) {
    console.warn("TBI");
  }
};

// community-modules/core/src/utils/timer.ts
var Timer = class {
  constructor() {
    this.timestamp = (/* @__PURE__ */ new Date()).getTime();
  }
  print(msg) {
    const duration = (/* @__PURE__ */ new Date()).getTime() - this.timestamp;
    console.info(`${msg} = ${duration}`);
    this.timestamp = (/* @__PURE__ */ new Date()).getTime();
  }
};

// community-modules/core/src/rendering/cssClassManager.ts
var CssClassManager = class {
  constructor(getGui) {
    // to minimise DOM hits, we only apply CSS classes if they have changed. as adding a CSS class that is already
    // there, or removing one that wasn't present, all takes CPU.
    this.cssClassStates = {};
    this.getGui = getGui;
  }
  addCssClass(className) {
    const list = (className || "").split(" ");
    if (list.length > 1) {
      list.forEach((cls) => this.addCssClass(cls));
      return;
    }
    const updateNeeded = this.cssClassStates[className] !== true;
    if (updateNeeded && className.length) {
      const eGui = this.getGui();
      if (eGui) {
        eGui.classList.add(className);
      }
      this.cssClassStates[className] = true;
    }
  }
  removeCssClass(className) {
    const list = (className || "").split(" ");
    if (list.length > 1) {
      list.forEach((cls) => this.removeCssClass(cls));
      return;
    }
    const updateNeeded = this.cssClassStates[className] !== false;
    if (updateNeeded && className.length) {
      const eGui = this.getGui();
      if (eGui) {
        eGui.classList.remove(className);
      }
      this.cssClassStates[className] = false;
    }
  }
  containsCssClass(className) {
    const eGui = this.getGui();
    if (!eGui) {
      return false;
    }
    return eGui.classList.contains(className);
  }
  addOrRemoveCssClass(className, addOrRemove) {
    if (!className) {
      return;
    }
    if (className.indexOf(" ") >= 0) {
      const list = (className || "").split(" ");
      if (list.length > 1) {
        list.forEach((cls) => this.addOrRemoveCssClass(cls, addOrRemove));
        return;
      }
    }
    const updateNeeded = this.cssClassStates[className] !== addOrRemove;
    if (updateNeeded && className.length) {
      const eGui = this.getGui();
      if (eGui) {
        eGui.classList.toggle(className, addOrRemove);
      }
      this.cssClassStates[className] = addOrRemove;
    }
  }
};

// community-modules/core/src/widgets/tooltipStateManager.ts
var _TooltipStateManager = class _TooltipStateManager extends BeanStub {
  constructor(parentComp, tooltipShowDelayOverride, tooltipHideDelayOverride, shouldDisplayTooltip) {
    super();
    this.parentComp = parentComp;
    this.tooltipShowDelayOverride = tooltipShowDelayOverride;
    this.tooltipHideDelayOverride = tooltipHideDelayOverride;
    this.shouldDisplayTooltip = shouldDisplayTooltip;
    this.SHOW_QUICK_TOOLTIP_DIFF = 1e3;
    this.FADE_OUT_TOOLTIP_TIMEOUT = 1e3;
    this.INTERACTIVE_HIDE_DELAY = 100;
    this.interactionEnabled = false;
    this.isInteractingWithTooltip = false;
    this.state = 0 /* NOTHING */;
    // when showing the tooltip, we need to make sure it's the most recent instance we request, as due to
    // async we could request two tooltips before the first instance returns, in which case we should
    // disregard the second instance.
    this.tooltipInstanceCount = 0;
    this.tooltipMouseTrack = false;
  }
  postConstruct() {
    if (this.gos.get("tooltipInteraction")) {
      this.interactionEnabled = true;
    }
    this.tooltipTrigger = this.getTooltipTrigger();
    this.tooltipMouseTrack = this.gos.get("tooltipMouseTrack");
    const el = this.parentComp.getGui();
    if (this.tooltipTrigger === 0 /* HOVER */) {
      this.addManagedListener(el, "mouseenter", this.onMouseEnter.bind(this));
      this.addManagedListener(el, "mouseleave", this.onMouseLeave.bind(this));
    }
    if (this.tooltipTrigger === 1 /* FOCUS */) {
      this.addManagedListener(el, "focusin", this.onFocusIn.bind(this));
      this.addManagedListener(el, "focusout", this.onFocusOut.bind(this));
    }
    this.addManagedListener(el, "mousemove", this.onMouseMove.bind(this));
    if (!this.interactionEnabled) {
      this.addManagedListener(el, "mousedown", this.onMouseDown.bind(this));
      this.addManagedListener(el, "keydown", this.onKeyDown.bind(this));
    }
  }
  getGridOptionsTooltipDelay(delayOption) {
    const delay = this.gos.get(delayOption);
    if (delay < 0) {
      warnOnce(`${delayOption} should not be lower than 0`);
    }
    return Math.max(200, delay);
  }
  getTooltipDelay(type) {
    var _a, _b;
    if (type === "show") {
      return (_a = this.tooltipShowDelayOverride) != null ? _a : this.getGridOptionsTooltipDelay("tooltipShowDelay");
    }
    return (_b = this.tooltipHideDelayOverride) != null ? _b : this.getGridOptionsTooltipDelay("tooltipHideDelay");
  }
  destroy() {
    this.setToDoNothing();
    super.destroy();
  }
  getTooltipTrigger() {
    const trigger = this.gos.get("tooltipTrigger");
    if (!trigger || trigger === "hover") {
      return 0 /* HOVER */;
    }
    return 1 /* FOCUS */;
  }
  onMouseEnter(e) {
    if (this.interactionEnabled && this.interactiveTooltipTimeoutId) {
      this.unlockService();
      this.startHideTimeout();
    }
    if (isIOSUserAgent()) {
      return;
    }
    if (_TooltipStateManager.isLocked) {
      this.showTooltipTimeoutId = window.setTimeout(() => {
        this.prepareToShowTooltip(e);
      }, this.INTERACTIVE_HIDE_DELAY);
    } else {
      this.prepareToShowTooltip(e);
    }
  }
  onMouseMove(e) {
    if (this.lastMouseEvent) {
      this.lastMouseEvent = e;
    }
    if (this.tooltipMouseTrack && this.state === 2 /* SHOWING */ && this.tooltipComp) {
      this.positionTooltip();
    }
  }
  onMouseDown() {
    this.setToDoNothing();
  }
  onMouseLeave() {
    if (this.interactionEnabled) {
      this.lockService();
    } else {
      this.setToDoNothing();
    }
  }
  onFocusIn() {
    this.prepareToShowTooltip();
  }
  onFocusOut(e) {
    var _a;
    const relatedTarget = e.relatedTarget;
    const parentCompGui = this.parentComp.getGui();
    const tooltipGui = (_a = this.tooltipComp) == null ? void 0 : _a.getGui();
    if (this.isInteractingWithTooltip || parentCompGui.contains(relatedTarget) || this.interactionEnabled && (tooltipGui == null ? void 0 : tooltipGui.contains(relatedTarget))) {
      return;
    }
    this.setToDoNothing();
  }
  onKeyDown() {
    this.setToDoNothing();
  }
  prepareToShowTooltip(mouseEvent) {
    if (this.state != 0 /* NOTHING */ || _TooltipStateManager.isLocked) {
      return;
    }
    let delay = 0;
    if (mouseEvent) {
      delay = this.isLastTooltipHiddenRecently() ? 200 : this.getTooltipDelay("show");
    }
    this.lastMouseEvent = mouseEvent || null;
    this.showTooltipTimeoutId = window.setTimeout(this.showTooltip.bind(this), delay);
    this.state = 1 /* WAITING_TO_SHOW */;
  }
  isLastTooltipHiddenRecently() {
    const now = (/* @__PURE__ */ new Date()).getTime();
    const then = _TooltipStateManager.lastTooltipHideTime;
    return now - then < this.SHOW_QUICK_TOOLTIP_DIFF;
  }
  setToDoNothing() {
    if (this.state === 2 /* SHOWING */) {
      this.hideTooltip();
    }
    if (this.onBodyScrollEventCallback) {
      this.onBodyScrollEventCallback();
      this.onBodyScrollEventCallback = void 0;
    }
    if (this.onColumnMovedEventCallback) {
      this.onColumnMovedEventCallback();
      this.onColumnMovedEventCallback = void 0;
    }
    this.clearTimeouts();
    this.state = 0 /* NOTHING */;
    this.lastMouseEvent = null;
  }
  showTooltip() {
    const params = __spreadValues({}, this.parentComp.getTooltipParams());
    if (!exists(params.value) || this.shouldDisplayTooltip && !this.shouldDisplayTooltip()) {
      this.setToDoNothing();
      return;
    }
    this.state = 2 /* SHOWING */;
    this.tooltipInstanceCount++;
    const callback = this.newTooltipComponentCallback.bind(this, this.tooltipInstanceCount);
    const userDetails = this.userComponentFactory.getTooltipCompDetails(params);
    userDetails.newAgStackInstance().then(callback);
  }
  hideTooltip(forceHide) {
    if (!forceHide && this.isInteractingWithTooltip) {
      return;
    }
    if (this.tooltipComp) {
      this.destroyTooltipComp();
      _TooltipStateManager.lastTooltipHideTime = (/* @__PURE__ */ new Date()).getTime();
    }
    const event = {
      type: Events.EVENT_TOOLTIP_HIDE,
      parentGui: this.parentComp.getGui()
    };
    this.eventService.dispatchEvent(event);
    this.state = 0 /* NOTHING */;
  }
  newTooltipComponentCallback(tooltipInstanceCopy, tooltipComp) {
    const compNoLongerNeeded = this.state !== 2 /* SHOWING */ || this.tooltipInstanceCount !== tooltipInstanceCopy;
    if (compNoLongerNeeded) {
      this.getContext().destroyBean(tooltipComp);
      return;
    }
    const eGui = tooltipComp.getGui();
    this.tooltipComp = tooltipComp;
    if (!eGui.classList.contains("ag-tooltip")) {
      eGui.classList.add("ag-tooltip-custom");
    }
    if (this.tooltipTrigger === 0 /* HOVER */) {
      eGui.classList.add("ag-tooltip-animate");
    }
    if (this.interactionEnabled) {
      eGui.classList.add("ag-tooltip-interactive");
    }
    const translate = this.localeService.getLocaleTextFunc();
    const addPopupRes = this.popupService.addPopup({
      eChild: eGui,
      ariaLabel: translate("ariaLabelTooltip", "Tooltip")
    });
    if (addPopupRes) {
      this.tooltipPopupDestroyFunc = addPopupRes.hideFunc;
    }
    this.positionTooltip();
    if (this.tooltipTrigger === 1 /* FOCUS */) {
      this.onBodyScrollEventCallback = this.addManagedListener(this.eventService, Events.EVENT_BODY_SCROLL, this.setToDoNothing.bind(this));
      this.onColumnMovedEventCallback = this.addManagedListener(this.eventService, Events.EVENT_COLUMN_MOVED, this.setToDoNothing.bind(this));
    }
    if (this.interactionEnabled) {
      if (this.tooltipTrigger === 0 /* HOVER */) {
        this.tooltipMouseEnterListener = this.addManagedListener(eGui, "mouseenter", this.onTooltipMouseEnter.bind(this)) || null;
        this.tooltipMouseLeaveListener = this.addManagedListener(eGui, "mouseleave", this.onTooltipMouseLeave.bind(this)) || null;
      } else {
        this.tooltipFocusInListener = this.addManagedListener(eGui, "focusin", this.onTooltipFocusIn.bind(this)) || null;
        this.tooltipFocusOutListener = this.addManagedListener(eGui, "focusout", this.onTooltipFocusOut.bind(this)) || null;
      }
    }
    const event = {
      type: Events.EVENT_TOOLTIP_SHOW,
      tooltipGui: eGui,
      parentGui: this.parentComp.getGui()
    };
    this.eventService.dispatchEvent(event);
    this.startHideTimeout();
  }
  onTooltipMouseEnter() {
    this.isInteractingWithTooltip = true;
    this.unlockService();
  }
  onTooltipMouseLeave() {
    this.isInteractingWithTooltip = false;
    this.lockService();
  }
  onTooltipFocusIn() {
    this.isInteractingWithTooltip = true;
  }
  onTooltipFocusOut(e) {
    var _a;
    const parentGui = this.parentComp.getGui();
    const tooltipGui = (_a = this.tooltipComp) == null ? void 0 : _a.getGui();
    const relatedTarget = e.relatedTarget;
    if (tooltipGui == null ? void 0 : tooltipGui.contains(relatedTarget)) {
      return;
    }
    this.isInteractingWithTooltip = false;
    if (parentGui.contains(relatedTarget)) {
      this.startHideTimeout();
    } else {
      this.hideTooltip();
    }
  }
  positionTooltip() {
    const params = {
      type: "tooltip",
      ePopup: this.tooltipComp.getGui(),
      nudgeY: 18,
      skipObserver: this.tooltipMouseTrack
    };
    if (this.lastMouseEvent) {
      this.popupService.positionPopupUnderMouseEvent(__spreadProps(__spreadValues({}, params), {
        mouseEvent: this.lastMouseEvent
      }));
    } else {
      this.popupService.positionPopupByComponent(__spreadProps(__spreadValues({}, params), {
        eventSource: this.parentComp.getGui(),
        position: "under",
        keepWithinBounds: true,
        nudgeY: 5
      }));
    }
  }
  destroyTooltipComp() {
    this.tooltipComp.getGui().classList.add("ag-tooltip-hiding");
    const tooltipPopupDestroyFunc = this.tooltipPopupDestroyFunc;
    const tooltipComp = this.tooltipComp;
    const delay = this.tooltipTrigger === 0 /* HOVER */ ? this.FADE_OUT_TOOLTIP_TIMEOUT : 0;
    window.setTimeout(() => {
      tooltipPopupDestroyFunc();
      this.getContext().destroyBean(tooltipComp);
    }, delay);
    this.clearTooltipListeners();
    this.tooltipPopupDestroyFunc = void 0;
    this.tooltipComp = void 0;
  }
  clearTooltipListeners() {
    [
      this.tooltipMouseEnterListener,
      this.tooltipMouseLeaveListener,
      this.tooltipFocusInListener,
      this.tooltipFocusOutListener
    ].forEach((listener) => {
      if (listener) {
        listener();
      }
    });
    this.tooltipMouseEnterListener = this.tooltipMouseLeaveListener = this.tooltipFocusInListener = this.tooltipFocusOutListener = null;
  }
  lockService() {
    _TooltipStateManager.isLocked = true;
    this.interactiveTooltipTimeoutId = window.setTimeout(() => {
      this.unlockService();
      this.setToDoNothing();
    }, this.INTERACTIVE_HIDE_DELAY);
  }
  unlockService() {
    _TooltipStateManager.isLocked = false;
    this.clearInteractiveTimeout();
  }
  startHideTimeout() {
    this.clearHideTimeout();
    this.hideTooltipTimeoutId = window.setTimeout(this.hideTooltip.bind(this), this.getTooltipDelay("hide"));
  }
  clearShowTimeout() {
    if (!this.showTooltipTimeoutId) {
      return;
    }
    window.clearTimeout(this.showTooltipTimeoutId);
    this.showTooltipTimeoutId = void 0;
  }
  clearHideTimeout() {
    if (!this.hideTooltipTimeoutId) {
      return;
    }
    window.clearTimeout(this.hideTooltipTimeoutId);
    this.hideTooltipTimeoutId = void 0;
  }
  clearInteractiveTimeout() {
    if (!this.interactiveTooltipTimeoutId) {
      return;
    }
    window.clearTimeout(this.interactiveTooltipTimeoutId);
    this.interactiveTooltipTimeoutId = void 0;
  }
  clearTimeouts() {
    this.clearShowTimeout();
    this.clearHideTimeout();
    this.clearInteractiveTimeout();
  }
};
_TooltipStateManager.isLocked = false;
__decorateClass([
  Autowired("popupService")
], _TooltipStateManager.prototype, "popupService", 2);
__decorateClass([
  Autowired("userComponentFactory")
], _TooltipStateManager.prototype, "userComponentFactory", 2);
__decorateClass([
  PostConstruct
], _TooltipStateManager.prototype, "postConstruct", 1);
var TooltipStateManager = _TooltipStateManager;

// community-modules/core/src/widgets/tooltipFeature.ts
var TooltipFeature = class extends BeanStub {
  constructor(ctrl, beans) {
    super();
    this.ctrl = ctrl;
    if (beans) {
      this.beans = beans;
    }
  }
  postConstruct() {
    this.refreshToolTip();
  }
  setBrowserTooltip(tooltip) {
    const name = "title";
    const eGui = this.ctrl.getGui();
    if (!eGui) {
      return;
    }
    if (tooltip != null && tooltip != "") {
      eGui.setAttribute(name, tooltip);
    } else {
      eGui.removeAttribute(name);
    }
  }
  updateTooltipText() {
    this.tooltip = this.ctrl.getTooltipValue();
  }
  createTooltipFeatureIfNeeded() {
    var _a, _b, _c, _d;
    if (this.tooltipManager != null) {
      return;
    }
    const parent = {
      getTooltipParams: () => this.getTooltipParams(),
      getGui: () => this.ctrl.getGui()
    };
    this.tooltipManager = this.createBean(new TooltipStateManager(
      parent,
      (_b = (_a = this.ctrl).getTooltipShowDelayOverride) == null ? void 0 : _b.call(_a),
      (_d = (_c = this.ctrl).getTooltipHideDelayOverride) == null ? void 0 : _d.call(_c),
      this.ctrl.shouldDisplayTooltip
    ), this.beans.context);
  }
  refreshToolTip() {
    this.browserTooltips = this.beans.gos.get("enableBrowserTooltips");
    this.updateTooltipText();
    if (this.browserTooltips) {
      this.setBrowserTooltip(this.tooltip);
      if (this.tooltipManager) {
        this.tooltipManager = this.destroyBean(this.tooltipManager, this.beans.context);
      }
    } else {
      this.setBrowserTooltip(null);
      this.createTooltipFeatureIfNeeded();
    }
  }
  getTooltipParams() {
    const ctrl = this.ctrl;
    const column = ctrl.getColumn ? ctrl.getColumn() : void 0;
    const colDef = ctrl.getColDef ? ctrl.getColDef() : void 0;
    const rowNode = ctrl.getRowNode ? ctrl.getRowNode() : void 0;
    return {
      location: ctrl.getLocation(),
      //'cell',
      colDef,
      column,
      rowIndex: ctrl.getRowIndex ? ctrl.getRowIndex() : void 0,
      node: rowNode,
      data: rowNode ? rowNode.data : void 0,
      value: this.getTooltipText(),
      valueFormatted: ctrl.getValueFormatted ? ctrl.getValueFormatted() : void 0,
      hideTooltipCallback: () => {
        var _a;
        return (_a = this.tooltipManager) == null ? void 0 : _a.hideTooltip(true);
      }
    };
  }
  getTooltipText() {
    return this.tooltip;
  }
  // overriding to make public, as we don't dispose this bean via context
  destroy() {
    if (this.tooltipManager) {
      this.tooltipManager = this.destroyBean(this.tooltipManager, this.beans.context);
    }
    super.destroy();
  }
};
__decorateClass([
  Autowired("beans")
], TooltipFeature.prototype, "beans", 2);
__decorateClass([
  PostConstruct
], TooltipFeature.prototype, "postConstruct", 1);

// community-modules/core/src/widgets/component.ts
var compIdSequence = new NumberSequence();
var _Component = class _Component extends BeanStub {
  constructor(template) {
    super();
    // if false, then CSS class "ag-hidden" is applied, which sets "display: none"
    this.displayed = true;
    // if false, then CSS class "ag-invisible" is applied, which sets "visibility: hidden"
    this.visible = true;
    // unique id for this row component. this is used for getting a reference to the HTML dom.
    // we cannot use the RowNode id as this is not unique (due to animation, old rows can be lying
    // around as we create a new rowComp instance for the same row node).
    this.compId = compIdSequence.next();
    this.cssClassManager = new CssClassManager(() => this.eGui);
    if (template) {
      this.setTemplate(template);
    }
  }
  preConstructOnComponent() {
    this.usingBrowserTooltips = this.gos.get("enableBrowserTooltips");
  }
  getCompId() {
    return this.compId;
  }
  getTooltipParams() {
    return {
      value: this.tooltipText,
      location: "UNKNOWN"
    };
  }
  setTooltip(params) {
    const { newTooltipText, showDelayOverride, hideDelayOverride, location, shouldDisplayTooltip } = params || {};
    if (this.tooltipFeature) {
      this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    }
    if (this.tooltipText !== newTooltipText) {
      this.tooltipText = newTooltipText;
    }
    const getTooltipValue = () => this.tooltipText;
    if (newTooltipText != null) {
      this.tooltipFeature = this.createBean(new TooltipFeature({
        getTooltipValue,
        getGui: () => this.getGui(),
        getLocation: () => location != null ? location : "UNKNOWN",
        getColDef: params == null ? void 0 : params.getColDef,
        getColumn: params == null ? void 0 : params.getColumn,
        getTooltipShowDelayOverride: showDelayOverride != null ? () => showDelayOverride : void 0,
        getTooltipHideDelayOverride: hideDelayOverride != null ? () => hideDelayOverride : void 0,
        shouldDisplayTooltip
      }));
    }
  }
  // for registered components only, eg creates AgCheckbox instance from ag-checkbox HTML tag
  createChildComponentsFromTags(parentNode, paramsMap) {
    const childNodeList = copyNodeList(parentNode.childNodes);
    childNodeList.forEach((childNode) => {
      if (!(childNode instanceof HTMLElement)) {
        return;
      }
      const childComp = this.createComponentFromElement(childNode, (childComp2) => {
        const childGui = childComp2.getGui();
        if (childGui) {
          this.copyAttributesFromNode(childNode, childComp2.getGui());
        }
      }, paramsMap);
      if (childComp) {
        if (childComp.addItems && childNode.children.length) {
          this.createChildComponentsFromTags(childNode, paramsMap);
          const items = Array.prototype.slice.call(childNode.children);
          childComp.addItems(items);
        }
        this.swapComponentForNode(childComp, parentNode, childNode);
      } else if (childNode.childNodes) {
        this.createChildComponentsFromTags(childNode, paramsMap);
      }
    });
  }
  createComponentFromElement(element, afterPreCreateCallback, paramsMap) {
    const key = element.nodeName;
    const componentParams = paramsMap ? paramsMap[element.getAttribute("ref")] : void 0;
    const ComponentClass = this.agStackComponentsRegistry.getComponentClass(key);
    if (ComponentClass) {
      _Component.elementGettingCreated = element;
      const newComponent = new ComponentClass(componentParams);
      newComponent.setParentComponent(this);
      this.createBean(newComponent, null, afterPreCreateCallback);
      return newComponent;
    }
    return null;
  }
  copyAttributesFromNode(source, dest) {
    iterateNamedNodeMap(source.attributes, (name, value) => dest.setAttribute(name, value));
  }
  swapComponentForNode(newComponent, parentNode, childNode) {
    const eComponent = newComponent.getGui();
    parentNode.replaceChild(eComponent, childNode);
    parentNode.insertBefore(document.createComment(childNode.nodeName), eComponent);
    this.addDestroyFunc(this.destroyBean.bind(this, newComponent));
    this.swapInComponentForQuerySelectors(newComponent, childNode);
  }
  swapInComponentForQuerySelectors(newComponent, childNode) {
    const thisNoType = this;
    this.iterateOverQuerySelectors((querySelector) => {
      if (thisNoType[querySelector.attributeName] === childNode) {
        thisNoType[querySelector.attributeName] = newComponent;
      }
    });
  }
  iterateOverQuerySelectors(action) {
    let thisPrototype = Object.getPrototypeOf(this);
    while (thisPrototype != null) {
      const metaData = thisPrototype.__agComponentMetaData;
      const currentProtoName = getFunctionName(thisPrototype.constructor);
      if (metaData && metaData[currentProtoName] && metaData[currentProtoName].querySelectors) {
        metaData[currentProtoName].querySelectors.forEach((querySelector) => action(querySelector));
      }
      thisPrototype = Object.getPrototypeOf(thisPrototype);
    }
  }
  activateTabIndex(elements) {
    const tabIndex = this.gos.get("tabIndex");
    if (!elements) {
      elements = [];
    }
    if (!elements.length) {
      elements.push(this.getGui());
    }
    elements.forEach((el) => el.setAttribute("tabindex", tabIndex.toString()));
  }
  setTemplate(template, paramsMap) {
    const eGui = loadTemplate(template);
    this.setTemplateFromElement(eGui, paramsMap);
  }
  setTemplateFromElement(element, paramsMap) {
    this.eGui = element;
    this.eGui.__agComponent = this;
    this.wireQuerySelectors();
    if (!!this.getContext()) {
      this.createChildComponentsFromTags(this.getGui(), paramsMap);
    }
  }
  createChildComponentsPreConstruct() {
    if (!!this.getGui()) {
      this.createChildComponentsFromTags(this.getGui());
    }
  }
  wireQuerySelectors() {
    if (!this.eGui) {
      return;
    }
    const thisNoType = this;
    this.iterateOverQuerySelectors((querySelector) => {
      const setResult = (result) => thisNoType[querySelector.attributeName] = result;
      const topLevelRefMatch = querySelector.refSelector && this.getAttribute("ref") === querySelector.refSelector;
      if (topLevelRefMatch) {
        setResult(this.eGui);
      } else {
        const resultOfQuery = this.eGui.querySelector(querySelector.querySelector);
        if (resultOfQuery) {
          setResult(resultOfQuery.__agComponent || resultOfQuery);
        }
      }
    });
  }
  getGui() {
    return this.eGui;
  }
  getFocusableElement() {
    return this.eGui;
  }
  getAriaElement() {
    return this.getFocusableElement();
  }
  setParentComponent(component) {
    this.parentComponent = component;
  }
  getParentComponent() {
    return this.parentComponent;
  }
  // this method is for older code, that wants to provide the gui element,
  // it is not intended for this to be in ag-Stack
  setGui(eGui) {
    this.eGui = eGui;
  }
  queryForHtmlElement(cssSelector) {
    return this.eGui.querySelector(cssSelector);
  }
  queryForHtmlInputElement(cssSelector) {
    return this.eGui.querySelector(cssSelector);
  }
  appendChild(newChild, container) {
    if (newChild == null) {
      return;
    }
    if (!container) {
      container = this.eGui;
    }
    if (isNodeOrElement(newChild)) {
      container.appendChild(newChild);
    } else {
      const childComponent = newChild;
      container.appendChild(childComponent.getGui());
    }
  }
  isDisplayed() {
    return this.displayed;
  }
  setVisible(visible, options = {}) {
    if (visible !== this.visible) {
      this.visible = visible;
      const { skipAriaHidden } = options;
      setVisible(this.eGui, visible, { skipAriaHidden });
    }
  }
  setDisplayed(displayed, options = {}) {
    if (displayed !== this.displayed) {
      this.displayed = displayed;
      const { skipAriaHidden } = options;
      setDisplayed(this.eGui, displayed, { skipAriaHidden });
      const event = {
        type: _Component.EVENT_DISPLAYED_CHANGED,
        visible: this.displayed
      };
      this.dispatchEvent(event);
    }
  }
  destroy() {
    if (this.parentComponent) {
      this.parentComponent = void 0;
    }
    if (this.tooltipFeature) {
      this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    }
    const eGui = this.eGui;
    if (eGui && eGui.__agComponent) {
      eGui.__agComponent = void 0;
    }
    super.destroy();
  }
  addGuiEventListener(event, listener, options) {
    this.eGui.addEventListener(event, listener, options);
    this.addDestroyFunc(() => this.eGui.removeEventListener(event, listener));
  }
  addCssClass(className) {
    this.cssClassManager.addCssClass(className);
  }
  removeCssClass(className) {
    this.cssClassManager.removeCssClass(className);
  }
  containsCssClass(className) {
    return this.cssClassManager.containsCssClass(className);
  }
  addOrRemoveCssClass(className, addOrRemove) {
    this.cssClassManager.addOrRemoveCssClass(className, addOrRemove);
  }
  getAttribute(key) {
    const { eGui } = this;
    return eGui ? eGui.getAttribute(key) : null;
  }
  getRefElement(refName) {
    return this.queryForHtmlElement(`[ref="${refName}"]`);
  }
};
_Component.EVENT_DISPLAYED_CHANGED = "displayedChanged";
__decorateClass([
  Autowired("agStackComponentsRegistry")
], _Component.prototype, "agStackComponentsRegistry", 2);
__decorateClass([
  PreConstruct
], _Component.prototype, "preConstructOnComponent", 1);
__decorateClass([
  PreConstruct
], _Component.prototype, "createChildComponentsPreConstruct", 1);
var Component = _Component;

// community-modules/core/src/widgets/componentAnnotations.ts
function QuerySelector(selector) {
  return querySelectorFunc.bind(this, selector, void 0);
}
function RefSelector(ref) {
  return querySelectorFunc.bind(this, `[ref=${ref}]`, ref);
}
function querySelectorFunc(selector, refSelector, classPrototype, methodOrAttributeName, index) {
  if (selector === null) {
    console.error("AG Grid: QuerySelector selector should not be null");
    return;
  }
  if (typeof index === "number") {
    console.error("AG Grid: QuerySelector should be on an attribute");
    return;
  }
  addToObjectProps(classPrototype, "querySelectors", {
    attributeName: methodOrAttributeName,
    querySelector: selector,
    refSelector
  });
}
function addToObjectProps(target, key, value) {
  const props = getOrCreateProps2(target, getFunctionName(target.constructor));
  if (!props[key]) {
    props[key] = [];
  }
  props[key].push(value);
}
function getOrCreateProps2(target, instanceName) {
  if (!target.__agComponentMetaData) {
    target.__agComponentMetaData = {};
  }
  if (!target.__agComponentMetaData[instanceName]) {
    target.__agComponentMetaData[instanceName] = {};
  }
  return target.__agComponentMetaData[instanceName];
}

// community-modules/core/src/filter/floating/provided/readOnlyFloatingFilter.ts
var ReadOnlyFloatingFilter = class extends Component {
  constructor() {
    super(
      /* html */
      `
            <div class="ag-floating-filter-input" role="presentation">
                <ag-input-text-field ref="eFloatingFilterText"></ag-input-text-field>
            </div>`
    );
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
  init(params) {
    this.params = params;
    const displayName = this.columnModel.getDisplayNameForColumn(params.column, "header", true);
    const translate = this.localeService.getLocaleTextFunc();
    this.eFloatingFilterText.setDisabled(true).setInputAriaLabel(`${displayName} ${translate("ariaFilterInput", "Filter Input")}`);
  }
  onParentModelChanged(parentModel) {
    if (parentModel == null) {
      this.eFloatingFilterText.setValue("");
      return;
    }
    this.params.parentFilterInstance((filterInstance) => {
      if (filterInstance.getModelAsString) {
        const modelAsString = filterInstance.getModelAsString(parentModel);
        this.eFloatingFilterText.setValue(modelAsString);
      }
    });
  }
  onParamsUpdated(params) {
    this.refresh(params);
  }
  refresh(params) {
    this.init(params);
  }
};
__decorateClass([
  RefSelector("eFloatingFilterText")
], ReadOnlyFloatingFilter.prototype, "eFloatingFilterText", 2);
__decorateClass([
  Autowired("columnModel")
], ReadOnlyFloatingFilter.prototype, "columnModel", 2);

// community-modules/core/src/filter/provided/date/dateCompWrapper.ts
var DateCompWrapper = class {
  constructor(context, userComponentFactory, dateComponentParams, eParent, onReady) {
    this.alive = true;
    this.context = context;
    this.eParent = eParent;
    const compDetails = userComponentFactory.getDateCompDetails(dateComponentParams);
    const promise = compDetails.newAgStackInstance();
    promise.then((dateComp) => {
      if (!this.alive) {
        context.destroyBean(dateComp);
        return;
      }
      this.dateComp = dateComp;
      if (!dateComp) {
        return;
      }
      eParent.appendChild(dateComp.getGui());
      if (dateComp.afterGuiAttached) {
        dateComp.afterGuiAttached();
      }
      if (this.tempValue) {
        dateComp.setDate(this.tempValue);
      }
      if (this.disabled != null) {
        this.setDateCompDisabled(this.disabled);
      }
      onReady == null ? void 0 : onReady(this);
    });
  }
  destroy() {
    this.alive = false;
    this.dateComp = this.context.destroyBean(this.dateComp);
  }
  getDate() {
    return this.dateComp ? this.dateComp.getDate() : this.tempValue;
  }
  setDate(value) {
    if (this.dateComp) {
      this.dateComp.setDate(value);
    } else {
      this.tempValue = value;
    }
  }
  setDisabled(disabled) {
    if (this.dateComp) {
      this.setDateCompDisabled(disabled);
    } else {
      this.disabled = disabled;
    }
  }
  setDisplayed(displayed) {
    setDisplayed(this.eParent, displayed);
  }
  setInputPlaceholder(placeholder) {
    if (this.dateComp && this.dateComp.setInputPlaceholder) {
      this.dateComp.setInputPlaceholder(placeholder);
    }
  }
  setInputAriaLabel(label) {
    if (this.dateComp && this.dateComp.setInputAriaLabel) {
      this.dateComp.setInputAriaLabel(label);
    }
  }
  afterGuiAttached(params) {
    if (this.dateComp && typeof this.dateComp.afterGuiAttached === "function") {
      this.dateComp.afterGuiAttached(params);
    }
  }
  updateParams(params) {
    var _a, _b;
    let hasRefreshed = false;
    if (((_a = this.dateComp) == null ? void 0 : _a.refresh) && typeof this.dateComp.refresh === "function") {
      const result = this.dateComp.refresh(params);
      if (result !== null) {
        hasRefreshed = true;
      }
    }
    if (!hasRefreshed && ((_b = this.dateComp) == null ? void 0 : _b.onParamsUpdated) && typeof this.dateComp.onParamsUpdated === "function") {
      const result = this.dateComp.onParamsUpdated(params);
      if (result !== null) {
        warnOnce(`Custom date component method 'onParamsUpdated' is deprecated. Use 'refresh' instead.`);
      }
    }
  }
  setDateCompDisabled(disabled) {
    if (this.dateComp == null) {
      return;
    }
    if (this.dateComp.setDisabled == null) {
      return;
    }
    this.dateComp.setDisabled(disabled);
  }
};

// community-modules/core/src/filter/provided/optionsFactory.ts
var OptionsFactory = class {
  constructor() {
    this.customFilterOptions = {};
  }
  init(params, defaultOptions) {
    this.filterOptions = params.filterOptions || defaultOptions;
    this.mapCustomOptions();
    this.selectDefaultItem(params);
  }
  getFilterOptions() {
    return this.filterOptions;
  }
  mapCustomOptions() {
    if (!this.filterOptions) {
      return;
    }
    this.filterOptions.forEach((filterOption) => {
      if (typeof filterOption === "string") {
        return;
      }
      const requiredProperties = [["displayKey"], ["displayName"], ["predicate", "test"]];
      const propertyCheck = (keys2) => {
        if (!keys2.some((key) => filterOption[key] != null)) {
          console.warn(`AG Grid: ignoring FilterOptionDef as it doesn't contain one of '${keys2}'`);
          return false;
        }
        return true;
      };
      if (!requiredProperties.every(propertyCheck)) {
        this.filterOptions = this.filterOptions.filter((v) => v === filterOption) || [];
        return;
      }
      this.customFilterOptions[filterOption.displayKey] = filterOption;
    });
  }
  selectDefaultItem(params) {
    if (params.defaultOption) {
      this.defaultOption = params.defaultOption;
    } else if (this.filterOptions.length >= 1) {
      const firstFilterOption = this.filterOptions[0];
      if (typeof firstFilterOption === "string") {
        this.defaultOption = firstFilterOption;
      } else if (firstFilterOption.displayKey) {
        this.defaultOption = firstFilterOption.displayKey;
      } else {
        console.warn(`AG Grid: invalid FilterOptionDef supplied as it doesn't contain a 'displayKey'`);
      }
    } else {
      console.warn("AG Grid: no filter options for filter");
    }
  }
  getDefaultOption() {
    return this.defaultOption;
  }
  getCustomOption(name) {
    return this.customFilterOptions[name];
  }
};

// community-modules/core/src/filter/filterLocaleText.ts
var FILTER_LOCALE_TEXT = {
  applyFilter: "Apply",
  clearFilter: "Clear",
  resetFilter: "Reset",
  cancelFilter: "Cancel",
  textFilter: "Text Filter",
  numberFilter: "Number Filter",
  dateFilter: "Date Filter",
  setFilter: "Set Filter",
  filterOoo: "Filter...",
  empty: "Choose one",
  equals: "Equals",
  notEqual: "Does not equal",
  lessThan: "Less than",
  greaterThan: "Greater than",
  inRange: "Between",
  inRangeStart: "From",
  inRangeEnd: "To",
  lessThanOrEqual: "Less than or equal to",
  greaterThanOrEqual: "Greater than or equal to",
  contains: "Contains",
  notContains: "Does not contain",
  startsWith: "Begins with",
  endsWith: "Ends with",
  blank: "Blank",
  notBlank: "Not blank",
  before: "Before",
  after: "After",
  andCondition: "AND",
  orCondition: "OR",
  dateFormatOoo: "yyyy-mm-dd"
};

// community-modules/core/src/widgets/managedFocusFeature.ts
var _ManagedFocusFeature = class _ManagedFocusFeature extends BeanStub {
  constructor(eFocusableElement, callbacks = {}) {
    super();
    this.eFocusableElement = eFocusableElement;
    this.callbacks = callbacks;
    this.callbacks = __spreadValues({
      shouldStopEventPropagation: () => false,
      onTabKeyDown: (e) => {
        if (e.defaultPrevented) {
          return;
        }
        const nextRoot = this.focusService.findNextFocusableElement(this.eFocusableElement, false, e.shiftKey);
        if (!nextRoot) {
          return;
        }
        nextRoot.focus();
        e.preventDefault();
      }
    }, callbacks);
  }
  postConstruct() {
    this.eFocusableElement.classList.add(_ManagedFocusFeature.FOCUS_MANAGED_CLASS);
    this.addKeyDownListeners(this.eFocusableElement);
    if (this.callbacks.onFocusIn) {
      this.addManagedListener(this.eFocusableElement, "focusin", this.callbacks.onFocusIn);
    }
    if (this.callbacks.onFocusOut) {
      this.addManagedListener(this.eFocusableElement, "focusout", this.callbacks.onFocusOut);
    }
  }
  addKeyDownListeners(eGui) {
    this.addManagedListener(eGui, "keydown", (e) => {
      if (e.defaultPrevented || isStopPropagationForAgGrid(e)) {
        return;
      }
      if (this.callbacks.shouldStopEventPropagation(e)) {
        stopPropagationForAgGrid(e);
        return;
      }
      if (e.key === KeyCode.TAB) {
        this.callbacks.onTabKeyDown(e);
      } else if (this.callbacks.handleKeyDown) {
        this.callbacks.handleKeyDown(e);
      }
    });
  }
};
_ManagedFocusFeature.FOCUS_MANAGED_CLASS = "ag-focus-managed";
__decorateClass([
  Autowired("focusService")
], _ManagedFocusFeature.prototype, "focusService", 2);
__decorateClass([
  PostConstruct
], _ManagedFocusFeature.prototype, "postConstruct", 1);
var ManagedFocusFeature = _ManagedFocusFeature;

// community-modules/core/src/rendering/features/positionableFeature.ts
var RESIZE_CONTAINER_STYLE = "ag-resizer-wrapper";
var RESIZE_TEMPLATE = (
  /* html */
  `<div class="${RESIZE_CONTAINER_STYLE}">
        <div ref="eTopLeftResizer" class="ag-resizer ag-resizer-topLeft"></div>
        <div ref="eTopResizer" class="ag-resizer ag-resizer-top"></div>
        <div ref="eTopRightResizer" class="ag-resizer ag-resizer-topRight"></div>
        <div ref="eRightResizer" class="ag-resizer ag-resizer-right"></div>
        <div ref="eBottomRightResizer" class="ag-resizer ag-resizer-bottomRight"></div>
        <div ref="eBottomResizer" class="ag-resizer ag-resizer-bottom"></div>
        <div ref="eBottomLeftResizer" class="ag-resizer ag-resizer-bottomLeft"></div>
        <div ref="eLeftResizer" class="ag-resizer ag-resizer-left"></div>
    </div>`
);
var PositionableFeature = class extends BeanStub {
  constructor(element, config) {
    super();
    this.element = element;
    this.dragStartPosition = {
      x: 0,
      y: 0
    };
    this.position = {
      x: 0,
      y: 0
    };
    this.lastSize = {
      width: -1,
      height: -1
    };
    this.positioned = false;
    this.resizersAdded = false;
    this.resizeListeners = [];
    this.boundaryEl = null;
    this.isResizing = false;
    this.isMoving = false;
    this.resizable = {};
    this.movable = false;
    this.currentResizer = null;
    this.config = Object.assign({}, { popup: false }, config);
  }
  center() {
    const { clientHeight, clientWidth } = this.offsetParent;
    const x = clientWidth / 2 - this.getWidth() / 2;
    const y = clientHeight / 2 - this.getHeight() / 2;
    this.offsetElement(x, y);
  }
  initialisePosition() {
    if (this.positioned) {
      return;
    }
    const { centered, forcePopupParentAsOffsetParent, minWidth, width, minHeight, height, x, y } = this.config;
    if (!this.offsetParent) {
      this.setOffsetParent();
    }
    let computedMinHeight = 0;
    let computedMinWidth = 0;
    const isElementVisible = isVisible(this.element);
    if (isElementVisible) {
      const boundaryEl = this.findBoundaryElement();
      const offsetParentComputedStyles = window.getComputedStyle(boundaryEl);
      if (offsetParentComputedStyles.minWidth != null) {
        const paddingWidth = boundaryEl.offsetWidth - this.element.offsetWidth;
        computedMinWidth = parseInt(offsetParentComputedStyles.minWidth, 10) - paddingWidth;
      }
      if (offsetParentComputedStyles.minHeight != null) {
        const paddingHeight = boundaryEl.offsetHeight - this.element.offsetHeight;
        computedMinHeight = parseInt(offsetParentComputedStyles.minHeight, 10) - paddingHeight;
      }
    }
    this.minHeight = minHeight || computedMinHeight;
    this.minWidth = minWidth || computedMinWidth;
    if (width) {
      this.setWidth(width);
    }
    if (height) {
      this.setHeight(height);
    }
    if (!width || !height) {
      this.refreshSize();
    }
    if (centered) {
      this.center();
    } else if (x || y) {
      this.offsetElement(x, y);
    } else if (isElementVisible && forcePopupParentAsOffsetParent) {
      let boundaryEl = this.boundaryEl;
      let initialisedDuringPositioning = true;
      if (!boundaryEl) {
        boundaryEl = this.findBoundaryElement();
        initialisedDuringPositioning = false;
      }
      if (boundaryEl) {
        const top = parseFloat(boundaryEl.style.top);
        const left = parseFloat(boundaryEl.style.left);
        if (initialisedDuringPositioning) {
          this.offsetElement(
            isNaN(left) ? 0 : left,
            isNaN(top) ? 0 : top
          );
        } else {
          this.setPosition(left, top);
        }
      }
    }
    this.positioned = !!this.offsetParent;
  }
  isPositioned() {
    return this.positioned;
  }
  getPosition() {
    return this.position;
  }
  setMovable(movable, moveElement) {
    if (!this.config.popup || movable === this.movable) {
      return;
    }
    this.movable = movable;
    const params = this.moveElementDragListener || {
      eElement: moveElement,
      onDragStart: this.onMoveStart.bind(this),
      onDragging: this.onMove.bind(this),
      onDragStop: this.onMoveEnd.bind(this)
    };
    if (movable) {
      this.dragService.addDragSource(params);
      this.moveElementDragListener = params;
    } else {
      this.dragService.removeDragSource(params);
      this.moveElementDragListener = void 0;
    }
  }
  setResizable(resizable) {
    this.clearResizeListeners();
    if (resizable) {
      this.addResizers();
    } else {
      this.removeResizers();
    }
    if (typeof resizable === "boolean") {
      if (resizable === false) {
        return;
      }
      resizable = {
        topLeft: resizable,
        top: resizable,
        topRight: resizable,
        right: resizable,
        bottomRight: resizable,
        bottom: resizable,
        bottomLeft: resizable,
        left: resizable
      };
    }
    Object.keys(resizable).forEach((side) => {
      const resizableStructure = resizable;
      const isSideResizable = !!resizableStructure[side];
      const resizerEl = this.getResizerElement(side);
      const params = {
        dragStartPixels: 0,
        eElement: resizerEl,
        onDragStart: (e) => this.onResizeStart(e, side),
        onDragging: this.onResize.bind(this),
        onDragStop: (e) => this.onResizeEnd(e, side)
      };
      if (isSideResizable || !this.isAlive() && !isSideResizable) {
        if (isSideResizable) {
          this.dragService.addDragSource(params);
          this.resizeListeners.push(params);
          resizerEl.style.pointerEvents = "all";
        } else {
          resizerEl.style.pointerEvents = "none";
        }
        this.resizable[side] = isSideResizable;
      }
    });
  }
  removeSizeFromEl() {
    this.element.style.removeProperty("height");
    this.element.style.removeProperty("width");
    this.element.style.removeProperty("flex");
  }
  restoreLastSize() {
    this.element.style.flex = "0 0 auto";
    const { height, width } = this.lastSize;
    if (width !== -1) {
      this.element.style.width = `${width}px`;
    }
    if (height !== -1) {
      this.element.style.height = `${height}px`;
    }
  }
  getHeight() {
    return this.element.offsetHeight;
  }
  setHeight(height) {
    const { popup } = this.config;
    const eGui = this.element;
    let isPercent = false;
    if (typeof height === "string" && height.indexOf("%") !== -1) {
      setFixedHeight(eGui, height);
      height = getAbsoluteHeight(eGui);
      isPercent = true;
    } else {
      height = Math.max(this.minHeight, height);
      if (this.positioned) {
        const availableHeight = this.getAvailableHeight();
        if (availableHeight && height > availableHeight) {
          height = availableHeight;
        }
      }
    }
    if (this.getHeight() === height) {
      return;
    }
    if (!isPercent) {
      if (popup) {
        setFixedHeight(eGui, height);
      } else {
        eGui.style.height = `${height}px`;
        eGui.style.flex = "0 0 auto";
        this.lastSize.height = typeof height === "number" ? height : parseFloat(height);
      }
    } else {
      eGui.style.maxHeight = "unset";
      eGui.style.minHeight = "unset";
    }
  }
  getAvailableHeight() {
    const { popup, forcePopupParentAsOffsetParent } = this.config;
    if (!this.positioned) {
      this.initialisePosition();
    }
    const { clientHeight } = this.offsetParent;
    if (!clientHeight) {
      return null;
    }
    const elRect = this.element.getBoundingClientRect();
    const offsetParentRect = this.offsetParent.getBoundingClientRect();
    const yPosition = popup ? this.position.y : elRect.top;
    const parentTop = popup ? 0 : offsetParentRect.top;
    let additionalHeight = 0;
    if (forcePopupParentAsOffsetParent) {
      const parentEl = this.element.parentElement;
      if (parentEl) {
        const { bottom } = parentEl.getBoundingClientRect();
        additionalHeight = bottom - elRect.bottom;
      }
    }
    const availableHeight = clientHeight + parentTop - yPosition - additionalHeight;
    return availableHeight;
  }
  getWidth() {
    return this.element.offsetWidth;
  }
  setWidth(width) {
    const eGui = this.element;
    const { popup } = this.config;
    let isPercent = false;
    if (typeof width === "string" && width.indexOf("%") !== -1) {
      setFixedWidth(eGui, width);
      width = getAbsoluteWidth(eGui);
      isPercent = true;
    } else if (this.positioned) {
      width = Math.max(this.minWidth, width);
      const { clientWidth } = this.offsetParent;
      const xPosition = popup ? this.position.x : this.element.getBoundingClientRect().left;
      if (clientWidth && width + xPosition > clientWidth) {
        width = clientWidth - xPosition;
      }
    }
    if (this.getWidth() === width) {
      return;
    }
    if (!isPercent) {
      if (this.config.popup) {
        setFixedWidth(eGui, width);
      } else {
        eGui.style.width = `${width}px`;
        eGui.style.flex = " unset";
        this.lastSize.width = typeof width === "number" ? width : parseFloat(width);
      }
    } else {
      eGui.style.maxWidth = "unset";
      eGui.style.minWidth = "unset";
    }
  }
  offsetElement(x = 0, y = 0) {
    const { forcePopupParentAsOffsetParent } = this.config;
    const ePopup = forcePopupParentAsOffsetParent ? this.boundaryEl : this.element;
    if (!ePopup) {
      return;
    }
    this.popupService.positionPopup({
      ePopup,
      keepWithinBounds: true,
      skipObserver: this.movable || this.isResizable(),
      updatePosition: () => ({ x, y })
    });
    this.setPosition(
      parseFloat(ePopup.style.left),
      parseFloat(ePopup.style.top)
    );
  }
  constrainSizeToAvailableHeight(constrain) {
    if (!this.config.forcePopupParentAsOffsetParent) {
      return;
    }
    const applyMaxHeightToElement = () => {
      const availableHeight = this.getAvailableHeight();
      this.element.style.setProperty("max-height", `${availableHeight}px`);
    };
    if (constrain) {
      this.resizeObserverSubscriber = this.resizeObserverService.observeResize(
        this.popupService.getPopupParent(),
        applyMaxHeightToElement
      );
    } else {
      this.element.style.removeProperty("max-height");
      if (this.resizeObserverSubscriber) {
        this.resizeObserverSubscriber();
        this.resizeObserverSubscriber = void 0;
      }
    }
  }
  setPosition(x, y) {
    this.position.x = x;
    this.position.y = y;
  }
  updateDragStartPosition(x, y) {
    this.dragStartPosition = { x, y };
  }
  calculateMouseMovement(params) {
    const { e, isLeft, isTop, anywhereWithin, topBuffer } = params;
    const xDiff = e.clientX - this.dragStartPosition.x;
    const yDiff = e.clientY - this.dragStartPosition.y;
    const movementX = this.shouldSkipX(e, !!isLeft, !!anywhereWithin, xDiff) ? 0 : xDiff;
    const movementY = this.shouldSkipY(e, !!isTop, topBuffer, yDiff) ? 0 : yDiff;
    return { movementX, movementY };
  }
  shouldSkipX(e, isLeft, anywhereWithin, diff) {
    const elRect = this.element.getBoundingClientRect();
    const parentRect = this.offsetParent.getBoundingClientRect();
    const boundaryElRect = this.boundaryEl.getBoundingClientRect();
    const xPosition = this.config.popup ? this.position.x : elRect.left;
    let skipX = xPosition <= 0 && parentRect.left >= e.clientX || parentRect.right <= e.clientX && parentRect.right <= boundaryElRect.right;
    if (skipX) {
      return true;
    }
    if (isLeft) {
      skipX = // skip if we are moving to the left and the cursor
      // is positioned to the right of the left side anchor
      diff < 0 && e.clientX > xPosition + parentRect.left || // skip if we are moving to the right and the cursor
      // is positioned to the left of the dialog
      diff > 0 && e.clientX < xPosition + parentRect.left;
    } else {
      if (anywhereWithin) {
        skipX = diff < 0 && e.clientX > boundaryElRect.right || diff > 0 && e.clientX < xPosition + parentRect.left;
      } else {
        skipX = // if the movement is bound to the right side of the dialog
        // we skip if we are moving to the left and the cursor
        // is to the right of the dialog
        diff < 0 && e.clientX > boundaryElRect.right || // or skip if we are moving to the right and the cursor
        // is to the left of the right side anchor
        diff > 0 && e.clientX < boundaryElRect.right;
      }
    }
    return skipX;
  }
  shouldSkipY(e, isTop, topBuffer = 0, diff) {
    const elRect = this.element.getBoundingClientRect();
    const parentRect = this.offsetParent.getBoundingClientRect();
    const boundaryElRect = this.boundaryEl.getBoundingClientRect();
    const yPosition = this.config.popup ? this.position.y : elRect.top;
    let skipY = yPosition <= 0 && parentRect.top >= e.clientY || parentRect.bottom <= e.clientY && parentRect.bottom <= boundaryElRect.bottom;
    if (skipY) {
      return true;
    }
    if (isTop) {
      skipY = // skip if we are moving to towards top and the cursor is
      // below the top anchor + topBuffer
      // note: topBuffer is used when moving the dialog using the title bar
      diff < 0 && e.clientY > yPosition + parentRect.top + topBuffer || // skip if we are moving to the bottom and the cursor is
      // above the top anchor
      diff > 0 && e.clientY < yPosition + parentRect.top;
    } else {
      skipY = // skip if we are moving towards the top and the cursor
      // is below the bottom anchor
      diff < 0 && e.clientY > boundaryElRect.bottom || // skip if we are moving towards the bottom and the cursor
      // is above the bottom anchor
      diff > 0 && e.clientY < boundaryElRect.bottom;
    }
    return skipY;
  }
  createResizeMap() {
    const eGui = this.element;
    this.resizerMap = {
      topLeft: { element: eGui.querySelector("[ref=eTopLeftResizer]") },
      top: { element: eGui.querySelector("[ref=eTopResizer]") },
      topRight: { element: eGui.querySelector("[ref=eTopRightResizer]") },
      right: { element: eGui.querySelector("[ref=eRightResizer]") },
      bottomRight: { element: eGui.querySelector("[ref=eBottomRightResizer]") },
      bottom: { element: eGui.querySelector("[ref=eBottomResizer]") },
      bottomLeft: { element: eGui.querySelector("[ref=eBottomLeftResizer]") },
      left: { element: eGui.querySelector("[ref=eLeftResizer]") }
    };
  }
  addResizers() {
    if (this.resizersAdded) {
      return;
    }
    const eGui = this.element;
    if (!eGui) {
      return;
    }
    const parser = new DOMParser();
    const resizers = parser.parseFromString(RESIZE_TEMPLATE, "text/html").body;
    eGui.appendChild(resizers.firstChild);
    this.createResizeMap();
    this.resizersAdded = true;
  }
  removeResizers() {
    this.resizerMap = void 0;
    const resizerEl = this.element.querySelector(`.${RESIZE_CONTAINER_STYLE}`);
    if (resizerEl) {
      this.element.removeChild(resizerEl);
    }
    this.resizersAdded = false;
  }
  getResizerElement(side) {
    return this.resizerMap[side].element;
  }
  onResizeStart(e, side) {
    this.boundaryEl = this.findBoundaryElement();
    if (!this.positioned) {
      this.initialisePosition();
    }
    this.currentResizer = {
      isTop: !!side.match(/top/i),
      isRight: !!side.match(/right/i),
      isBottom: !!side.match(/bottom/i),
      isLeft: !!side.match(/left/i)
    };
    this.element.classList.add("ag-resizing");
    this.resizerMap[side].element.classList.add("ag-active");
    const { popup, forcePopupParentAsOffsetParent } = this.config;
    if (!popup && !forcePopupParentAsOffsetParent) {
      this.applySizeToSiblings(this.currentResizer.isBottom || this.currentResizer.isTop);
    }
    this.isResizing = true;
    this.updateDragStartPosition(e.clientX, e.clientY);
  }
  getSiblings() {
    const element = this.element;
    const parent = element.parentElement;
    if (!parent) {
      return null;
    }
    return Array.prototype.slice.call(parent.children).filter((el) => !el.classList.contains("ag-hidden"));
  }
  getMinSizeOfSiblings() {
    const siblings = this.getSiblings() || [];
    let height = 0;
    let width = 0;
    for (let i = 0; i < siblings.length; i++) {
      const currentEl = siblings[i];
      const isFlex = !!currentEl.style.flex && currentEl.style.flex !== "0 0 auto";
      if (currentEl === this.element) {
        continue;
      }
      let nextHeight = this.minHeight || 0;
      let nextWidth = this.minWidth || 0;
      if (isFlex) {
        const computedStyle = window.getComputedStyle(currentEl);
        if (computedStyle.minHeight) {
          nextHeight = parseInt(computedStyle.minHeight, 10);
        }
        if (computedStyle.minWidth) {
          nextWidth = parseInt(computedStyle.minWidth, 10);
        }
      } else {
        nextHeight = currentEl.offsetHeight;
        nextWidth = currentEl.offsetWidth;
      }
      height += nextHeight;
      width += nextWidth;
    }
    return { height, width };
  }
  applySizeToSiblings(vertical) {
    let containerToFlex = null;
    const siblings = this.getSiblings();
    if (!siblings) {
      return;
    }
    for (let i = 0; i < siblings.length; i++) {
      const el = siblings[i];
      if (el === containerToFlex) {
        continue;
      }
      if (vertical) {
        el.style.height = `${el.offsetHeight}px`;
      } else {
        el.style.width = `${el.offsetWidth}px`;
      }
      el.style.flex = "0 0 auto";
      if (el === this.element) {
        containerToFlex = siblings[i + 1];
      }
    }
    if (containerToFlex) {
      containerToFlex.style.removeProperty("height");
      containerToFlex.style.removeProperty("min-height");
      containerToFlex.style.removeProperty("max-height");
      containerToFlex.style.flex = "1 1 auto";
    }
  }
  isResizable() {
    return Object.values(this.resizable).some((value) => value);
  }
  onResize(e) {
    if (!this.isResizing || !this.currentResizer) {
      return;
    }
    const { popup, forcePopupParentAsOffsetParent } = this.config;
    const { isTop, isRight, isBottom, isLeft } = this.currentResizer;
    const isHorizontal = isRight || isLeft;
    const isVertical = isBottom || isTop;
    const { movementX, movementY } = this.calculateMouseMovement({ e, isLeft, isTop });
    const xPosition = this.position.x;
    const yPosition = this.position.y;
    let offsetLeft = 0;
    let offsetTop = 0;
    if (isHorizontal && movementX) {
      const direction = isLeft ? -1 : 1;
      const oldWidth = this.getWidth();
      const newWidth = oldWidth + movementX * direction;
      let skipWidth = false;
      if (isLeft) {
        offsetLeft = oldWidth - newWidth;
        if (xPosition + offsetLeft <= 0 || newWidth <= this.minWidth) {
          skipWidth = true;
          offsetLeft = 0;
        }
      }
      if (!skipWidth) {
        this.setWidth(newWidth);
      }
    }
    if (isVertical && movementY) {
      const direction = isTop ? -1 : 1;
      const oldHeight = this.getHeight();
      const newHeight = oldHeight + movementY * direction;
      let skipHeight = false;
      if (isTop) {
        offsetTop = oldHeight - newHeight;
        if (yPosition + offsetTop <= 0 || newHeight <= this.minHeight) {
          skipHeight = true;
          offsetTop = 0;
        }
      } else {
        if (!this.config.popup && !this.config.forcePopupParentAsOffsetParent && oldHeight < newHeight && this.getMinSizeOfSiblings().height + newHeight > this.element.parentElement.offsetHeight) {
          skipHeight = true;
        }
      }
      if (!skipHeight) {
        this.setHeight(newHeight);
      }
    }
    this.updateDragStartPosition(e.clientX, e.clientY);
    if ((popup || forcePopupParentAsOffsetParent) && offsetLeft || offsetTop) {
      this.offsetElement(
        xPosition + offsetLeft,
        yPosition + offsetTop
      );
    }
  }
  onResizeEnd(e, side) {
    this.isResizing = false;
    this.currentResizer = null;
    this.boundaryEl = null;
    const params = {
      type: "resize"
    };
    this.element.classList.remove("ag-resizing");
    this.resizerMap[side].element.classList.remove("ag-active");
    this.dispatchEvent(params);
  }
  refreshSize() {
    const eGui = this.element;
    if (this.config.popup) {
      if (!this.config.width) {
        this.setWidth(eGui.offsetWidth);
      }
      if (!this.config.height) {
        this.setHeight(eGui.offsetHeight);
      }
    }
  }
  onMoveStart(e) {
    this.boundaryEl = this.findBoundaryElement();
    if (!this.positioned) {
      this.initialisePosition();
    }
    this.isMoving = true;
    this.element.classList.add("ag-moving");
    this.updateDragStartPosition(e.clientX, e.clientY);
  }
  onMove(e) {
    if (!this.isMoving) {
      return;
    }
    const { x, y } = this.position;
    let topBuffer;
    if (this.config.calculateTopBuffer) {
      topBuffer = this.config.calculateTopBuffer();
    }
    const { movementX, movementY } = this.calculateMouseMovement({
      e,
      isTop: true,
      anywhereWithin: true,
      topBuffer
    });
    this.offsetElement(x + movementX, y + movementY);
    this.updateDragStartPosition(e.clientX, e.clientY);
  }
  onMoveEnd() {
    this.isMoving = false;
    this.boundaryEl = null;
    this.element.classList.remove("ag-moving");
  }
  setOffsetParent() {
    if (this.config.forcePopupParentAsOffsetParent) {
      this.offsetParent = this.popupService.getPopupParent();
    } else {
      this.offsetParent = this.element.offsetParent;
    }
  }
  findBoundaryElement() {
    let el = this.element;
    while (el) {
      if (window.getComputedStyle(el).position !== "static") {
        return el;
      }
      el = el.parentElement;
    }
    return this.element;
  }
  clearResizeListeners() {
    while (this.resizeListeners.length) {
      const params = this.resizeListeners.pop();
      this.dragService.removeDragSource(params);
    }
  }
  destroy() {
    super.destroy();
    if (this.moveElementDragListener) {
      this.dragService.removeDragSource(this.moveElementDragListener);
    }
    this.constrainSizeToAvailableHeight(false);
    this.clearResizeListeners();
    this.removeResizers();
  }
};
__decorateClass([
  Autowired("popupService")
], PositionableFeature.prototype, "popupService", 2);
__decorateClass([
  Autowired("resizeObserverService")
], PositionableFeature.prototype, "resizeObserverService", 2);
__decorateClass([
  Autowired("dragService")
], PositionableFeature.prototype, "dragService", 2);

// community-modules/core/src/filter/provided/providedFilter.ts
var _ProvidedFilter = class _ProvidedFilter extends Component {
  constructor(filterNameKey) {
    super();
    this.filterNameKey = filterNameKey;
    this.applyActive = false;
    this.hidePopup = null;
    this.debouncePending = false;
    // after the user hits 'apply' the model gets copied to here. this is then the model that we use for
    // all filtering. so if user changes UI but doesn't hit apply, then the UI will be out of sync with this model.
    // this is what we want, as the UI should only become the 'active' filter once it's applied. when apply is
    // inactive, this model will be in sync (following the debounce ms). if the UI is not a valid filter
    // (eg the value is missing so nothing to filter on, or for set filter all checkboxes are checked so filter
    // not active) then this appliedModel will be null/undefined.
    this.appliedModel = null;
    this.buttonListeners = [];
  }
  postConstruct() {
    this.resetTemplate();
    this.createManagedBean(new ManagedFocusFeature(
      this.getFocusableElement(),
      {
        handleKeyDown: this.handleKeyDown.bind(this)
      }
    ));
    this.positionableFeature = new PositionableFeature(
      this.getPositionableElement(),
      {
        forcePopupParentAsOffsetParent: true
      }
    );
    this.createBean(this.positionableFeature);
  }
  // override
  handleKeyDown(e) {
  }
  getFilterTitle() {
    return this.translate(this.filterNameKey);
  }
  isFilterActive() {
    return !!this.appliedModel;
  }
  resetTemplate(paramsMap) {
    let eGui = this.getGui();
    if (eGui) {
      eGui.removeEventListener("submit", this.onFormSubmit);
    }
    const templateString = (
      /* html */
      `
            <form class="ag-filter-wrapper">
                <div class="ag-filter-body-wrapper ag-${this.getCssIdentifier()}-body-wrapper" ref="eFilterBody">
                    ${this.createBodyTemplate()}
                </div>
            </form>`
    );
    this.setTemplate(templateString, paramsMap);
    eGui = this.getGui();
    if (eGui) {
      eGui.addEventListener("submit", this.onFormSubmit);
    }
  }
  isReadOnly() {
    return !!this.providedFilterParams.readOnly;
  }
  init(params) {
    this.setParams(params);
    this.resetUiToDefaults(true).then(() => {
      this.updateUiVisibility();
      this.setupOnBtApplyDebounce();
    });
  }
  setParams(params) {
    this.providedFilterParams = params;
    this.applyActive = _ProvidedFilter.isUseApplyButton(params);
    this.resetButtonsPanel();
  }
  updateParams(params) {
    this.providedFilterParams = params;
    this.applyActive = _ProvidedFilter.isUseApplyButton(params);
    this.resetUiToActiveModel(this.getModel(), () => {
      this.updateUiVisibility();
      this.setupOnBtApplyDebounce();
    });
  }
  resetButtonsPanel() {
    const { buttons } = this.providedFilterParams;
    const hasButtons = buttons && buttons.length > 0 && !this.isReadOnly();
    if (!this.eButtonsPanel) {
      if (hasButtons) {
        this.eButtonsPanel = document.createElement("div");
        this.eButtonsPanel.classList.add("ag-filter-apply-panel");
      }
    } else {
      clearElement(this.eButtonsPanel);
      this.buttonListeners.forEach((destroyFunc) => destroyFunc == null ? void 0 : destroyFunc());
      this.buttonListeners = [];
    }
    if (!hasButtons) {
      if (this.eButtonsPanel) {
        removeFromParent(this.eButtonsPanel);
      }
      return;
    }
    const fragment = document.createDocumentFragment();
    const addButton = (type) => {
      let text;
      let clickListener;
      switch (type) {
        case "apply":
          text = this.translate("applyFilter");
          clickListener = (e) => this.onBtApply(false, false, e);
          break;
        case "clear":
          text = this.translate("clearFilter");
          clickListener = () => this.onBtClear();
          break;
        case "reset":
          text = this.translate("resetFilter");
          clickListener = () => this.onBtReset();
          break;
        case "cancel":
          text = this.translate("cancelFilter");
          clickListener = (e) => {
            this.onBtCancel(e);
          };
          break;
        default:
          console.warn("AG Grid: Unknown button type specified");
          return;
      }
      const buttonType = type === "apply" ? "submit" : "button";
      const button = loadTemplate(
        /* html */
        `<button
                    type="${buttonType}"
                    ref="${type}FilterButton"
                    class="ag-button ag-standard-button ag-filter-apply-panel-button"
                >${text}
                </button>`
      );
      this.buttonListeners.push(this.addManagedListener(button, "click", clickListener));
      fragment.append(button);
    };
    convertToSet(buttons).forEach((type) => addButton(type));
    this.eButtonsPanel.append(fragment);
    this.getGui().appendChild(this.eButtonsPanel);
  }
  // subclasses can override this to provide alternative debounce defaults
  getDefaultDebounceMs() {
    return 0;
  }
  setupOnBtApplyDebounce() {
    const debounceMs = _ProvidedFilter.getDebounceMs(this.providedFilterParams, this.getDefaultDebounceMs());
    const debounceFunc = debounce(this.checkApplyDebounce.bind(this), debounceMs);
    this.onBtApplyDebounce = () => {
      this.debouncePending = true;
      debounceFunc();
    };
  }
  checkApplyDebounce() {
    if (this.debouncePending) {
      this.debouncePending = false;
      this.onBtApply();
    }
  }
  getModel() {
    return this.appliedModel ? this.appliedModel : null;
  }
  setModel(model) {
    const promise = model != null ? this.setModelIntoUi(model) : this.resetUiToDefaults();
    return promise.then(() => {
      this.updateUiVisibility();
      this.applyModel("api");
    });
  }
  onBtCancel(e) {
    this.resetUiToActiveModel(this.getModel(), () => {
      this.handleCancelEnd(e);
    });
  }
  handleCancelEnd(e) {
    if (this.providedFilterParams.closeOnApply) {
      this.close(e);
    }
  }
  resetUiToActiveModel(currentModel, afterUiUpdatedFunc) {
    const afterAppliedFunc = () => {
      this.onUiChanged(false, "prevent");
      afterUiUpdatedFunc == null ? void 0 : afterUiUpdatedFunc();
    };
    if (currentModel != null) {
      this.setModelIntoUi(currentModel).then(afterAppliedFunc);
    } else {
      this.resetUiToDefaults().then(afterAppliedFunc);
    }
  }
  onBtClear() {
    this.resetUiToDefaults().then(() => this.onUiChanged());
  }
  onBtReset() {
    this.onBtClear();
    this.onBtApply();
  }
  /**
   * Applies changes made in the UI to the filter, and returns true if the model has changed.
   */
  applyModel(source = "api") {
    const newModel = this.getModelFromUi();
    if (!this.isModelValid(newModel)) {
      return false;
    }
    const previousModel = this.appliedModel;
    this.appliedModel = newModel;
    return !this.areModelsEqual(previousModel, newModel);
  }
  isModelValid(model) {
    return true;
  }
  onFormSubmit(e) {
    e.preventDefault();
  }
  onBtApply(afterFloatingFilter = false, afterDataChange = false, e) {
    if (e) {
      e.preventDefault();
    }
    if (this.applyModel(afterDataChange ? "rowDataUpdated" : "ui")) {
      const source = "columnFilter";
      this.providedFilterParams.filterChangedCallback({ afterFloatingFilter, afterDataChange, source });
    }
    const { closeOnApply } = this.providedFilterParams;
    if (closeOnApply && this.applyActive && !afterFloatingFilter && !afterDataChange) {
      this.close(e);
    }
  }
  onNewRowsLoaded() {
  }
  close(e) {
    if (!this.hidePopup) {
      return;
    }
    const keyboardEvent = e;
    const key = keyboardEvent && keyboardEvent.key;
    let params;
    if (key === "Enter" || key === "Space") {
      params = { keyboardEvent };
    }
    this.hidePopup(params);
    this.hidePopup = null;
  }
  /**
   * By default, if the change came from a floating filter it will be applied immediately, otherwise if there is no
   * apply button it will be applied after a debounce, otherwise it will not be applied at all. This behaviour can
   * be adjusted by using the apply parameter.
   */
  onUiChanged(fromFloatingFilter = false, apply) {
    this.updateUiVisibility();
    this.providedFilterParams.filterModifiedCallback();
    if (this.applyActive && !this.isReadOnly()) {
      const isValid = this.isModelValid(this.getModelFromUi());
      const applyFilterButton = this.getRefElement("applyFilterButton");
      if (applyFilterButton) {
        setDisabled(applyFilterButton, !isValid);
      }
    }
    if (fromFloatingFilter && !apply || apply === "immediately") {
      this.onBtApply(fromFloatingFilter);
    } else if (!this.applyActive && !apply || apply === "debounce") {
      this.onBtApplyDebounce();
    }
  }
  afterGuiAttached(params) {
    if (params) {
      this.hidePopup = params.hidePopup;
    }
    this.refreshFilterResizer(params == null ? void 0 : params.container);
  }
  refreshFilterResizer(containerType) {
    if (!this.positionableFeature || containerType === "toolPanel") {
      return;
    }
    const isResizable = containerType === "floatingFilter" || containerType === "columnFilter";
    const { positionableFeature, gos } = this;
    if (isResizable) {
      positionableFeature.restoreLastSize();
      positionableFeature.setResizable(
        gos.get("enableRtl") ? { bottom: true, bottomLeft: true, left: true } : { bottom: true, bottomRight: true, right: true }
      );
    } else {
      this.positionableFeature.removeSizeFromEl();
      this.positionableFeature.setResizable(false);
    }
    this.positionableFeature.constrainSizeToAvailableHeight(true);
  }
  afterGuiDetached() {
    this.checkApplyDebounce();
    if (this.positionableFeature) {
      this.positionableFeature.constrainSizeToAvailableHeight(false);
    }
  }
  // static, as used by floating filter also
  static getDebounceMs(params, debounceDefault) {
    if (_ProvidedFilter.isUseApplyButton(params)) {
      if (params.debounceMs != null) {
        console.warn("AG Grid: debounceMs is ignored when apply button is present");
      }
      return 0;
    }
    return params.debounceMs != null ? params.debounceMs : debounceDefault;
  }
  // static, as used by floating filter also
  static isUseApplyButton(params) {
    return !!params.buttons && params.buttons.indexOf("apply") >= 0;
  }
  refresh(newParams) {
    this.providedFilterParams = newParams;
    return true;
  }
  destroy() {
    const eGui = this.getGui();
    if (eGui) {
      eGui.removeEventListener("submit", this.onFormSubmit);
    }
    this.hidePopup = null;
    if (this.positionableFeature) {
      this.positionableFeature = this.destroyBean(this.positionableFeature);
    }
    this.appliedModel = null;
    super.destroy();
  }
  translate(key) {
    const translate = this.localeService.getLocaleTextFunc();
    return translate(key, FILTER_LOCALE_TEXT[key]);
  }
  getCellValue(rowNode) {
    return this.providedFilterParams.getValue(rowNode);
  }
  // override to control positionable feature
  getPositionableElement() {
    return this.eFilterBody;
  }
};
__decorateClass([
  Autowired("rowModel")
], _ProvidedFilter.prototype, "rowModel", 2);
__decorateClass([
  RefSelector("eFilterBody")
], _ProvidedFilter.prototype, "eFilterBody", 2);
__decorateClass([
  PostConstruct
], _ProvidedFilter.prototype, "postConstruct", 1);
var ProvidedFilter = _ProvidedFilter;

// community-modules/core/src/widgets/agAbstractLabel.ts
var AgAbstractLabel = class extends Component {
  constructor(config, template) {
    super(template);
    this.labelSeparator = "";
    this.labelAlignment = "left";
    this.disabled = false;
    this.label = "";
    this.config = config || {};
  }
  postConstruct() {
    this.addCssClass("ag-labeled");
    this.eLabel.classList.add("ag-label");
    const { labelSeparator, label, labelWidth, labelAlignment, disabled } = this.config;
    if (disabled != null) {
      this.setDisabled(disabled);
    }
    if (labelSeparator != null) {
      this.setLabelSeparator(labelSeparator);
    }
    if (label != null) {
      this.setLabel(label);
    }
    if (labelWidth != null) {
      this.setLabelWidth(labelWidth);
    }
    this.setLabelAlignment(labelAlignment || this.labelAlignment);
    this.refreshLabel();
  }
  refreshLabel() {
    clearElement(this.eLabel);
    if (typeof this.label === "string") {
      this.eLabel.innerText = this.label + this.labelSeparator;
    } else if (this.label) {
      this.eLabel.appendChild(this.label);
    }
    if (this.label === "") {
      setDisplayed(this.eLabel, false);
      setAriaRole(this.eLabel, "presentation");
    } else {
      setDisplayed(this.eLabel, true);
      setAriaRole(this.eLabel, null);
    }
  }
  setLabelSeparator(labelSeparator) {
    if (this.labelSeparator === labelSeparator) {
      return this;
    }
    this.labelSeparator = labelSeparator;
    if (this.label != null) {
      this.refreshLabel();
    }
    return this;
  }
  getLabelId() {
    this.eLabel.id = this.eLabel.id || `ag-${this.getCompId()}-label`;
    return this.eLabel.id;
  }
  getLabel() {
    return this.label;
  }
  setLabel(label) {
    if (this.label === label) {
      return this;
    }
    this.label = label;
    this.refreshLabel();
    return this;
  }
  setLabelAlignment(alignment) {
    const eGui = this.getGui();
    const eGuiClassList = eGui.classList;
    eGuiClassList.toggle("ag-label-align-left", alignment === "left");
    eGuiClassList.toggle("ag-label-align-right", alignment === "right");
    eGuiClassList.toggle("ag-label-align-top", alignment === "top");
    return this;
  }
  setLabelEllipsis(hasEllipsis) {
    this.eLabel.classList.toggle("ag-label-ellipsis", hasEllipsis);
    return this;
  }
  setLabelWidth(width) {
    if (this.label == null) {
      return this;
    }
    setElementWidth(this.eLabel, width);
    return this;
  }
  setDisabled(disabled) {
    disabled = !!disabled;
    const element = this.getGui();
    setDisabled(element, disabled);
    element.classList.toggle("ag-disabled", disabled);
    this.disabled = disabled;
    return this;
  }
  isDisabled() {
    return !!this.disabled;
  }
};
__decorateClass([
  PostConstruct
], AgAbstractLabel.prototype, "postConstruct", 1);

// community-modules/core/src/widgets/agAbstractField.ts
var AgAbstractField = class extends AgAbstractLabel {
  constructor(config, template, className) {
    super(config, template);
    this.className = className;
  }
  postConstruct() {
    super.postConstruct();
    const { width, value, onValueChange } = this.config;
    if (width != null) {
      this.setWidth(width);
    }
    if (value != null) {
      this.setValue(value);
    }
    if (onValueChange != null) {
      this.onValueChange(onValueChange);
    }
    if (this.className) {
      this.addCssClass(this.className);
    }
    this.refreshAriaLabelledBy();
  }
  refreshAriaLabelledBy() {
    const ariaEl = this.getAriaElement();
    const labelId = this.getLabelId();
    if (getAriaLabel(ariaEl) !== null) {
      setAriaLabelledBy(ariaEl, "");
    } else {
      setAriaLabelledBy(ariaEl, labelId != null ? labelId : "");
    }
  }
  setAriaLabel(label) {
    setAriaLabel(this.getAriaElement(), label);
    this.refreshAriaLabelledBy();
    return this;
  }
  onValueChange(callbackFn) {
    this.addManagedListener(this, Events.EVENT_FIELD_VALUE_CHANGED, () => callbackFn(this.getValue()));
    return this;
  }
  getWidth() {
    return this.getGui().clientWidth;
  }
  setWidth(width) {
    setFixedWidth(this.getGui(), width);
    return this;
  }
  getPreviousValue() {
    return this.previousValue;
  }
  getValue() {
    return this.value;
  }
  setValue(value, silent) {
    if (this.value === value) {
      return this;
    }
    this.previousValue = this.value;
    this.value = value;
    if (!silent) {
      this.dispatchEvent({ type: Events.EVENT_FIELD_VALUE_CHANGED });
    }
    return this;
  }
};

// community-modules/core/src/widgets/agPickerField.ts
var TEMPLATE = (
  /* html */
  `
    <div class="ag-picker-field" role="presentation">
        <div ref="eLabel"></div>
            <div ref="eWrapper" class="ag-wrapper ag-picker-field-wrapper ag-picker-collapsed">
            <div ref="eDisplayField" class="ag-picker-field-display"></div>
            <div ref="eIcon" class="ag-picker-field-icon" aria-hidden="true"></div>
        </div>
    </div>`
);
var AgPickerField = class extends AgAbstractField {
  constructor(config) {
    super(config, (config == null ? void 0 : config.template) || TEMPLATE, config == null ? void 0 : config.className);
    this.isPickerDisplayed = false;
    this.skipClick = false;
    this.pickerGap = 4;
    this.hideCurrentPicker = null;
    this.ariaRole = config == null ? void 0 : config.ariaRole;
    this.onPickerFocusIn = this.onPickerFocusIn.bind(this);
    this.onPickerFocusOut = this.onPickerFocusOut.bind(this);
    if (!config) {
      return;
    }
    const { pickerGap, maxPickerHeight, variableWidth, minPickerWidth, maxPickerWidth } = config;
    if (pickerGap != null) {
      this.pickerGap = pickerGap;
    }
    this.variableWidth = !!variableWidth;
    if (maxPickerHeight != null) {
      this.setPickerMaxHeight(maxPickerHeight);
    }
    if (minPickerWidth != null) {
      this.setPickerMinWidth(minPickerWidth);
    }
    if (maxPickerWidth != null) {
      this.setPickerMaxWidth(maxPickerWidth);
    }
  }
  postConstruct() {
    super.postConstruct();
    this.setupAria();
    const displayId = `ag-${this.getCompId()}-display`;
    this.eDisplayField.setAttribute("id", displayId);
    const ariaEl = this.getAriaElement();
    this.addManagedListener(ariaEl, "keydown", this.onKeyDown.bind(this));
    this.addManagedListener(this.eLabel, "mousedown", this.onLabelOrWrapperMouseDown.bind(this));
    this.addManagedListener(this.eWrapper, "mousedown", this.onLabelOrWrapperMouseDown.bind(this));
    const { pickerIcon, inputWidth } = this.config;
    if (pickerIcon) {
      const icon = createIconNoSpan(pickerIcon, this.gos);
      if (icon) {
        this.eIcon.appendChild(icon);
      }
    }
    if (inputWidth != null) {
      this.setInputWidth(inputWidth);
    }
  }
  setupAria() {
    const ariaEl = this.getAriaElement();
    ariaEl.setAttribute("tabindex", this.gos.get("tabIndex").toString());
    setAriaExpanded(ariaEl, false);
    if (this.ariaRole) {
      setAriaRole(ariaEl, this.ariaRole);
    }
  }
  onLabelOrWrapperMouseDown(e) {
    if (e) {
      const focusableEl = this.getFocusableElement();
      if (focusableEl !== this.eWrapper && (e == null ? void 0 : e.target) === focusableEl) {
        return;
      }
      e.preventDefault();
      this.getFocusableElement().focus();
    }
    if (this.skipClick) {
      this.skipClick = false;
      return;
    }
    if (this.isDisabled()) {
      return;
    }
    if (this.isPickerDisplayed) {
      this.hidePicker();
    } else {
      this.showPicker();
    }
  }
  onKeyDown(e) {
    switch (e.key) {
      case KeyCode.UP:
      case KeyCode.DOWN:
      case KeyCode.ENTER:
      case KeyCode.SPACE:
        e.preventDefault();
        this.onLabelOrWrapperMouseDown();
        break;
      case KeyCode.ESCAPE:
        if (this.isPickerDisplayed) {
          e.preventDefault();
          e.stopPropagation();
          if (this.hideCurrentPicker) {
            this.hideCurrentPicker();
          }
        }
        break;
    }
  }
  showPicker() {
    this.isPickerDisplayed = true;
    if (!this.pickerComponent) {
      this.pickerComponent = this.createPickerComponent();
    }
    const pickerGui = this.pickerComponent.getGui();
    pickerGui.addEventListener("focusin", this.onPickerFocusIn);
    pickerGui.addEventListener("focusout", this.onPickerFocusOut);
    this.hideCurrentPicker = this.renderAndPositionPicker();
    this.toggleExpandedStyles(true);
  }
  renderAndPositionPicker() {
    const eDocument = this.gos.getDocument();
    const ePicker = this.pickerComponent.getGui();
    if (!this.gos.get("suppressScrollWhenPopupsAreOpen")) {
      this.destroyMouseWheelFunc = this.addManagedListener(this.eventService, Events.EVENT_BODY_SCROLL, () => {
        this.hidePicker();
      });
    }
    const translate = this.localeService.getLocaleTextFunc();
    const { pickerAriaLabelKey, pickerAriaLabelValue, modalPicker = true } = this.config;
    const popupParams = {
      modal: modalPicker,
      eChild: ePicker,
      closeOnEsc: true,
      closedCallback: () => {
        const activeEl = this.gos.getActiveDomElement();
        const shouldRestoreFocus = !activeEl || activeEl === eDocument.body;
        this.beforeHidePicker();
        if (shouldRestoreFocus && this.isAlive()) {
          this.getFocusableElement().focus();
        }
      },
      ariaLabel: translate(pickerAriaLabelKey, pickerAriaLabelValue)
    };
    const addPopupRes = this.popupService.addPopup(popupParams);
    const { maxPickerHeight, minPickerWidth, maxPickerWidth, variableWidth } = this;
    if (variableWidth) {
      if (minPickerWidth) {
        ePicker.style.minWidth = minPickerWidth;
      }
      ePicker.style.width = formatSize(getAbsoluteWidth(this.eWrapper));
      if (maxPickerWidth) {
        ePicker.style.maxWidth = maxPickerWidth;
      }
    } else {
      setElementWidth(ePicker, maxPickerWidth != null ? maxPickerWidth : getAbsoluteWidth(this.eWrapper));
    }
    const maxHeight = maxPickerHeight != null ? maxPickerHeight : `${getInnerHeight(this.popupService.getPopupParent())}px`;
    ePicker.style.setProperty("max-height", maxHeight);
    ePicker.style.position = "absolute";
    this.alignPickerToComponent();
    return addPopupRes.hideFunc;
  }
  alignPickerToComponent() {
    if (!this.pickerComponent) {
      return;
    }
    const { pickerType } = this.config;
    const { pickerGap } = this;
    const alignSide = this.gos.get("enableRtl") ? "right" : "left";
    this.popupService.positionPopupByComponent({
      type: pickerType,
      eventSource: this.eWrapper,
      ePopup: this.pickerComponent.getGui(),
      position: "under",
      alignSide,
      keepWithinBounds: true,
      nudgeY: pickerGap
    });
  }
  beforeHidePicker() {
    if (this.destroyMouseWheelFunc) {
      this.destroyMouseWheelFunc();
      this.destroyMouseWheelFunc = void 0;
    }
    this.toggleExpandedStyles(false);
    const pickerGui = this.pickerComponent.getGui();
    pickerGui.removeEventListener("focusin", this.onPickerFocusIn);
    pickerGui.removeEventListener("focusout", this.onPickerFocusOut);
    this.isPickerDisplayed = false;
    this.pickerComponent = void 0;
    this.hideCurrentPicker = null;
  }
  toggleExpandedStyles(expanded) {
    if (!this.isAlive()) {
      return;
    }
    const ariaEl = this.getAriaElement();
    setAriaExpanded(ariaEl, expanded);
    this.eWrapper.classList.toggle("ag-picker-expanded", expanded);
    this.eWrapper.classList.toggle("ag-picker-collapsed", !expanded);
  }
  onPickerFocusIn() {
    this.togglePickerHasFocus(true);
  }
  onPickerFocusOut(e) {
    var _a;
    if (!((_a = this.pickerComponent) == null ? void 0 : _a.getGui().contains(e.relatedTarget))) {
      this.togglePickerHasFocus(false);
    }
  }
  togglePickerHasFocus(focused) {
    if (!this.pickerComponent) {
      return;
    }
    this.eWrapper.classList.toggle("ag-picker-has-focus", focused);
  }
  hidePicker() {
    if (this.hideCurrentPicker) {
      this.hideCurrentPicker();
    }
  }
  setInputWidth(width) {
    setElementWidth(this.eWrapper, width);
    return this;
  }
  getFocusableElement() {
    return this.eWrapper;
  }
  setPickerGap(gap) {
    this.pickerGap = gap;
    return this;
  }
  setPickerMinWidth(width) {
    if (typeof width === "number") {
      width = `${width}px`;
    }
    this.minPickerWidth = width == null ? void 0 : width;
    return this;
  }
  setPickerMaxWidth(width) {
    if (typeof width === "number") {
      width = `${width}px`;
    }
    this.maxPickerWidth = width == null ? void 0 : width;
    return this;
  }
  setPickerMaxHeight(height) {
    if (typeof height === "number") {
      height = `${height}px`;
    }
    this.maxPickerHeight = height == null ? void 0 : height;
    return this;
  }
  destroy() {
    this.hidePicker();
    super.destroy();
  }
};
__decorateClass([
  Autowired("popupService")
], AgPickerField.prototype, "popupService", 2);
__decorateClass([
  RefSelector("eLabel")
], AgPickerField.prototype, "eLabel", 2);
__decorateClass([
  RefSelector("eWrapper")
], AgPickerField.prototype, "eWrapper", 2);
__decorateClass([
  RefSelector("eDisplayField")
], AgPickerField.prototype, "eDisplayField", 2);
__decorateClass([
  RefSelector("eIcon")
], AgPickerField.prototype, "eIcon", 2);

// community-modules/core/src/widgets/agList.ts
var _AgList = class _AgList extends Component {
  constructor(cssIdentifier = "default", unFocusable = false) {
    super(
      /* html */
      `<div class="ag-list ag-${cssIdentifier}-list" role="listbox"></div>`
    );
    this.cssIdentifier = cssIdentifier;
    this.unFocusable = unFocusable;
    this.options = [];
    this.itemEls = [];
  }
  init() {
    const eGui = this.getGui();
    this.addManagedListener(eGui, "mouseleave", () => this.clearHighlighted());
    if (this.unFocusable) {
      return;
    }
    this.addManagedListener(eGui, "keydown", this.handleKeyDown.bind(this));
  }
  handleKeyDown(e) {
    const key = e.key;
    switch (key) {
      case KeyCode.ENTER:
        if (!this.highlightedEl) {
          this.setValue(this.getValue());
        } else {
          const pos = this.itemEls.indexOf(this.highlightedEl);
          this.setValueByIndex(pos);
        }
        break;
      case KeyCode.DOWN:
      case KeyCode.UP:
        e.preventDefault();
        this.navigate(key);
        break;
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        e.preventDefault();
        this.navigateToPage(key);
        break;
    }
  }
  navigate(key) {
    const isDown = key === KeyCode.DOWN;
    let itemToHighlight;
    if (!this.highlightedEl) {
      itemToHighlight = this.itemEls[isDown ? 0 : this.itemEls.length - 1];
    } else {
      const currentIdx = this.itemEls.indexOf(this.highlightedEl);
      let nextPos = currentIdx + (isDown ? 1 : -1);
      nextPos = Math.min(Math.max(nextPos, 0), this.itemEls.length - 1);
      itemToHighlight = this.itemEls[nextPos];
    }
    this.highlightItem(itemToHighlight);
  }
  navigateToPage(key) {
    if (!this.highlightedEl || this.itemEls.length === 0) {
      return;
    }
    const currentIdx = this.itemEls.indexOf(this.highlightedEl);
    const rowCount = this.options.length - 1;
    const itemHeight = this.itemEls[0].clientHeight;
    const pageSize = Math.floor(this.getGui().clientHeight / itemHeight);
    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(currentIdx + pageSize, rowCount);
    } else if (key === KeyCode.PAGE_UP) {
      newIndex = Math.max(currentIdx - pageSize, 0);
    }
    if (newIndex === -1) {
      return;
    }
    this.highlightItem(this.itemEls[newIndex]);
  }
  addOptions(listOptions) {
    listOptions.forEach((listOption) => this.addOption(listOption));
    return this;
  }
  addOption(listOption) {
    const { value, text } = listOption;
    const valueToRender = text || value;
    this.options.push({ value, text: valueToRender });
    this.renderOption(value, valueToRender);
    this.updateIndices();
    return this;
  }
  clearOptions() {
    this.options = [];
    this.reset(true);
    this.itemEls.forEach((itemEl) => {
      removeFromParent(itemEl);
    });
    this.itemEls = [];
  }
  updateIndices() {
    const options = this.getGui().querySelectorAll(".ag-list-item");
    options.forEach((option, idx) => {
      setAriaPosInSet(option, idx + 1);
      setAriaSetSize(option, options.length);
    });
  }
  renderOption(value, text) {
    const eDocument = this.gos.getDocument();
    const itemEl = eDocument.createElement("div");
    setAriaRole(itemEl, "option");
    itemEl.classList.add("ag-list-item", `ag-${this.cssIdentifier}-list-item`);
    const span = eDocument.createElement("span");
    itemEl.appendChild(span);
    span.textContent = text;
    if (!this.unFocusable) {
      itemEl.tabIndex = -1;
    }
    this.itemEls.push(itemEl);
    this.addManagedListener(itemEl, "mousemove", () => this.highlightItem(itemEl));
    this.addManagedListener(itemEl, "mousedown", (e) => {
      e.preventDefault();
      this.setValue(value);
    });
    this.createManagedBean(new TooltipFeature({
      getTooltipValue: () => text,
      getGui: () => itemEl,
      getLocation: () => "UNKNOWN",
      // only show tooltips for items where the text cannot be fully displayed
      shouldDisplayTooltip: () => span.scrollWidth > span.clientWidth
    }));
    this.getGui().appendChild(itemEl);
  }
  setValue(value, silent) {
    if (this.value === value) {
      this.fireItemSelected();
      return this;
    }
    if (value == null) {
      this.reset(silent);
      return this;
    }
    const idx = this.options.findIndex((option) => option.value === value);
    if (idx !== -1) {
      const option = this.options[idx];
      this.value = option.value;
      this.displayValue = option.text;
      this.highlightItem(this.itemEls[idx]);
      if (!silent) {
        this.fireChangeEvent();
      }
    }
    return this;
  }
  setValueByIndex(idx) {
    return this.setValue(this.options[idx].value);
  }
  getValue() {
    return this.value;
  }
  getDisplayValue() {
    return this.displayValue;
  }
  refreshHighlighted() {
    this.clearHighlighted();
    const idx = this.options.findIndex((option) => option.value === this.value);
    if (idx !== -1) {
      this.highlightItem(this.itemEls[idx]);
    }
  }
  reset(silent) {
    this.value = null;
    this.displayValue = null;
    this.clearHighlighted();
    if (!silent) {
      this.fireChangeEvent();
    }
  }
  highlightItem(el) {
    if (!isVisible(el)) {
      return;
    }
    this.clearHighlighted();
    this.highlightedEl = el;
    this.highlightedEl.classList.add(_AgList.ACTIVE_CLASS);
    setAriaSelected(this.highlightedEl, true);
    const eGui = this.getGui();
    const { scrollTop, clientHeight } = eGui;
    const { offsetTop, offsetHeight } = el;
    if (offsetTop + offsetHeight > scrollTop + clientHeight || offsetTop < scrollTop) {
      this.highlightedEl.scrollIntoView({ block: "nearest" });
    }
    if (!this.unFocusable) {
      this.highlightedEl.focus();
    }
  }
  clearHighlighted() {
    if (!this.highlightedEl || !isVisible(this.highlightedEl)) {
      return;
    }
    this.highlightedEl.classList.remove(_AgList.ACTIVE_CLASS);
    setAriaSelected(this.highlightedEl, false);
    this.highlightedEl = null;
  }
  fireChangeEvent() {
    this.dispatchEvent({ type: Events.EVENT_FIELD_VALUE_CHANGED });
    this.fireItemSelected();
  }
  fireItemSelected() {
    this.dispatchEvent({ type: _AgList.EVENT_ITEM_SELECTED });
  }
};
_AgList.EVENT_ITEM_SELECTED = "selectedItem";
_AgList.ACTIVE_CLASS = "ag-active-item";
__decorateClass([
  PostConstruct
], _AgList.prototype, "init", 1);
var AgList = _AgList;

// community-modules/core/src/widgets/agSelect.ts
var _AgSelect = class _AgSelect extends AgPickerField {
  constructor(config) {
    super(__spreadValues({
      pickerAriaLabelKey: "ariaLabelSelectField",
      pickerAriaLabelValue: "Select Field",
      pickerType: "ag-list",
      className: "ag-select",
      pickerIcon: "smallDown",
      ariaRole: "combobox"
    }, config));
  }
  postConstruct() {
    super.postConstruct();
    this.createListComponent();
    this.eWrapper.tabIndex = this.gos.get("tabIndex");
    const { options, value, placeholder } = this.config;
    if (options != null) {
      this.addOptions(options);
    }
    if (value != null) {
      this.setValue(value, true);
    }
    if (placeholder && value == null) {
      this.eDisplayField.textContent = placeholder;
    }
    this.addManagedListener(this.eWrapper, "focusout", this.onWrapperFocusOut.bind(this));
  }
  onWrapperFocusOut(e) {
    if (!this.eWrapper.contains(e.relatedTarget)) {
      this.hidePicker();
    }
  }
  createListComponent() {
    this.listComponent = this.createBean(new AgList("select", true));
    this.listComponent.setParentComponent(this);
    const eListAriaEl = this.listComponent.getAriaElement();
    const listId = `ag-select-list-${this.listComponent.getCompId()}`;
    eListAriaEl.setAttribute("id", listId);
    setAriaControls(this.getAriaElement(), eListAriaEl);
    this.listComponent.addManagedListener(
      this.listComponent,
      AgList.EVENT_ITEM_SELECTED,
      () => {
        this.hidePicker();
        this.dispatchEvent({ type: _AgSelect.EVENT_ITEM_SELECTED });
      }
    );
    this.listComponent.addManagedListener(
      this.listComponent,
      Events.EVENT_FIELD_VALUE_CHANGED,
      () => {
        if (!this.listComponent) {
          return;
        }
        this.setValue(this.listComponent.getValue(), false, true);
        this.hidePicker();
      }
    );
  }
  createPickerComponent() {
    return this.listComponent;
  }
  onKeyDown(e) {
    var _a;
    const { key } = e;
    if (key === KeyCode.TAB) {
      this.hidePicker();
    }
    switch (key) {
      case KeyCode.ENTER:
      case KeyCode.UP:
      case KeyCode.DOWN:
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        e.preventDefault();
        if (this.isPickerDisplayed) {
          (_a = this.listComponent) == null ? void 0 : _a.handleKeyDown(e);
        } else {
          super.onKeyDown(e);
        }
        break;
      case KeyCode.ESCAPE:
        super.onKeyDown(e);
        break;
    }
  }
  showPicker() {
    if (!this.listComponent) {
      return;
    }
    super.showPicker();
    this.listComponent.refreshHighlighted();
  }
  addOptions(options) {
    options.forEach((option) => this.addOption(option));
    return this;
  }
  addOption(option) {
    this.listComponent.addOption(option);
    return this;
  }
  clearOptions() {
    var _a;
    (_a = this.listComponent) == null ? void 0 : _a.clearOptions();
    return this;
  }
  setValue(value, silent, fromPicker) {
    if (this.value === value || !this.listComponent) {
      return this;
    }
    if (!fromPicker) {
      this.listComponent.setValue(value, true);
    }
    const newValue = this.listComponent.getValue();
    if (newValue === this.getValue()) {
      return this;
    }
    let displayValue = this.listComponent.getDisplayValue();
    if (displayValue == null && this.config.placeholder) {
      displayValue = this.config.placeholder;
    }
    this.eDisplayField.textContent = displayValue;
    this.setTooltip({
      newTooltipText: displayValue != null ? displayValue : null,
      shouldDisplayTooltip: () => this.eDisplayField.scrollWidth > this.eDisplayField.clientWidth
    });
    return super.setValue(value, silent);
  }
  destroy() {
    if (this.listComponent) {
      this.destroyBean(this.listComponent);
      this.listComponent = void 0;
    }
    super.destroy();
  }
};
_AgSelect.EVENT_ITEM_SELECTED = "selectedItem";
var AgSelect = _AgSelect;

// community-modules/core/src/widgets/agAbstractInputField.ts
var AgAbstractInputField = class extends AgAbstractField {
  constructor(config, className, inputType = "text", displayFieldTag = "input") {
    super(
      config,
      /* html */
      `
            <div role="presentation">
                <div ref="eLabel" class="ag-input-field-label"></div>
                <div ref="eWrapper" class="ag-wrapper ag-input-wrapper" role="presentation">
                    <${displayFieldTag} ref="eInput" class="ag-input-field-input"></${displayFieldTag}>
                </div>
            </div>`,
      className
    );
    this.inputType = inputType;
    this.displayFieldTag = displayFieldTag;
  }
  postConstruct() {
    super.postConstruct();
    this.setInputType();
    this.eLabel.classList.add(`${this.className}-label`);
    this.eWrapper.classList.add(`${this.className}-input-wrapper`);
    this.eInput.classList.add(`${this.className}-input`);
    this.addCssClass("ag-input-field");
    this.eInput.id = this.eInput.id || `ag-${this.getCompId()}-input`;
    const { inputName, inputWidth } = this.config;
    if (inputName != null) {
      this.setInputName(inputName);
    }
    if (inputWidth != null) {
      this.setInputWidth(inputWidth);
    }
    this.addInputListeners();
    this.activateTabIndex([this.eInput]);
  }
  addInputListeners() {
    this.addManagedListener(this.eInput, "input", (e) => this.setValue(e.target.value));
  }
  setInputType() {
    if (this.displayFieldTag === "input") {
      this.eInput.setAttribute("type", this.inputType);
    }
  }
  getInputElement() {
    return this.eInput;
  }
  setInputWidth(width) {
    setElementWidth(this.eWrapper, width);
    return this;
  }
  setInputName(name) {
    this.getInputElement().setAttribute("name", name);
    return this;
  }
  getFocusableElement() {
    return this.eInput;
  }
  setMaxLength(length) {
    const eInput = this.eInput;
    eInput.maxLength = length;
    return this;
  }
  setInputPlaceholder(placeholder) {
    addOrRemoveAttribute(this.eInput, "placeholder", placeholder);
    return this;
  }
  setInputAriaLabel(label) {
    setAriaLabel(this.eInput, label);
    this.refreshAriaLabelledBy();
    return this;
  }
  setDisabled(disabled) {
    setDisabled(this.eInput, disabled);
    return super.setDisabled(disabled);
  }
  setAutoComplete(value) {
    if (value === true) {
      addOrRemoveAttribute(this.eInput, "autocomplete", null);
    } else {
      const autoCompleteValue = typeof value === "string" ? value : "off";
      addOrRemoveAttribute(this.eInput, "autocomplete", autoCompleteValue);
    }
    return this;
  }
};
__decorateClass([
  RefSelector("eLabel")
], AgAbstractInputField.prototype, "eLabel", 2);
__decorateClass([
  RefSelector("eWrapper")
], AgAbstractInputField.prototype, "eWrapper", 2);
__decorateClass([
  RefSelector("eInput")
], AgAbstractInputField.prototype, "eInput", 2);

// community-modules/core/src/widgets/agCheckbox.ts
var AgCheckbox = class extends AgAbstractInputField {
  constructor(config, className = "ag-checkbox", inputType = "checkbox") {
    super(config, className, inputType);
    this.labelAlignment = "right";
    this.selected = false;
    this.readOnly = false;
    this.passive = false;
  }
  postConstruct() {
    super.postConstruct();
    const { readOnly, passive } = this.config;
    if (typeof readOnly === "boolean")
      this.setReadOnly(readOnly);
    if (typeof passive === "boolean")
      this.setPassive(passive);
  }
  addInputListeners() {
    this.addManagedListener(this.eInput, "click", this.onCheckboxClick.bind(this));
    this.addManagedListener(this.eLabel, "click", this.toggle.bind(this));
  }
  getNextValue() {
    return this.selected === void 0 ? true : !this.selected;
  }
  setPassive(passive) {
    this.passive = passive;
  }
  isReadOnly() {
    return this.readOnly;
  }
  setReadOnly(readOnly) {
    this.eWrapper.classList.toggle("ag-disabled", readOnly);
    this.eInput.disabled = readOnly;
    this.readOnly = readOnly;
  }
  setDisabled(disabled) {
    this.eWrapper.classList.toggle("ag-disabled", disabled);
    return super.setDisabled(disabled);
  }
  toggle() {
    if (this.eInput.disabled) {
      return;
    }
    const previousValue = this.isSelected();
    const nextValue = this.getNextValue();
    if (this.passive) {
      this.dispatchChange(nextValue, previousValue);
    } else {
      this.setValue(nextValue);
    }
  }
  getValue() {
    return this.isSelected();
  }
  setValue(value, silent) {
    this.refreshSelectedClass(value);
    this.setSelected(value, silent);
    return this;
  }
  setName(name) {
    const input = this.getInputElement();
    input.name = name;
    return this;
  }
  isSelected() {
    return this.selected;
  }
  setSelected(selected, silent) {
    if (this.isSelected() === selected) {
      return;
    }
    this.previousValue = this.isSelected();
    selected = this.selected = typeof selected === "boolean" ? selected : void 0;
    this.eInput.checked = selected;
    this.eInput.indeterminate = selected === void 0;
    if (!silent) {
      this.dispatchChange(this.selected, this.previousValue);
    }
  }
  dispatchChange(selected, previousValue, event) {
    this.dispatchEvent({ type: Events.EVENT_FIELD_VALUE_CHANGED, selected, previousValue, event });
    const input = this.getInputElement();
    const checkboxChangedEvent = {
      type: Events.EVENT_CHECKBOX_CHANGED,
      id: input.id,
      name: input.name,
      selected,
      previousValue
    };
    this.eventService.dispatchEvent(checkboxChangedEvent);
  }
  onCheckboxClick(e) {
    if (this.passive || this.eInput.disabled) {
      return;
    }
    const previousValue = this.isSelected();
    const selected = this.selected = e.target.checked;
    this.refreshSelectedClass(selected);
    this.dispatchChange(selected, previousValue, e);
  }
  refreshSelectedClass(value) {
    this.eWrapper.classList.toggle("ag-checked", value === true);
    this.eWrapper.classList.toggle("ag-indeterminate", value == null);
  }
};

// community-modules/core/src/widgets/agRadioButton.ts
var AgRadioButton = class extends AgCheckbox {
  constructor(config) {
    super(config, "ag-radio-button", "radio");
  }
  isSelected() {
    return this.eInput.checked;
  }
  toggle() {
    if (this.eInput.disabled) {
      return;
    }
    if (!this.isSelected()) {
      this.setValue(true);
    }
  }
  addInputListeners() {
    super.addInputListeners();
    this.addManagedListener(this.eventService, Events.EVENT_CHECKBOX_CHANGED, this.onChange.bind(this));
  }
  /**
   * This ensures that if another radio button in the same named group is selected, we deselect this radio button.
   * By default the browser does this for you, but we are managing classes ourselves in order to ensure input
   * elements are styled correctly in IE11, and the DOM 'changed' event is only fired when a button is selected,
   * not deselected, so we need to use our own event.
   */
  onChange(event) {
    if (event.selected && event.name && this.eInput.name && this.eInput.name === event.name && event.id && this.eInput.id !== event.id) {
      this.setValue(false, true);
    }
  }
};

// community-modules/core/src/filter/provided/simpleFilter.ts
var SimpleFilterModelFormatter = class {
  constructor(localeService, optionsFactory, valueFormatter) {
    this.localeService = localeService;
    this.optionsFactory = optionsFactory;
    this.valueFormatter = valueFormatter;
  }
  // used by:
  // 1) NumberFloatingFilter & TextFloatingFilter: Always, for both when editable and read only.
  // 2) DateFloatingFilter: Only when read only (as we show text rather than a date picker when read only)
  getModelAsString(model) {
    if (!model) {
      return null;
    }
    const isCombined = model.operator != null;
    const translate = this.localeService.getLocaleTextFunc();
    if (isCombined) {
      const combinedModel = model;
      let { conditions } = combinedModel;
      if (!conditions) {
        const { condition1, condition2 } = combinedModel;
        conditions = [condition1, condition2];
      }
      const customOptions = conditions.map((condition) => this.getModelAsString(condition));
      const joinOperatorTranslateKey = combinedModel.operator === "AND" ? "andCondition" : "orCondition";
      return customOptions.join(` ${translate(joinOperatorTranslateKey, FILTER_LOCALE_TEXT[joinOperatorTranslateKey])} `);
    } else if (model.type === SimpleFilter.BLANK || model.type === SimpleFilter.NOT_BLANK) {
      return translate(model.type, model.type);
    } else {
      const condition = model;
      const customOption = this.optionsFactory.getCustomOption(condition.type);
      const { displayKey, displayName, numberOfInputs } = customOption || {};
      if (displayKey && displayName && numberOfInputs === 0) {
        translate(displayKey, displayName);
        return displayName;
      }
      return this.conditionToString(condition, customOption);
    }
  }
  updateParams(params) {
    this.optionsFactory = params.optionsFactory;
  }
  formatValue(value) {
    var _a;
    return this.valueFormatter ? (_a = this.valueFormatter(value != null ? value : null)) != null ? _a : "" : String(value);
  }
};
var _SimpleFilter = class _SimpleFilter extends ProvidedFilter {
  constructor() {
    super(...arguments);
    this.eTypes = [];
    this.eJoinOperatorPanels = [];
    this.eJoinOperatorsAnd = [];
    this.eJoinOperatorsOr = [];
    this.eConditionBodies = [];
    this.listener = () => this.onUiChanged();
    this.lastUiCompletePosition = null;
    this.joinOperatorId = 0;
  }
  getNumberOfInputs(type) {
    const customOpts = this.optionsFactory.getCustomOption(type);
    if (customOpts) {
      const { numberOfInputs } = customOpts;
      return numberOfInputs != null ? numberOfInputs : 1;
    }
    const zeroInputTypes = [
      _SimpleFilter.EMPTY,
      _SimpleFilter.NOT_BLANK,
      _SimpleFilter.BLANK
    ];
    if (type && zeroInputTypes.indexOf(type) >= 0) {
      return 0;
    } else if (type === _SimpleFilter.IN_RANGE) {
      return 2;
    }
    return 1;
  }
  // floating filter calls this when user applies filter from floating filter
  onFloatingFilterChanged(type, value) {
    this.setTypeFromFloatingFilter(type);
    this.setValueFromFloatingFilter(value);
    this.onUiChanged(true);
  }
  setTypeFromFloatingFilter(type) {
    this.eTypes.forEach((eType, position) => {
      if (position === 0) {
        eType.setValue(type, true);
      } else {
        eType.setValue(this.optionsFactory.getDefaultOption(), true);
      }
    });
  }
  getModelFromUi() {
    const conditions = this.getUiCompleteConditions();
    if (conditions.length === 0) {
      return null;
    }
    if (this.maxNumConditions > 1 && conditions.length > 1) {
      return {
        filterType: this.getFilterType(),
        operator: this.getJoinOperator(),
        condition1: conditions[0],
        condition2: conditions[1],
        conditions
      };
    }
    return conditions[0];
  }
  getConditionTypes() {
    return this.eTypes.map((eType) => eType.getValue());
  }
  getConditionType(position) {
    return this.eTypes[position].getValue();
  }
  getJoinOperator() {
    if (this.eJoinOperatorsOr.length === 0) {
      return this.defaultJoinOperator;
    }
    return this.eJoinOperatorsOr[0].getValue() === true ? "OR" : "AND";
  }
  areModelsEqual(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a && b || a && !b) {
      return false;
    }
    const aIsSimple = !a.operator;
    const bIsSimple = !b.operator;
    const oneSimpleOneCombined = !aIsSimple && bIsSimple || aIsSimple && !bIsSimple;
    if (oneSimpleOneCombined) {
      return false;
    }
    let res;
    if (aIsSimple) {
      const aSimple = a;
      const bSimple = b;
      res = this.areSimpleModelsEqual(aSimple, bSimple);
    } else {
      const aCombined = a;
      const bCombined = b;
      res = aCombined.operator === bCombined.operator && areEqual(aCombined.conditions, bCombined.conditions, (aModel, bModel) => this.areSimpleModelsEqual(aModel, bModel));
    }
    return res;
  }
  shouldRefresh(newParams) {
    var _a, _b, _c;
    const model = this.getModel();
    const conditions = model ? (_a = model.conditions) != null ? _a : [model] : null;
    const newOptionsList = (_c = (_b = newParams.filterOptions) == null ? void 0 : _b.map(
      (option) => typeof option === "string" ? option : option.displayKey
    )) != null ? _c : this.getDefaultFilterOptions();
    const allConditionsExistInNewOptionsList = !conditions || conditions.every((condition) => newOptionsList.find((option) => option === condition.type) !== void 0);
    if (!allConditionsExistInNewOptionsList) {
      return false;
    }
    if (typeof newParams.maxNumConditions === "number" && conditions && conditions.length > newParams.maxNumConditions) {
      return false;
    }
    return true;
  }
  refresh(newParams) {
    if (!this.shouldRefresh(newParams)) {
      return false;
    }
    const parentRefreshed = super.refresh(newParams);
    if (!parentRefreshed) {
      return false;
    }
    this.setParams(newParams);
    this.removeConditionsAndOperators(0);
    this.createOption();
    this.setModel(this.getModel());
    return true;
  }
  setModelIntoUi(model) {
    const isCombined = model.operator;
    if (isCombined) {
      let combinedModel = model;
      if (!combinedModel.conditions) {
        combinedModel.conditions = [
          combinedModel.condition1,
          combinedModel.condition2
        ];
      }
      const numConditions = this.validateAndUpdateConditions(combinedModel.conditions);
      const numPrevConditions = this.getNumConditions();
      if (numConditions < numPrevConditions) {
        this.removeConditionsAndOperators(numConditions);
      } else if (numConditions > numPrevConditions) {
        for (let i = numPrevConditions; i < numConditions; i++) {
          this.createJoinOperatorPanel();
          this.createOption();
        }
      }
      const orChecked = combinedModel.operator === "OR";
      this.eJoinOperatorsAnd.forEach((eJoinOperatorAnd) => eJoinOperatorAnd.setValue(!orChecked, true));
      this.eJoinOperatorsOr.forEach((eJoinOperatorOr) => eJoinOperatorOr.setValue(orChecked, true));
      combinedModel.conditions.forEach((condition, position) => {
        this.eTypes[position].setValue(condition.type, true);
        this.setConditionIntoUi(condition, position);
      });
    } else {
      const simpleModel = model;
      if (this.getNumConditions() > 1) {
        this.removeConditionsAndOperators(1);
      }
      this.eTypes[0].setValue(simpleModel.type, true);
      this.setConditionIntoUi(simpleModel, 0);
    }
    this.lastUiCompletePosition = this.getNumConditions() - 1;
    this.createMissingConditionsAndOperators();
    this.onUiChanged();
    return AgPromise.resolve();
  }
  validateAndUpdateConditions(conditions) {
    let numConditions = conditions.length;
    if (numConditions > this.maxNumConditions) {
      conditions.splice(this.maxNumConditions);
      warnOnce('Filter Model contains more conditions than "filterParams.maxNumConditions". Additional conditions have been ignored.');
      numConditions = this.maxNumConditions;
    }
    return numConditions;
  }
  doesFilterPass(params) {
    var _a;
    const model = this.getModel();
    if (model == null) {
      return true;
    }
    const { operator } = model;
    const models = [];
    if (operator) {
      const combinedModel = model;
      models.push(...(_a = combinedModel.conditions) != null ? _a : []);
    } else {
      models.push(model);
    }
    const combineFunction = operator && operator === "OR" ? "some" : "every";
    return models[combineFunction]((m) => this.individualConditionPasses(params, m));
  }
  setParams(params) {
    super.setParams(params);
    this.setNumConditions(params);
    this.defaultJoinOperator = this.getDefaultJoinOperator(params.defaultJoinOperator);
    this.filterPlaceholder = params.filterPlaceholder;
    this.optionsFactory = new OptionsFactory();
    this.optionsFactory.init(params, this.getDefaultFilterOptions());
    this.createFilterListOptions();
    this.createOption();
    this.createMissingConditionsAndOperators();
    if (this.isReadOnly()) {
      this.eFilterBody.setAttribute("tabindex", "-1");
    }
  }
  setNumConditions(params) {
    var _a, _b;
    if (params.suppressAndOrCondition != null) {
      warnOnce('Since v29.2 "filterParams.suppressAndOrCondition" is deprecated. Use "filterParams.maxNumConditions = 1" instead.');
    }
    if (params.alwaysShowBothConditions != null) {
      warnOnce('Since v29.2 "filterParams.alwaysShowBothConditions" is deprecated. Use "filterParams.numAlwaysVisibleConditions = 2" instead.');
    }
    this.maxNumConditions = (_a = params.maxNumConditions) != null ? _a : params.suppressAndOrCondition ? 1 : 2;
    if (this.maxNumConditions < 1) {
      warnOnce('"filterParams.maxNumConditions" must be greater than or equal to zero.');
      this.maxNumConditions = 1;
    }
    this.numAlwaysVisibleConditions = (_b = params.numAlwaysVisibleConditions) != null ? _b : params.alwaysShowBothConditions ? 2 : 1;
    if (this.numAlwaysVisibleConditions < 1) {
      warnOnce('"filterParams.numAlwaysVisibleConditions" must be greater than or equal to zero.');
      this.numAlwaysVisibleConditions = 1;
    }
    if (this.numAlwaysVisibleConditions > this.maxNumConditions) {
      warnOnce('"filterParams.numAlwaysVisibleConditions" cannot be greater than "filterParams.maxNumConditions".');
      this.numAlwaysVisibleConditions = this.maxNumConditions;
    }
  }
  createOption() {
    const eType = this.createManagedBean(new AgSelect());
    this.eTypes.push(eType);
    eType.addCssClass("ag-filter-select");
    this.eFilterBody.appendChild(eType.getGui());
    const eConditionBody = this.createValueElement();
    this.eConditionBodies.push(eConditionBody);
    this.eFilterBody.appendChild(eConditionBody);
    this.putOptionsIntoDropdown(eType);
    this.resetType(eType);
    const position = this.getNumConditions() - 1;
    this.forEachPositionInput(position, (element) => this.resetInput(element));
    this.addChangedListeners(eType, position);
  }
  createJoinOperatorPanel() {
    const eJoinOperatorPanel = document.createElement("div");
    this.eJoinOperatorPanels.push(eJoinOperatorPanel);
    eJoinOperatorPanel.classList.add("ag-filter-condition");
    const eJoinOperatorAnd = this.createJoinOperator(this.eJoinOperatorsAnd, eJoinOperatorPanel, "and");
    const eJoinOperatorOr = this.createJoinOperator(this.eJoinOperatorsOr, eJoinOperatorPanel, "or");
    this.eFilterBody.appendChild(eJoinOperatorPanel);
    const index = this.eJoinOperatorPanels.length - 1;
    const uniqueGroupId = this.joinOperatorId++;
    this.resetJoinOperatorAnd(eJoinOperatorAnd, index, uniqueGroupId);
    this.resetJoinOperatorOr(eJoinOperatorOr, index, uniqueGroupId);
    if (!this.isReadOnly()) {
      eJoinOperatorAnd.onValueChange(this.listener);
      eJoinOperatorOr.onValueChange(this.listener);
    }
  }
  createJoinOperator(eJoinOperators, eJoinOperatorPanel, andOr) {
    const eJoinOperator = this.createManagedBean(new AgRadioButton());
    eJoinOperators.push(eJoinOperator);
    eJoinOperator.addCssClass("ag-filter-condition-operator");
    eJoinOperator.addCssClass(`ag-filter-condition-operator-${andOr}`);
    eJoinOperatorPanel.appendChild(eJoinOperator.getGui());
    return eJoinOperator;
  }
  getDefaultJoinOperator(defaultJoinOperator) {
    return defaultJoinOperator === "AND" || defaultJoinOperator === "OR" ? defaultJoinOperator : "AND";
  }
  createFilterListOptions() {
    const filterOptions = this.optionsFactory.getFilterOptions();
    this.filterListOptions = filterOptions.map(
      (option) => typeof option === "string" ? this.createBoilerplateListOption(option) : this.createCustomListOption(option)
    );
  }
  putOptionsIntoDropdown(eType) {
    this.filterListOptions.forEach((listOption) => {
      eType.addOption(listOption);
    });
    eType.setDisabled(this.filterListOptions.length <= 1);
  }
  createBoilerplateListOption(option) {
    return { value: option, text: this.translate(option) };
  }
  createCustomListOption(option) {
    const { displayKey } = option;
    const customOption = this.optionsFactory.getCustomOption(option.displayKey);
    return {
      value: displayKey,
      text: customOption ? this.localeService.getLocaleTextFunc()(customOption.displayKey, customOption.displayName) : this.translate(displayKey)
    };
  }
  /**
   * @deprecated As of v29.2 filters can have more than two conditions. Check `colDef.filterParams.maxNumConditions` instead.
   */
  isAllowTwoConditions() {
    return this.maxNumConditions >= 2;
  }
  createBodyTemplate() {
    return "";
  }
  getCssIdentifier() {
    return "simple-filter";
  }
  updateUiVisibility() {
    const joinOperator = this.getJoinOperator();
    this.updateNumConditions();
    this.updateConditionStatusesAndValues(this.lastUiCompletePosition, joinOperator);
  }
  updateNumConditions() {
    var _a;
    let lastUiCompletePosition = -1;
    let areAllConditionsUiComplete = true;
    for (let position = 0; position < this.getNumConditions(); position++) {
      if (this.isConditionUiComplete(position)) {
        lastUiCompletePosition = position;
      } else {
        areAllConditionsUiComplete = false;
      }
    }
    if (this.shouldAddNewConditionAtEnd(areAllConditionsUiComplete)) {
      this.createJoinOperatorPanel();
      this.createOption();
    } else {
      const activePosition = (_a = this.lastUiCompletePosition) != null ? _a : this.getNumConditions() - 2;
      if (lastUiCompletePosition < activePosition) {
        this.removeConditionsAndOperators(activePosition + 1);
        const removeStartPosition = lastUiCompletePosition + 1;
        const numConditionsToRemove = activePosition - removeStartPosition;
        if (numConditionsToRemove > 0) {
          this.removeConditionsAndOperators(removeStartPosition, numConditionsToRemove);
        }
        this.createMissingConditionsAndOperators();
      }
    }
    this.lastUiCompletePosition = lastUiCompletePosition;
  }
  updateConditionStatusesAndValues(lastUiCompletePosition, joinOperator) {
    this.eTypes.forEach((eType, position) => {
      const disabled = this.isConditionDisabled(position, lastUiCompletePosition);
      eType.setDisabled(disabled || this.filterListOptions.length <= 1);
      if (position === 1) {
        setDisabled(this.eJoinOperatorPanels[0], disabled);
        this.eJoinOperatorsAnd[0].setDisabled(disabled);
        this.eJoinOperatorsOr[0].setDisabled(disabled);
      }
    });
    this.eConditionBodies.forEach((element, index) => {
      setDisplayed(element, this.isConditionBodyVisible(index));
    });
    const orChecked = (joinOperator != null ? joinOperator : this.getJoinOperator()) === "OR";
    this.eJoinOperatorsAnd.forEach((eJoinOperatorAnd, index) => {
      eJoinOperatorAnd.setValue(!orChecked, true);
    });
    this.eJoinOperatorsOr.forEach((eJoinOperatorOr, index) => {
      eJoinOperatorOr.setValue(orChecked, true);
    });
    this.forEachInput((element, index, position, numberOfInputs) => {
      this.setElementDisplayed(element, index < numberOfInputs);
      this.setElementDisabled(element, this.isConditionDisabled(position, lastUiCompletePosition));
    });
    this.resetPlaceholder();
  }
  shouldAddNewConditionAtEnd(areAllConditionsUiComplete) {
    return areAllConditionsUiComplete && this.getNumConditions() < this.maxNumConditions && !this.isReadOnly();
  }
  removeConditionsAndOperators(startPosition, deleteCount) {
    if (startPosition >= this.getNumConditions()) {
      return;
    }
    this.removeComponents(this.eTypes, startPosition, deleteCount);
    this.removeElements(this.eConditionBodies, startPosition, deleteCount);
    this.removeValueElements(startPosition, deleteCount);
    const joinOperatorIndex = Math.max(startPosition - 1, 0);
    this.removeElements(this.eJoinOperatorPanels, joinOperatorIndex, deleteCount);
    this.removeComponents(this.eJoinOperatorsAnd, joinOperatorIndex, deleteCount);
    this.removeComponents(this.eJoinOperatorsOr, joinOperatorIndex, deleteCount);
  }
  removeElements(elements, startPosition, deleteCount) {
    const removedElements = this.removeItems(elements, startPosition, deleteCount);
    removedElements.forEach((element) => removeFromParent(element));
  }
  removeComponents(components, startPosition, deleteCount) {
    const removedComponents = this.removeItems(components, startPosition, deleteCount);
    removedComponents.forEach((comp) => {
      removeFromParent(comp.getGui());
      this.destroyBean(comp);
    });
  }
  removeItems(items, startPosition, deleteCount) {
    return deleteCount == null ? items.splice(startPosition) : items.splice(startPosition, deleteCount);
  }
  afterGuiAttached(params) {
    super.afterGuiAttached(params);
    this.resetPlaceholder();
    if (!(params == null ? void 0 : params.suppressFocus)) {
      if (this.isReadOnly()) {
        this.eFilterBody.focus();
      } else {
        const firstInput = this.getInputs(0)[0];
        if (!firstInput) {
          return;
        }
        if (firstInput instanceof AgAbstractInputField) {
          firstInput.getInputElement().focus();
        }
      }
    }
  }
  afterGuiDetached() {
    super.afterGuiDetached();
    const appliedModel = this.getModel();
    this.resetUiToActiveModel(appliedModel);
    let lastUiCompletePosition = -1;
    let updatedLastUiCompletePosition = -1;
    let conditionsRemoved = false;
    const joinOperator = this.getJoinOperator();
    for (let position = this.getNumConditions() - 1; position >= 0; position--) {
      if (this.isConditionUiComplete(position)) {
        if (lastUiCompletePosition === -1) {
          lastUiCompletePosition = position;
          updatedLastUiCompletePosition = position;
        }
      } else {
        const shouldRemovePositionAtEnd = position >= this.numAlwaysVisibleConditions && !this.isConditionUiComplete(position - 1);
        const positionBeforeLastUiCompletePosition = position < lastUiCompletePosition;
        if (shouldRemovePositionAtEnd || positionBeforeLastUiCompletePosition) {
          this.removeConditionsAndOperators(position, 1);
          conditionsRemoved = true;
          if (positionBeforeLastUiCompletePosition) {
            updatedLastUiCompletePosition--;
          }
        }
      }
    }
    let shouldUpdateConditionStatusesAndValues = false;
    if (this.getNumConditions() < this.numAlwaysVisibleConditions) {
      this.createMissingConditionsAndOperators();
      shouldUpdateConditionStatusesAndValues = true;
    }
    if (this.shouldAddNewConditionAtEnd(updatedLastUiCompletePosition === this.getNumConditions() - 1)) {
      this.createJoinOperatorPanel();
      this.createOption();
      shouldUpdateConditionStatusesAndValues = true;
    }
    if (shouldUpdateConditionStatusesAndValues) {
      this.updateConditionStatusesAndValues(updatedLastUiCompletePosition, joinOperator);
    }
    if (conditionsRemoved) {
      this.updateJoinOperatorsDisabled();
    }
    this.lastUiCompletePosition = updatedLastUiCompletePosition;
  }
  getPlaceholderText(defaultPlaceholder, position) {
    let placeholder = this.translate(defaultPlaceholder);
    if (isFunction(this.filterPlaceholder)) {
      const filterPlaceholderFn = this.filterPlaceholder;
      const filterOptionKey = this.eTypes[position].getValue();
      const filterOption = this.translate(filterOptionKey);
      placeholder = filterPlaceholderFn({
        filterOptionKey,
        filterOption,
        placeholder
      });
    } else if (typeof this.filterPlaceholder === "string") {
      placeholder = this.filterPlaceholder;
    }
    return placeholder;
  }
  // allow sub-classes to reset HTML placeholders after UI update.
  resetPlaceholder() {
    const globalTranslate = this.localeService.getLocaleTextFunc();
    this.forEachInput((element, index, position, numberOfInputs) => {
      if (!(element instanceof AgAbstractInputField)) {
        return;
      }
      const placeholder = index === 0 && numberOfInputs > 1 ? "inRangeStart" : index === 0 ? "filterOoo" : "inRangeEnd";
      const ariaLabel = index === 0 && numberOfInputs > 1 ? globalTranslate("ariaFilterFromValue", "Filter from value") : index === 0 ? globalTranslate("ariaFilterValue", "Filter Value") : globalTranslate("ariaFilterToValue", "Filter to Value");
      element.setInputPlaceholder(this.getPlaceholderText(placeholder, position));
      element.setInputAriaLabel(ariaLabel);
    });
  }
  setElementValue(element, value, fromFloatingFilter) {
    if (element instanceof AgAbstractInputField) {
      element.setValue(value != null ? String(value) : null, true);
    }
  }
  setElementDisplayed(element, displayed) {
    if (element instanceof Component) {
      setDisplayed(element.getGui(), displayed);
    }
  }
  setElementDisabled(element, disabled) {
    if (element instanceof Component) {
      setDisabled(element.getGui(), disabled);
    }
  }
  attachElementOnChange(element, listener) {
    if (element instanceof AgAbstractInputField) {
      element.onValueChange(listener);
    }
  }
  forEachInput(cb) {
    this.getConditionTypes().forEach((type, position) => {
      this.forEachPositionTypeInput(position, type, cb);
    });
  }
  forEachPositionInput(position, cb) {
    const type = this.getConditionType(position);
    this.forEachPositionTypeInput(position, type, cb);
  }
  forEachPositionTypeInput(position, type, cb) {
    const numberOfInputs = this.getNumberOfInputs(type);
    const inputs = this.getInputs(position);
    for (let index = 0; index < inputs.length; index++) {
      const input = inputs[index];
      if (input != null) {
        cb(input, index, position, numberOfInputs);
      }
    }
  }
  isConditionDisabled(position, lastUiCompletePosition) {
    if (this.isReadOnly()) {
      return true;
    }
    if (position === 0) {
      return false;
    }
    return position > lastUiCompletePosition + 1;
  }
  isConditionBodyVisible(position) {
    const type = this.getConditionType(position);
    const numberOfInputs = this.getNumberOfInputs(type);
    return numberOfInputs > 0;
  }
  // returns true if the UI represents a working filter, eg all parts are filled out.
  // eg if text filter and textfield blank then returns false.
  isConditionUiComplete(position) {
    if (position >= this.getNumConditions()) {
      return false;
    }
    const type = this.getConditionType(position);
    if (type === _SimpleFilter.EMPTY) {
      return false;
    }
    if (this.getValues(position).some((v) => v == null)) {
      return false;
    }
    return true;
  }
  getNumConditions() {
    return this.eTypes.length;
  }
  getUiCompleteConditions() {
    const conditions = [];
    for (let position = 0; position < this.getNumConditions(); position++) {
      if (this.isConditionUiComplete(position)) {
        conditions.push(this.createCondition(position));
      }
    }
    return conditions;
  }
  createMissingConditionsAndOperators() {
    if (this.isReadOnly()) {
      return;
    }
    for (let i = this.getNumConditions(); i < this.numAlwaysVisibleConditions; i++) {
      this.createJoinOperatorPanel();
      this.createOption();
    }
  }
  resetUiToDefaults(silent) {
    this.removeConditionsAndOperators(this.isReadOnly() ? 1 : this.numAlwaysVisibleConditions);
    this.eTypes.forEach((eType) => this.resetType(eType));
    this.eJoinOperatorsAnd.forEach((eJoinOperatorAnd, index) => this.resetJoinOperatorAnd(eJoinOperatorAnd, index, this.joinOperatorId + index));
    this.eJoinOperatorsOr.forEach((eJoinOperatorOr, index) => this.resetJoinOperatorOr(eJoinOperatorOr, index, this.joinOperatorId + index));
    this.joinOperatorId++;
    this.forEachInput((element) => this.resetInput(element));
    this.resetPlaceholder();
    this.createMissingConditionsAndOperators();
    this.lastUiCompletePosition = null;
    if (!silent) {
      this.onUiChanged();
    }
    return AgPromise.resolve();
  }
  resetType(eType) {
    const translate = this.localeService.getLocaleTextFunc();
    const filteringLabel = translate("ariaFilteringOperator", "Filtering operator");
    eType.setValue(this.optionsFactory.getDefaultOption(), true).setAriaLabel(filteringLabel).setDisabled(this.isReadOnly() || this.filterListOptions.length <= 1);
  }
  resetJoinOperatorAnd(eJoinOperatorAnd, index, uniqueGroupId) {
    this.resetJoinOperator(eJoinOperatorAnd, index, this.isDefaultOperator("AND"), this.translate("andCondition"), uniqueGroupId);
  }
  resetJoinOperatorOr(eJoinOperatorOr, index, uniqueGroupId) {
    this.resetJoinOperator(eJoinOperatorOr, index, this.isDefaultOperator("OR"), this.translate("orCondition"), uniqueGroupId);
  }
  resetJoinOperator(eJoinOperator, index, value, label, uniqueGroupId) {
    this.updateJoinOperatorDisabled(
      eJoinOperator.setValue(value, true).setName(`ag-simple-filter-and-or-${this.getCompId()}-${uniqueGroupId}`).setLabel(label),
      index
    );
  }
  updateJoinOperatorsDisabled() {
    this.eJoinOperatorsAnd.forEach((eJoinOperator, index) => this.updateJoinOperatorDisabled(eJoinOperator, index));
    this.eJoinOperatorsOr.forEach((eJoinOperator, index) => this.updateJoinOperatorDisabled(eJoinOperator, index));
  }
  updateJoinOperatorDisabled(eJoinOperator, index) {
    eJoinOperator.setDisabled(this.isReadOnly() || index > 0);
  }
  resetInput(element) {
    this.setElementValue(element, null);
    this.setElementDisabled(element, this.isReadOnly());
  }
  // puts model values into the UI
  setConditionIntoUi(model, position) {
    const values2 = this.mapValuesFromModel(model);
    this.forEachInput((element, index, elPosition, _2) => {
      if (elPosition !== position) {
        return;
      }
      this.setElementValue(element, values2[index] != null ? values2[index] : null);
    });
  }
  // after floating filter changes, this sets the 'value' section. this is implemented by the base class
  // (as that's where value is controlled), the 'type' part from the floating filter is dealt with in this class.
  setValueFromFloatingFilter(value) {
    this.forEachInput((element, index, position, _2) => {
      this.setElementValue(element, index === 0 && position === 0 ? value : null, true);
    });
  }
  isDefaultOperator(operator) {
    return operator === this.defaultJoinOperator;
  }
  addChangedListeners(eType, position) {
    if (this.isReadOnly()) {
      return;
    }
    eType.onValueChange(this.listener);
    this.forEachPositionInput(position, (element) => {
      this.attachElementOnChange(element, this.listener);
    });
  }
  /** returns true if the row passes the said condition */
  individualConditionPasses(params, filterModel) {
    const cellValue = this.getCellValue(params.node);
    const values2 = this.mapValuesFromModel(filterModel);
    const customFilterOption = this.optionsFactory.getCustomOption(filterModel.type);
    const customFilterResult = this.evaluateCustomFilter(customFilterOption, values2, cellValue);
    if (customFilterResult != null) {
      return customFilterResult;
    }
    if (cellValue == null) {
      return this.evaluateNullValue(filterModel.type);
    }
    return this.evaluateNonNullValue(values2, cellValue, filterModel, params);
  }
  evaluateCustomFilter(customFilterOption, values2, cellValue) {
    if (customFilterOption == null) {
      return;
    }
    const { predicate } = customFilterOption;
    if (predicate != null && !values2.some((v) => v == null)) {
      return predicate(values2, cellValue);
    }
    return;
  }
  isBlank(cellValue) {
    return cellValue == null || typeof cellValue === "string" && cellValue.trim().length === 0;
  }
  hasInvalidInputs() {
    return false;
  }
};
_SimpleFilter.EMPTY = "empty";
_SimpleFilter.BLANK = "blank";
_SimpleFilter.NOT_BLANK = "notBlank";
_SimpleFilter.EQUALS = "equals";
_SimpleFilter.NOT_EQUAL = "notEqual";
_SimpleFilter.LESS_THAN = "lessThan";
_SimpleFilter.LESS_THAN_OR_EQUAL = "lessThanOrEqual";
_SimpleFilter.GREATER_THAN = "greaterThan";
_SimpleFilter.GREATER_THAN_OR_EQUAL = "greaterThanOrEqual";
_SimpleFilter.IN_RANGE = "inRange";
_SimpleFilter.CONTAINS = "contains";
_SimpleFilter.NOT_CONTAINS = "notContains";
_SimpleFilter.STARTS_WITH = "startsWith";
_SimpleFilter.ENDS_WITH = "endsWith";
var SimpleFilter = _SimpleFilter;

// community-modules/core/src/filter/provided/scalarFilter.ts
var ScalarFilter = class _ScalarFilter extends SimpleFilter {
  setParams(params) {
    super.setParams(params);
    this.scalarFilterParams = params;
  }
  evaluateNullValue(filterType) {
    switch (filterType) {
      case _ScalarFilter.EQUALS:
      case _ScalarFilter.NOT_EQUAL:
        if (this.scalarFilterParams.includeBlanksInEquals) {
          return true;
        }
        break;
      case _ScalarFilter.GREATER_THAN:
      case _ScalarFilter.GREATER_THAN_OR_EQUAL:
        if (this.scalarFilterParams.includeBlanksInGreaterThan) {
          return true;
        }
        break;
      case _ScalarFilter.LESS_THAN:
      case _ScalarFilter.LESS_THAN_OR_EQUAL:
        if (this.scalarFilterParams.includeBlanksInLessThan) {
          return true;
        }
        break;
      case _ScalarFilter.IN_RANGE:
        if (this.scalarFilterParams.includeBlanksInRange) {
          return true;
        }
        break;
      case _ScalarFilter.BLANK:
        return true;
      case _ScalarFilter.NOT_BLANK:
        return false;
    }
    return false;
  }
  evaluateNonNullValue(values2, cellValue, filterModel) {
    const comparator = this.comparator();
    const compareResult = values2[0] != null ? comparator(values2[0], cellValue) : 0;
    switch (filterModel.type) {
      case _ScalarFilter.EQUALS:
        return compareResult === 0;
      case _ScalarFilter.NOT_EQUAL:
        return compareResult !== 0;
      case _ScalarFilter.GREATER_THAN:
        return compareResult > 0;
      case _ScalarFilter.GREATER_THAN_OR_EQUAL:
        return compareResult >= 0;
      case _ScalarFilter.LESS_THAN:
        return compareResult < 0;
      case _ScalarFilter.LESS_THAN_OR_EQUAL:
        return compareResult <= 0;
      case _ScalarFilter.IN_RANGE: {
        const compareToResult = comparator(values2[1], cellValue);
        return this.scalarFilterParams.inRangeInclusive ? compareResult >= 0 && compareToResult <= 0 : compareResult > 0 && compareToResult < 0;
      }
      case _ScalarFilter.BLANK:
        return this.isBlank(cellValue);
      case _ScalarFilter.NOT_BLANK:
        return !this.isBlank(cellValue);
      default:
        console.warn('AG Grid: Unexpected type of filter "' + filterModel.type + '", it looks like the filter was configured with incorrect Filter Options');
        return true;
    }
  }
};

// community-modules/core/src/filter/provided/date/dateFilter.ts
var DEFAULT_MIN_YEAR = 1e3;
var DEFAULT_MAX_YEAR = Infinity;
var DateFilterModelFormatter = class extends SimpleFilterModelFormatter {
  constructor(dateFilterParams, localeService, optionsFactory) {
    super(localeService, optionsFactory);
    this.dateFilterParams = dateFilterParams;
  }
  conditionToString(condition, options) {
    const { type } = condition;
    const { numberOfInputs } = options || {};
    const isRange = type == SimpleFilter.IN_RANGE || numberOfInputs === 2;
    const dateFrom = parseDateTimeFromString(condition.dateFrom);
    const dateTo = parseDateTimeFromString(condition.dateTo);
    const format = this.dateFilterParams.inRangeFloatingFilterDateFormat;
    if (isRange) {
      const formattedFrom = dateFrom !== null ? dateToFormattedString(dateFrom, format) : "null";
      const formattedTo = dateTo !== null ? dateToFormattedString(dateTo, format) : "null";
      return `${formattedFrom}-${formattedTo}`;
    }
    if (dateFrom != null) {
      return dateToFormattedString(dateFrom, format);
    }
    return `${type}`;
  }
  updateParams(params) {
    super.updateParams(params);
    this.dateFilterParams = params.dateFilterParams;
  }
};
var _DateFilter = class _DateFilter extends ScalarFilter {
  constructor() {
    super("dateFilter");
    this.eConditionPanelsFrom = [];
    this.eConditionPanelsTo = [];
    this.dateConditionFromComps = [];
    this.dateConditionToComps = [];
    this.minValidYear = DEFAULT_MIN_YEAR;
    this.maxValidYear = DEFAULT_MAX_YEAR;
    this.minValidDate = null;
    this.maxValidDate = null;
  }
  afterGuiAttached(params) {
    super.afterGuiAttached(params);
    this.dateConditionFromComps[0].afterGuiAttached(params);
  }
  mapValuesFromModel(filterModel) {
    const { dateFrom, dateTo, type } = filterModel || {};
    return [
      dateFrom && parseDateTimeFromString(dateFrom) || null,
      dateTo && parseDateTimeFromString(dateTo) || null
    ].slice(0, this.getNumberOfInputs(type));
  }
  comparator() {
    return this.dateFilterParams.comparator ? this.dateFilterParams.comparator : this.defaultComparator.bind(this);
  }
  defaultComparator(filterDate, cellValue) {
    const cellAsDate = cellValue;
    if (cellValue == null || cellAsDate < filterDate) {
      return -1;
    }
    if (cellAsDate > filterDate) {
      return 1;
    }
    return 0;
  }
  setParams(params) {
    this.dateFilterParams = params;
    super.setParams(params);
    const yearParser = (param, fallback) => {
      if (params[param] != null) {
        if (!isNaN(params[param])) {
          return params[param] == null ? fallback : Number(params[param]);
        } else {
          console.warn(`AG Grid: DateFilter ${param} is not a number`);
        }
      }
      return fallback;
    };
    this.minValidYear = yearParser("minValidYear", DEFAULT_MIN_YEAR);
    this.maxValidYear = yearParser("maxValidYear", DEFAULT_MAX_YEAR);
    if (this.minValidYear > this.maxValidYear) {
      console.warn(`AG Grid: DateFilter minValidYear should be <= maxValidYear`);
    }
    if (params.minValidDate) {
      this.minValidDate = params.minValidDate instanceof Date ? params.minValidDate : parseDateTimeFromString(params.minValidDate);
    } else {
      this.minValidDate = null;
    }
    if (params.maxValidDate) {
      this.maxValidDate = params.maxValidDate instanceof Date ? params.maxValidDate : parseDateTimeFromString(params.maxValidDate);
    } else {
      this.maxValidDate = null;
    }
    if (this.minValidDate && this.maxValidDate && this.minValidDate > this.maxValidDate) {
      console.warn(`AG Grid: DateFilter minValidDate should be <= maxValidDate`);
    }
    this.filterModelFormatter = new DateFilterModelFormatter(this.dateFilterParams, this.localeService, this.optionsFactory);
  }
  createDateCompWrapper(element) {
    const dateCompWrapper = new DateCompWrapper(
      this.getContext(),
      this.userComponentFactory,
      {
        onDateChanged: () => this.onUiChanged(),
        filterParams: this.dateFilterParams
      },
      element
    );
    this.addDestroyFunc(() => dateCompWrapper.destroy());
    return dateCompWrapper;
  }
  setElementValue(element, value) {
    element.setDate(value);
  }
  setElementDisplayed(element, displayed) {
    element.setDisplayed(displayed);
  }
  setElementDisabled(element, disabled) {
    element.setDisabled(disabled);
  }
  getDefaultFilterOptions() {
    return _DateFilter.DEFAULT_FILTER_OPTIONS;
  }
  createValueElement() {
    const eDocument = this.gos.getDocument();
    const eCondition = eDocument.createElement("div");
    eCondition.classList.add("ag-filter-body");
    this.createFromToElement(eCondition, this.eConditionPanelsFrom, this.dateConditionFromComps, "from");
    this.createFromToElement(eCondition, this.eConditionPanelsTo, this.dateConditionToComps, "to");
    return eCondition;
  }
  createFromToElement(eCondition, eConditionPanels, dateConditionComps, fromTo) {
    const eDocument = this.gos.getDocument();
    const eConditionPanel = eDocument.createElement("div");
    eConditionPanel.classList.add(`ag-filter-${fromTo}`);
    eConditionPanel.classList.add(`ag-filter-date-${fromTo}`);
    eConditionPanels.push(eConditionPanel);
    eCondition.appendChild(eConditionPanel);
    dateConditionComps.push(this.createDateCompWrapper(eConditionPanel));
  }
  removeValueElements(startPosition, deleteCount) {
    this.removeDateComps(this.dateConditionFromComps, startPosition, deleteCount);
    this.removeDateComps(this.dateConditionToComps, startPosition, deleteCount);
    this.removeItems(this.eConditionPanelsFrom, startPosition, deleteCount);
    this.removeItems(this.eConditionPanelsTo, startPosition, deleteCount);
  }
  removeDateComps(components, startPosition, deleteCount) {
    const removedComponents = this.removeItems(components, startPosition, deleteCount);
    removedComponents.forEach((comp) => comp.destroy());
  }
  isValidDateValue(value) {
    if (value === null) {
      return false;
    }
    if (this.minValidDate) {
      if (value < this.minValidDate) {
        return false;
      }
    } else {
      if (value.getUTCFullYear() < this.minValidYear) {
        return false;
      }
    }
    if (this.maxValidDate) {
      if (value > this.maxValidDate) {
        return false;
      }
    } else {
      if (value.getUTCFullYear() > this.maxValidYear) {
        return false;
      }
    }
    return true;
  }
  isConditionUiComplete(position) {
    if (!super.isConditionUiComplete(position)) {
      return false;
    }
    let valid = true;
    this.forEachInput((element, index, elPosition, numberOfInputs) => {
      if (elPosition !== position || !valid || index >= numberOfInputs) {
        return;
      }
      valid = valid && this.isValidDateValue(element.getDate());
    });
    return valid;
  }
  areSimpleModelsEqual(aSimple, bSimple) {
    return aSimple.dateFrom === bSimple.dateFrom && aSimple.dateTo === bSimple.dateTo && aSimple.type === bSimple.type;
  }
  getFilterType() {
    return "date";
  }
  createCondition(position) {
    const type = this.getConditionType(position);
    const model = {};
    const values2 = this.getValues(position);
    if (values2.length > 0) {
      model.dateFrom = serialiseDate(values2[0]);
    }
    if (values2.length > 1) {
      model.dateTo = serialiseDate(values2[1]);
    }
    return __spreadValues({
      dateFrom: null,
      dateTo: null,
      filterType: this.getFilterType(),
      type
    }, model);
  }
  resetPlaceholder() {
    const globalTranslate = this.localeService.getLocaleTextFunc();
    const placeholder = this.translate("dateFormatOoo");
    const ariaLabel = globalTranslate("ariaFilterValue", "Filter Value");
    this.forEachInput((element) => {
      element.setInputPlaceholder(placeholder);
      element.setInputAriaLabel(ariaLabel);
    });
  }
  getInputs(position) {
    if (position >= this.dateConditionFromComps.length) {
      return [null, null];
    }
    return [this.dateConditionFromComps[position], this.dateConditionToComps[position]];
  }
  getValues(position) {
    const result = [];
    this.forEachPositionInput(position, (element, index, _elPosition, numberOfInputs) => {
      if (index < numberOfInputs) {
        result.push(element.getDate());
      }
    });
    return result;
  }
  translate(key) {
    if (key === ScalarFilter.LESS_THAN) {
      return super.translate("before");
    }
    if (key === ScalarFilter.GREATER_THAN) {
      return super.translate("after");
    }
    return super.translate(key);
  }
  getModelAsString(model) {
    var _a;
    return (_a = this.filterModelFormatter.getModelAsString(model)) != null ? _a : "";
  }
};
_DateFilter.DEFAULT_FILTER_OPTIONS = [
  ScalarFilter.EQUALS,
  ScalarFilter.NOT_EQUAL,
  ScalarFilter.LESS_THAN,
  ScalarFilter.GREATER_THAN,
  ScalarFilter.IN_RANGE,
  ScalarFilter.BLANK,
  ScalarFilter.NOT_BLANK
];
__decorateClass([
  Autowired("userComponentFactory")
], _DateFilter.prototype, "userComponentFactory", 2);
var DateFilter = _DateFilter;

// community-modules/core/src/filter/floating/provided/simpleFloatingFilter.ts
var SimpleFloatingFilter = class extends Component {
  getDefaultDebounceMs() {
    return 0;
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
  isEventFromFloatingFilter(event) {
    return event && event.afterFloatingFilter;
  }
  isEventFromDataChange(event) {
    return event == null ? void 0 : event.afterDataChange;
  }
  getLastType() {
    return this.lastType;
  }
  isReadOnly() {
    return this.readOnly;
  }
  setLastTypeFromModel(model) {
    if (!model) {
      this.lastType = this.optionsFactory.getDefaultOption();
      return;
    }
    const isCombined = model.operator;
    let condition;
    if (isCombined) {
      const combinedModel = model;
      condition = combinedModel.conditions[0];
    } else {
      condition = model;
    }
    this.lastType = condition.type;
  }
  canWeEditAfterModelFromParentFilter(model) {
    if (!model) {
      return this.isTypeEditable(this.lastType);
    }
    const isCombined = model.operator;
    if (isCombined) {
      return false;
    }
    const simpleModel = model;
    return this.isTypeEditable(simpleModel.type);
  }
  init(params) {
    this.setSimpleParams(params, false);
  }
  setSimpleParams(params, update = true) {
    this.optionsFactory = new OptionsFactory();
    this.optionsFactory.init(params.filterParams, this.getDefaultFilterOptions());
    if (!update) {
      this.lastType = this.optionsFactory.getDefaultOption();
    }
    this.readOnly = !!params.filterParams.readOnly;
    const editable = this.isTypeEditable(this.optionsFactory.getDefaultOption());
    this.setEditable(editable);
  }
  onParamsUpdated(params) {
    this.refresh(params);
  }
  refresh(params) {
    this.setSimpleParams(params);
  }
  doesFilterHaveSingleInput(filterType) {
    const customFilterOption = this.optionsFactory.getCustomOption(filterType);
    const { numberOfInputs } = customFilterOption || {};
    return numberOfInputs == null || numberOfInputs == 1;
  }
  isTypeEditable(type) {
    const uneditableTypes = [
      SimpleFilter.IN_RANGE,
      SimpleFilter.EMPTY,
      SimpleFilter.BLANK,
      SimpleFilter.NOT_BLANK
    ];
    return !!type && !this.isReadOnly() && this.doesFilterHaveSingleInput(type) && uneditableTypes.indexOf(type) < 0;
  }
  getAriaLabel(params) {
    const displayName = this.columnModel.getDisplayNameForColumn(params.column, "header", true);
    const translate = this.localeService.getLocaleTextFunc();
    return `${displayName} ${translate("ariaFilterInput", "Filter Input")}`;
  }
};
__decorateClass([
  Autowired("columnModel")
], SimpleFloatingFilter.prototype, "columnModel", 2);

// community-modules/core/src/filter/provided/date/dateFloatingFilter.ts
var DateFloatingFilter = class extends SimpleFloatingFilter {
  constructor() {
    super(
      /* html */
      `
            <div class="ag-floating-filter-input" role="presentation">
                <ag-input-text-field ref="eReadOnlyText"></ag-input-text-field>
                <div ref="eDateWrapper" style="display: flex;"></div>
            </div>`
    );
  }
  getDefaultFilterOptions() {
    return DateFilter.DEFAULT_FILTER_OPTIONS;
  }
  init(params) {
    super.init(params);
    this.params = params;
    this.filterParams = params.filterParams;
    this.createDateComponent();
    this.filterModelFormatter = new DateFilterModelFormatter(this.filterParams, this.localeService, this.optionsFactory);
    const translate = this.localeService.getLocaleTextFunc();
    this.eReadOnlyText.setDisabled(true).setInputAriaLabel(translate("ariaDateFilterInput", "Date Filter Input"));
  }
  onParamsUpdated(params) {
    this.refresh(params);
  }
  refresh(params) {
    super.refresh(params);
    this.params = params;
    this.filterParams = params.filterParams;
    this.updateDateComponent();
    this.filterModelFormatter.updateParams({ optionsFactory: this.optionsFactory, dateFilterParams: this.filterParams });
    this.updateCompOnModelChange(params.currentParentModel());
  }
  updateCompOnModelChange(model) {
    const allowEditing = !this.isReadOnly() && this.canWeEditAfterModelFromParentFilter(model);
    this.setEditable(allowEditing);
    if (allowEditing) {
      if (model) {
        const dateModel = model;
        this.dateComp.setDate(parseDateTimeFromString(dateModel.dateFrom));
      } else {
        this.dateComp.setDate(null);
      }
      this.eReadOnlyText.setValue("");
    } else {
      this.eReadOnlyText.setValue(this.filterModelFormatter.getModelAsString(model));
      this.dateComp.setDate(null);
    }
  }
  setEditable(editable) {
    setDisplayed(this.eDateWrapper, editable);
    setDisplayed(this.eReadOnlyText.getGui(), !editable);
  }
  onParentModelChanged(model, event) {
    if (this.isEventFromFloatingFilter(event) || this.isEventFromDataChange(event)) {
      return;
    }
    super.setLastTypeFromModel(model);
    this.updateCompOnModelChange(model);
  }
  onDateChanged() {
    const filterValueDate = this.dateComp.getDate();
    const filterValueText = serialiseDate(filterValueDate);
    this.params.parentFilterInstance((filterInstance) => {
      if (filterInstance) {
        const date = parseDateTimeFromString(filterValueText);
        filterInstance.onFloatingFilterChanged(this.getLastType() || null, date);
      }
    });
  }
  getDateComponentParams() {
    const debounceMs = ProvidedFilter.getDebounceMs(this.params.filterParams, this.getDefaultDebounceMs());
    return {
      onDateChanged: debounce(this.onDateChanged.bind(this), debounceMs),
      filterParams: this.params.column.getColDef().filterParams
    };
  }
  createDateComponent() {
    this.dateComp = new DateCompWrapper(this.getContext(), this.userComponentFactory, this.getDateComponentParams(), this.eDateWrapper, (dateComp) => {
      dateComp.setInputAriaLabel(this.getAriaLabel(this.params));
    });
    this.addDestroyFunc(() => this.dateComp.destroy());
  }
  updateDateComponent() {
    const params = this.gos.addGridCommonParams(this.getDateComponentParams());
    this.dateComp.updateParams(params);
  }
  getFilterModelFormatter() {
    return this.filterModelFormatter;
  }
};
__decorateClass([
  Autowired("userComponentFactory")
], DateFloatingFilter.prototype, "userComponentFactory", 2);
__decorateClass([
  RefSelector("eReadOnlyText")
], DateFloatingFilter.prototype, "eReadOnlyText", 2);
__decorateClass([
  RefSelector("eDateWrapper")
], DateFloatingFilter.prototype, "eDateWrapper", 2);

// community-modules/core/src/filter/provided/date/defaultDateComponent.ts
var DefaultDateComponent = class extends Component {
  constructor() {
    super(
      /* html */
      `
            <div class="ag-filter-filter">
                <ag-input-text-field class="ag-date-filter" ref="eDateInput"></ag-input-text-field>
            </div>`
    );
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
  init(params) {
    this.params = params;
    this.setParams(params);
    const inputElement = this.eDateInput.getInputElement();
    this.addManagedListener(inputElement, "mousedown", () => {
      if (this.eDateInput.isDisabled() || this.usingSafariDatePicker) {
        return;
      }
      inputElement.focus();
    });
    this.addManagedListener(inputElement, "input", (e) => {
      if (e.target !== this.gos.getActiveDomElement()) {
        return;
      }
      if (this.eDateInput.isDisabled()) {
        return;
      }
      this.params.onDateChanged();
    });
  }
  setParams(params) {
    const inputElement = this.eDateInput.getInputElement();
    const shouldUseBrowserDatePicker = this.shouldUseBrowserDatePicker(params);
    this.usingSafariDatePicker = shouldUseBrowserDatePicker && isBrowserSafari();
    inputElement.type = shouldUseBrowserDatePicker ? "date" : "text";
    const {
      minValidYear,
      maxValidYear,
      minValidDate,
      maxValidDate
    } = params.filterParams || {};
    if (minValidDate && minValidYear) {
      warnOnce("DateFilter should not have both minValidDate and minValidYear parameters set at the same time! minValidYear will be ignored.");
    }
    if (maxValidDate && maxValidYear) {
      warnOnce("DateFilter should not have both maxValidDate and maxValidYear parameters set at the same time! maxValidYear will be ignored.");
    }
    if (minValidDate && maxValidDate) {
      const [parsedMinValidDate, parsedMaxValidDate] = [minValidDate, maxValidDate].map((v) => v instanceof Date ? v : parseDateTimeFromString(v));
      if (parsedMinValidDate && parsedMaxValidDate && parsedMinValidDate.getTime() > parsedMaxValidDate.getTime()) {
        warnOnce("DateFilter parameter minValidDate should always be lower than or equal to parameter maxValidDate.");
      }
    }
    if (minValidDate) {
      if (minValidDate instanceof Date) {
        inputElement.min = dateToFormattedString(minValidDate);
      } else {
        inputElement.min = minValidDate;
      }
    } else {
      if (minValidYear) {
        inputElement.min = `${minValidYear}-01-01`;
      }
    }
    if (maxValidDate) {
      if (maxValidDate instanceof Date) {
        inputElement.max = dateToFormattedString(maxValidDate);
      } else {
        inputElement.max = maxValidDate;
      }
    } else {
      if (maxValidYear) {
        inputElement.max = `${maxValidYear}-12-31`;
      }
    }
  }
  onParamsUpdated(params) {
    this.refresh(params);
  }
  refresh(params) {
    this.params = params;
    this.setParams(params);
  }
  getDate() {
    return parseDateTimeFromString(this.eDateInput.getValue());
  }
  setDate(date) {
    this.eDateInput.setValue(serialiseDate(date, false));
  }
  setInputPlaceholder(placeholder) {
    this.eDateInput.setInputPlaceholder(placeholder);
  }
  setInputAriaLabel(ariaLabel) {
    this.eDateInput.setAriaLabel(ariaLabel);
  }
  setDisabled(disabled) {
    this.eDateInput.setDisabled(disabled);
  }
  afterGuiAttached(params) {
    if (!params || !params.suppressFocus) {
      this.eDateInput.getInputElement().focus();
    }
  }
  shouldUseBrowserDatePicker(params) {
    if (params.filterParams && params.filterParams.browserDatePicker != null) {
      return params.filterParams.browserDatePicker;
    }
    return isBrowserChrome() || isBrowserFirefox() || isBrowserSafari() && getSafariVersion() >= 14.1;
  }
};
__decorateClass([
  RefSelector("eDateInput")
], DefaultDateComponent.prototype, "eDateInput", 2);

// community-modules/core/src/widgets/agInputTextField.ts
var AgInputTextField = class extends AgAbstractInputField {
  constructor(config, className = "ag-text-field", inputType = "text") {
    super(config, className, inputType);
  }
  postConstruct() {
    super.postConstruct();
    if (this.config.allowedCharPattern) {
      this.preventDisallowedCharacters();
    }
  }
  setValue(value, silent) {
    if (this.eInput.value !== value) {
      this.eInput.value = exists(value) ? value : "";
    }
    return super.setValue(value, silent);
  }
  /** Used to set an initial value into the input without necessarily setting `this.value` or triggering events (e.g. to set an invalid value) */
  setStartValue(value) {
    this.setValue(value, true);
  }
  preventDisallowedCharacters() {
    const pattern = new RegExp(`[${this.config.allowedCharPattern}]`);
    const preventCharacters = (event) => {
      if (!isEventFromPrintableCharacter(event)) {
        return;
      }
      if (event.key && !pattern.test(event.key)) {
        event.preventDefault();
      }
    };
    this.addManagedListener(this.eInput, "keydown", preventCharacters);
    this.addManagedListener(this.eInput, "paste", (e) => {
      var _a;
      const text = (_a = e.clipboardData) == null ? void 0 : _a.getData("text");
      if (text && text.split("").some((c) => !pattern.test(c))) {
        e.preventDefault();
      }
    });
  }
};

// community-modules/core/src/widgets/agInputNumberField.ts
var AgInputNumberField = class extends AgInputTextField {
  constructor(config) {
    super(config, "ag-number-field", "number");
  }
  postConstruct() {
    super.postConstruct();
    this.addManagedListener(this.eInput, "blur", () => {
      const floatedValue = parseFloat(this.eInput.value);
      const value = isNaN(floatedValue) ? "" : this.normalizeValue(floatedValue.toString());
      if (this.value !== value) {
        this.setValue(value);
      }
    });
    this.addManagedListener(this.eInput, "wheel", this.onWheel.bind(this));
    this.eInput.step = "any";
    const { precision, min, max, step } = this.config;
    if (typeof precision === "number")
      this.setPrecision(precision);
    if (typeof min === "number")
      this.setMin(min);
    if (typeof max === "number")
      this.setMax(max);
    if (typeof step === "number")
      this.setStep(step);
  }
  onWheel(e) {
    if (this.gos.getActiveDomElement() === this.eInput) {
      e.preventDefault();
    }
  }
  normalizeValue(value) {
    if (value === "") {
      return "";
    }
    if (this.precision != null) {
      value = this.adjustPrecision(value);
    }
    const val = parseFloat(value);
    if (this.min != null && val < this.min) {
      value = this.min.toString();
    } else if (this.max != null && val > this.max) {
      value = this.max.toString();
    }
    return value;
  }
  adjustPrecision(value, isScientificNotation) {
    if (this.precision == null) {
      return value;
    }
    if (isScientificNotation) {
      const floatString = parseFloat(value).toFixed(this.precision);
      return parseFloat(floatString).toString();
    }
    const parts = String(value).split(".");
    if (parts.length > 1) {
      if (parts[1].length <= this.precision) {
        return value;
      } else if (this.precision > 0) {
        return `${parts[0]}.${parts[1].slice(0, this.precision)}`;
      }
    }
    return parts[0];
  }
  setMin(min) {
    if (this.min === min) {
      return this;
    }
    this.min = min;
    addOrRemoveAttribute(this.eInput, "min", min);
    return this;
  }
  setMax(max) {
    if (this.max === max) {
      return this;
    }
    this.max = max;
    addOrRemoveAttribute(this.eInput, "max", max);
    return this;
  }
  setPrecision(precision) {
    this.precision = precision;
    return this;
  }
  setStep(step) {
    if (this.step === step) {
      return this;
    }
    this.step = step;
    addOrRemoveAttribute(this.eInput, "step", step);
    return this;
  }
  setValue(value, silent) {
    return this.setValueOrInputValue((v) => super.setValue(v, silent), () => this, value);
  }
  setStartValue(value) {
    return this.setValueOrInputValue(
      (v) => super.setValue(v, true),
      (v) => {
        this.eInput.value = v;
      },
      value
    );
  }
  setValueOrInputValue(setValueFunc, setInputValueOnlyFunc, value) {
    if (exists(value)) {
      let setInputValueOnly = this.isScientificNotation(value);
      if (setInputValueOnly && this.eInput.validity.valid) {
        return setValueFunc(value);
      }
      if (!setInputValueOnly) {
        value = this.adjustPrecision(value);
        const normalizedValue = this.normalizeValue(value);
        setInputValueOnly = value != normalizedValue;
      }
      if (setInputValueOnly) {
        return setInputValueOnlyFunc(value);
      }
    }
    return setValueFunc(value);
  }
  getValue() {
    if (!this.eInput.validity.valid) {
      return void 0;
    }
    const inputValue = this.eInput.value;
    if (this.isScientificNotation(inputValue)) {
      return this.adjustPrecision(inputValue, true);
    }
    return super.getValue();
  }
  isScientificNotation(value) {
    return typeof value === "string" && value.includes("e");
  }
};

// community-modules/core/src/filter/provided/number/numberFilter.ts
var NumberFilterModelFormatter = class extends SimpleFilterModelFormatter {
  conditionToString(condition, options) {
    const { numberOfInputs } = options || {};
    const isRange = condition.type == SimpleFilter.IN_RANGE || numberOfInputs === 2;
    if (isRange) {
      return `${this.formatValue(condition.filter)}-${this.formatValue(condition.filterTo)}`;
    }
    if (condition.filter != null) {
      return this.formatValue(condition.filter);
    }
    return `${condition.type}`;
  }
};
function getAllowedCharPattern(filterParams) {
  const { allowedCharPattern } = filterParams != null ? filterParams : {};
  return allowedCharPattern != null ? allowedCharPattern : null;
}
var _NumberFilter = class _NumberFilter extends ScalarFilter {
  constructor() {
    super("numberFilter");
    this.eValuesFrom = [];
    this.eValuesTo = [];
  }
  refresh(params) {
    if (this.numberFilterParams.allowedCharPattern !== params.allowedCharPattern) {
      return false;
    }
    return super.refresh(params);
  }
  mapValuesFromModel(filterModel) {
    const { filter, filterTo, type } = filterModel || {};
    return [
      this.processValue(filter),
      this.processValue(filterTo)
    ].slice(0, this.getNumberOfInputs(type));
  }
  getDefaultDebounceMs() {
    return 500;
  }
  comparator() {
    return (left, right) => {
      if (left === right) {
        return 0;
      }
      return left < right ? 1 : -1;
    };
  }
  setParams(params) {
    this.numberFilterParams = params;
    super.setParams(params);
    this.filterModelFormatter = new NumberFilterModelFormatter(this.localeService, this.optionsFactory, this.numberFilterParams.numberFormatter);
  }
  getDefaultFilterOptions() {
    return _NumberFilter.DEFAULT_FILTER_OPTIONS;
  }
  setElementValue(element, value, fromFloatingFilter) {
    const valueToSet = !fromFloatingFilter && this.numberFilterParams.numberFormatter ? this.numberFilterParams.numberFormatter(value != null ? value : null) : value;
    super.setElementValue(element, valueToSet);
  }
  createValueElement() {
    const allowedCharPattern = getAllowedCharPattern(this.numberFilterParams);
    const eCondition = document.createElement("div");
    eCondition.classList.add("ag-filter-body");
    setAriaRole(eCondition, "presentation");
    this.createFromToElement(eCondition, this.eValuesFrom, "from", allowedCharPattern);
    this.createFromToElement(eCondition, this.eValuesTo, "to", allowedCharPattern);
    return eCondition;
  }
  createFromToElement(eCondition, eValues, fromTo, allowedCharPattern) {
    const eValue = this.createManagedBean(allowedCharPattern ? new AgInputTextField({ allowedCharPattern }) : new AgInputNumberField());
    eValue.addCssClass(`ag-filter-${fromTo}`);
    eValue.addCssClass("ag-filter-filter");
    eValues.push(eValue);
    eCondition.appendChild(eValue.getGui());
  }
  removeValueElements(startPosition, deleteCount) {
    this.removeComponents(this.eValuesFrom, startPosition, deleteCount);
    this.removeComponents(this.eValuesTo, startPosition, deleteCount);
  }
  getValues(position) {
    const result = [];
    this.forEachPositionInput(position, (element, index, _elPosition, numberOfInputs) => {
      if (index < numberOfInputs) {
        result.push(this.processValue(this.stringToFloat(element.getValue())));
      }
    });
    return result;
  }
  areSimpleModelsEqual(aSimple, bSimple) {
    return aSimple.filter === bSimple.filter && aSimple.filterTo === bSimple.filterTo && aSimple.type === bSimple.type;
  }
  getFilterType() {
    return "number";
  }
  processValue(value) {
    if (value == null) {
      return null;
    }
    return isNaN(value) ? null : value;
  }
  stringToFloat(value) {
    if (typeof value === "number") {
      return value;
    }
    let filterText = makeNull(value);
    if (filterText != null && filterText.trim() === "") {
      filterText = null;
    }
    if (this.numberFilterParams.numberParser) {
      return this.numberFilterParams.numberParser(filterText);
    }
    return filterText == null || filterText.trim() === "-" ? null : parseFloat(filterText);
  }
  createCondition(position) {
    const type = this.getConditionType(position);
    const model = {
      filterType: this.getFilterType(),
      type
    };
    const values2 = this.getValues(position);
    if (values2.length > 0) {
      model.filter = values2[0];
    }
    if (values2.length > 1) {
      model.filterTo = values2[1];
    }
    return model;
  }
  getInputs(position) {
    if (position >= this.eValuesFrom.length) {
      return [null, null];
    }
    return [this.eValuesFrom[position], this.eValuesTo[position]];
  }
  getModelAsString(model) {
    var _a;
    return (_a = this.filterModelFormatter.getModelAsString(model)) != null ? _a : "";
  }
  hasInvalidInputs() {
    let invalidInputs = false;
    this.forEachInput((element) => {
      if (!element.getInputElement().validity.valid) {
        invalidInputs = true;
        return;
      }
    });
    return invalidInputs;
  }
};
_NumberFilter.DEFAULT_FILTER_OPTIONS = [
  ScalarFilter.EQUALS,
  ScalarFilter.NOT_EQUAL,
  ScalarFilter.GREATER_THAN,
  ScalarFilter.GREATER_THAN_OR_EQUAL,
  ScalarFilter.LESS_THAN,
  ScalarFilter.LESS_THAN_OR_EQUAL,
  ScalarFilter.IN_RANGE,
  ScalarFilter.BLANK,
  ScalarFilter.NOT_BLANK
];
var NumberFilter = _NumberFilter;

// community-modules/core/src/filter/provided/text/textFilter.ts
var TextFilterModelFormatter = class extends SimpleFilterModelFormatter {
  conditionToString(condition, options) {
    const { numberOfInputs } = options || {};
    const isRange = condition.type == SimpleFilter.IN_RANGE || numberOfInputs === 2;
    if (isRange) {
      return `${condition.filter}-${condition.filterTo}`;
    }
    if (condition.filter != null) {
      return `${condition.filter}`;
    }
    return `${condition.type}`;
  }
};
var _TextFilter = class _TextFilter extends SimpleFilter {
  constructor() {
    super("textFilter");
    this.eValuesFrom = [];
    this.eValuesTo = [];
  }
  static trimInput(value) {
    const trimmedInput = value && value.trim();
    return trimmedInput === "" ? value : trimmedInput;
  }
  getDefaultDebounceMs() {
    return 500;
  }
  setParams(params) {
    this.textFilterParams = params;
    super.setParams(params);
    this.matcher = this.getTextMatcher();
    this.formatter = this.textFilterParams.textFormatter || (this.textFilterParams.caseSensitive ? _TextFilter.DEFAULT_FORMATTER : _TextFilter.DEFAULT_LOWERCASE_FORMATTER);
    this.filterModelFormatter = new TextFilterModelFormatter(this.localeService, this.optionsFactory);
  }
  getTextMatcher() {
    const legacyComparator = this.textFilterParams.textCustomComparator;
    if (legacyComparator) {
      _.warnOnce("textCustomComparator is deprecated, use textMatcher instead.");
      return ({ filterOption, value, filterText }) => legacyComparator(filterOption, value, filterText);
    }
    return this.textFilterParams.textMatcher || _TextFilter.DEFAULT_MATCHER;
  }
  createCondition(position) {
    const type = this.getConditionType(position);
    const model = {
      filterType: this.getFilterType(),
      type
    };
    const values2 = this.getValuesWithSideEffects(position, true);
    if (values2.length > 0) {
      model.filter = values2[0];
    }
    if (values2.length > 1) {
      model.filterTo = values2[1];
    }
    return model;
  }
  getFilterType() {
    return "text";
  }
  areSimpleModelsEqual(aSimple, bSimple) {
    return aSimple.filter === bSimple.filter && aSimple.filterTo === bSimple.filterTo && aSimple.type === bSimple.type;
  }
  getInputs(position) {
    if (position >= this.eValuesFrom.length) {
      return [null, null];
    }
    return [this.eValuesFrom[position], this.eValuesTo[position]];
  }
  getValues(position) {
    return this.getValuesWithSideEffects(position, false);
  }
  getValuesWithSideEffects(position, applySideEffects) {
    const result = [];
    this.forEachPositionInput(position, (element, index, _elPosition, numberOfInputs) => {
      var _a;
      if (index < numberOfInputs) {
        let value = makeNull(element.getValue());
        if (applySideEffects && this.textFilterParams.trimInput) {
          value = (_a = _TextFilter.trimInput(value)) != null ? _a : null;
          element.setValue(value, true);
        }
        result.push(value);
      }
    });
    return result;
  }
  getDefaultFilterOptions() {
    return _TextFilter.DEFAULT_FILTER_OPTIONS;
  }
  createValueElement() {
    const eCondition = document.createElement("div");
    eCondition.classList.add("ag-filter-body");
    setAriaRole(eCondition, "presentation");
    this.createFromToElement(eCondition, this.eValuesFrom, "from");
    this.createFromToElement(eCondition, this.eValuesTo, "to");
    return eCondition;
  }
  createFromToElement(eCondition, eValues, fromTo) {
    const eValue = this.createManagedBean(new AgInputTextField());
    eValue.addCssClass(`ag-filter-${fromTo}`);
    eValue.addCssClass("ag-filter-filter");
    eValues.push(eValue);
    eCondition.appendChild(eValue.getGui());
  }
  removeValueElements(startPosition, deleteCount) {
    this.removeComponents(this.eValuesFrom, startPosition, deleteCount);
    this.removeComponents(this.eValuesTo, startPosition, deleteCount);
  }
  mapValuesFromModel(filterModel) {
    const { filter, filterTo, type } = filterModel || {};
    return [
      filter || null,
      filterTo || null
    ].slice(0, this.getNumberOfInputs(type));
  }
  evaluateNullValue(filterType) {
    const filterTypesAllowNulls = [
      SimpleFilter.NOT_EQUAL,
      SimpleFilter.NOT_CONTAINS,
      SimpleFilter.BLANK
    ];
    return filterType ? filterTypesAllowNulls.indexOf(filterType) >= 0 : false;
  }
  evaluateNonNullValue(values2, cellValue, filterModel, params) {
    const formattedValues = values2.map((v) => this.formatter(v)) || [];
    const cellValueFormatted = this.formatter(cellValue);
    const { api, colDef, column, columnApi, context, textFormatter } = this.textFilterParams;
    if (filterModel.type === SimpleFilter.BLANK) {
      return this.isBlank(cellValue);
    } else if (filterModel.type === SimpleFilter.NOT_BLANK) {
      return !this.isBlank(cellValue);
    }
    const matcherParams = {
      api,
      colDef,
      column,
      columnApi,
      context,
      node: params.node,
      data: params.data,
      filterOption: filterModel.type,
      value: cellValueFormatted,
      textFormatter
    };
    return formattedValues.some((v) => this.matcher(__spreadProps(__spreadValues({}, matcherParams), { filterText: v })));
  }
  getModelAsString(model) {
    var _a;
    return (_a = this.filterModelFormatter.getModelAsString(model)) != null ? _a : "";
  }
};
_TextFilter.DEFAULT_FILTER_OPTIONS = [
  SimpleFilter.CONTAINS,
  SimpleFilter.NOT_CONTAINS,
  SimpleFilter.EQUALS,
  SimpleFilter.NOT_EQUAL,
  SimpleFilter.STARTS_WITH,
  SimpleFilter.ENDS_WITH,
  SimpleFilter.BLANK,
  SimpleFilter.NOT_BLANK
];
_TextFilter.DEFAULT_FORMATTER = (from) => from;
_TextFilter.DEFAULT_LOWERCASE_FORMATTER = (from) => from == null ? null : from.toString().toLowerCase();
_TextFilter.DEFAULT_MATCHER = ({ filterOption, value, filterText }) => {
  if (filterText == null) {
    return false;
  }
  switch (filterOption) {
    case _TextFilter.CONTAINS:
      return value.indexOf(filterText) >= 0;
    case _TextFilter.NOT_CONTAINS:
      return value.indexOf(filterText) < 0;
    case _TextFilter.EQUALS:
      return value === filterText;
    case _TextFilter.NOT_EQUAL:
      return value != filterText;
    case _TextFilter.STARTS_WITH:
      return value.indexOf(filterText) === 0;
    case _TextFilter.ENDS_WITH:
      const index = value.lastIndexOf(filterText);
      return index >= 0 && index === value.length - filterText.length;
    default:
      return false;
  }
};
var TextFilter = _TextFilter;

// community-modules/core/src/filter/floating/provided/textInputFloatingFilter.ts
var FloatingFilterTextInputService = class extends BeanStub {
  constructor(params) {
    super();
    this.params = params;
    this.valueChangedListener = () => {
    };
  }
  setupGui(parentElement) {
    var _a;
    this.eFloatingFilterTextInput = this.createManagedBean(new AgInputTextField((_a = this.params) == null ? void 0 : _a.config));
    const eInput = this.eFloatingFilterTextInput.getGui();
    parentElement.appendChild(eInput);
    this.addManagedListener(eInput, "input", (e) => this.valueChangedListener(e));
    this.addManagedListener(eInput, "keydown", (e) => this.valueChangedListener(e));
  }
  setEditable(editable) {
    this.eFloatingFilterTextInput.setDisabled(!editable);
  }
  setAutoComplete(autoComplete) {
    this.eFloatingFilterTextInput.setAutoComplete(autoComplete);
  }
  getValue() {
    return this.eFloatingFilterTextInput.getValue();
  }
  setValue(value, silent) {
    this.eFloatingFilterTextInput.setValue(value, silent);
  }
  setValueChangedListener(listener) {
    this.valueChangedListener = listener;
  }
  setParams(params) {
    this.setAriaLabel(params.ariaLabel);
    if (params.autoComplete !== void 0) {
      this.setAutoComplete(params.autoComplete);
    }
  }
  setAriaLabel(ariaLabel) {
    this.eFloatingFilterTextInput.setInputAriaLabel(ariaLabel);
  }
};
var TextInputFloatingFilter = class extends SimpleFloatingFilter {
  postConstruct() {
    this.setTemplate(
      /* html */
      `
            <div class="ag-floating-filter-input" role="presentation" ref="eFloatingFilterInputContainer"></div>
        `
    );
  }
  getDefaultDebounceMs() {
    return 500;
  }
  onParentModelChanged(model, event) {
    if (this.isEventFromFloatingFilter(event) || this.isEventFromDataChange(event)) {
      return;
    }
    this.setLastTypeFromModel(model);
    this.setEditable(this.canWeEditAfterModelFromParentFilter(model));
    this.floatingFilterInputService.setValue(this.getFilterModelFormatter().getModelAsString(model));
  }
  init(params) {
    this.setupFloatingFilterInputService(params);
    super.init(params);
    this.setTextInputParams(params);
  }
  setupFloatingFilterInputService(params) {
    this.floatingFilterInputService = this.createFloatingFilterInputService(params);
    this.floatingFilterInputService.setupGui(this.eFloatingFilterInputContainer);
  }
  setTextInputParams(params) {
    var _a;
    this.params = params;
    const autoComplete = (_a = params.browserAutoComplete) != null ? _a : false;
    this.floatingFilterInputService.setParams({
      ariaLabel: this.getAriaLabel(params),
      autoComplete
    });
    this.applyActive = ProvidedFilter.isUseApplyButton(this.params.filterParams);
    if (!this.isReadOnly()) {
      const debounceMs = ProvidedFilter.getDebounceMs(this.params.filterParams, this.getDefaultDebounceMs());
      const toDebounce = debounce(this.syncUpWithParentFilter.bind(this), debounceMs);
      this.floatingFilterInputService.setValueChangedListener(toDebounce);
    }
  }
  onParamsUpdated(params) {
    this.refresh(params);
  }
  refresh(params) {
    super.refresh(params);
    this.setTextInputParams(params);
  }
  recreateFloatingFilterInputService(params) {
    const value = this.floatingFilterInputService.getValue();
    clearElement(this.eFloatingFilterInputContainer);
    this.destroyBean(this.floatingFilterInputService);
    this.setupFloatingFilterInputService(params);
    this.floatingFilterInputService.setValue(value, true);
  }
  syncUpWithParentFilter(e) {
    const isEnterKey = e.key === KeyCode.ENTER;
    if (this.applyActive && !isEnterKey) {
      return;
    }
    let value = this.floatingFilterInputService.getValue();
    if (this.params.filterParams.trimInput) {
      value = TextFilter.trimInput(value);
      this.floatingFilterInputService.setValue(value, true);
    }
    this.params.parentFilterInstance((filterInstance) => {
      if (filterInstance) {
        filterInstance.onFloatingFilterChanged(this.getLastType() || null, value || null);
      }
    });
  }
  setEditable(editable) {
    this.floatingFilterInputService.setEditable(editable);
  }
};
__decorateClass([
  RefSelector("eFloatingFilterInputContainer")
], TextInputFloatingFilter.prototype, "eFloatingFilterInputContainer", 2);
__decorateClass([
  PostConstruct
], TextInputFloatingFilter.prototype, "postConstruct", 1);

// community-modules/core/src/filter/provided/number/numberFloatingFilter.ts
var FloatingFilterNumberInputService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.valueChangedListener = () => {
    };
    this.numberInputActive = true;
  }
  setupGui(parentElement) {
    this.eFloatingFilterNumberInput = this.createManagedBean(new AgInputNumberField());
    this.eFloatingFilterTextInput = this.createManagedBean(new AgInputTextField());
    this.eFloatingFilterTextInput.setDisabled(true);
    const eNumberInput = this.eFloatingFilterNumberInput.getGui();
    const eTextInput = this.eFloatingFilterTextInput.getGui();
    parentElement.appendChild(eNumberInput);
    parentElement.appendChild(eTextInput);
    this.setupListeners(eNumberInput, (e) => this.valueChangedListener(e));
    this.setupListeners(eTextInput, (e) => this.valueChangedListener(e));
  }
  setEditable(editable) {
    this.numberInputActive = editable;
    this.eFloatingFilterNumberInput.setDisplayed(this.numberInputActive);
    this.eFloatingFilterTextInput.setDisplayed(!this.numberInputActive);
  }
  setAutoComplete(autoComplete) {
    this.eFloatingFilterNumberInput.setAutoComplete(autoComplete);
    this.eFloatingFilterTextInput.setAutoComplete(autoComplete);
  }
  getValue() {
    return this.getActiveInputElement().getValue();
  }
  setValue(value, silent) {
    this.getActiveInputElement().setValue(value, silent);
  }
  getActiveInputElement() {
    return this.numberInputActive ? this.eFloatingFilterNumberInput : this.eFloatingFilterTextInput;
  }
  setValueChangedListener(listener) {
    this.valueChangedListener = listener;
  }
  setupListeners(element, listener) {
    this.addManagedListener(element, "input", listener);
    this.addManagedListener(element, "keydown", listener);
  }
  setParams(params) {
    this.setAriaLabel(params.ariaLabel);
    if (params.autoComplete !== void 0) {
      this.setAutoComplete(params.autoComplete);
    }
  }
  setAriaLabel(ariaLabel) {
    this.eFloatingFilterNumberInput.setInputAriaLabel(ariaLabel);
    this.eFloatingFilterTextInput.setInputAriaLabel(ariaLabel);
  }
};
var NumberFloatingFilter = class extends TextInputFloatingFilter {
  init(params) {
    var _a;
    super.init(params);
    this.filterModelFormatter = new NumberFilterModelFormatter(
      this.localeService,
      this.optionsFactory,
      (_a = params.filterParams) == null ? void 0 : _a.numberFormatter
    );
  }
  onParamsUpdated(params) {
    this.refresh(params);
  }
  refresh(params) {
    const allowedCharPattern = getAllowedCharPattern(params.filterParams);
    if (allowedCharPattern !== this.allowedCharPattern) {
      this.recreateFloatingFilterInputService(params);
    }
    super.refresh(params);
    this.filterModelFormatter.updateParams({ optionsFactory: this.optionsFactory });
  }
  getDefaultFilterOptions() {
    return NumberFilter.DEFAULT_FILTER_OPTIONS;
  }
  getFilterModelFormatter() {
    return this.filterModelFormatter;
  }
  createFloatingFilterInputService(params) {
    this.allowedCharPattern = getAllowedCharPattern(params.filterParams);
    if (this.allowedCharPattern) {
      return this.createManagedBean(new FloatingFilterTextInputService({
        config: { allowedCharPattern: this.allowedCharPattern }
      }));
    }
    return this.createManagedBean(new FloatingFilterNumberInputService());
  }
};

// community-modules/core/src/filter/provided/text/textFloatingFilter.ts
var TextFloatingFilter = class extends TextInputFloatingFilter {
  init(params) {
    super.init(params);
    this.filterModelFormatter = new TextFilterModelFormatter(this.localeService, this.optionsFactory);
  }
  onParamsUpdated(params) {
    this.refresh(params);
  }
  refresh(params) {
    super.refresh(params);
    this.filterModelFormatter.updateParams({ optionsFactory: this.optionsFactory });
  }
  getDefaultFilterOptions() {
    return TextFilter.DEFAULT_FILTER_OPTIONS;
  }
  getFilterModelFormatter() {
    return this.filterModelFormatter;
  }
  createFloatingFilterInputService() {
    return this.createManagedBean(new FloatingFilterTextInputService());
  }
};

// community-modules/core/src/widgets/touchListener.ts
var _TouchListener = class _TouchListener {
  constructor(eElement, preventMouseClick = false) {
    this.destroyFuncs = [];
    this.touching = false;
    this.eventService = new EventService();
    this.eElement = eElement;
    this.preventMouseClick = preventMouseClick;
    const startListener = this.onTouchStart.bind(this);
    const moveListener = this.onTouchMove.bind(this);
    const endListener = this.onTouchEnd.bind(this);
    this.eElement.addEventListener("touchstart", startListener, { passive: true });
    this.eElement.addEventListener("touchmove", moveListener, { passive: true });
    this.eElement.addEventListener("touchend", endListener, { passive: false });
    this.destroyFuncs.push(() => {
      this.eElement.removeEventListener("touchstart", startListener, { passive: true });
      this.eElement.removeEventListener("touchmove", moveListener, { passive: true });
      this.eElement.removeEventListener("touchend", endListener, { passive: false });
    });
  }
  getActiveTouch(touchList) {
    for (let i = 0; i < touchList.length; i++) {
      const matches = touchList[i].identifier === this.touchStart.identifier;
      if (matches) {
        return touchList[i];
      }
    }
    return null;
  }
  addEventListener(eventType, listener) {
    this.eventService.addEventListener(eventType, listener);
  }
  removeEventListener(eventType, listener) {
    this.eventService.removeEventListener(eventType, listener);
  }
  onTouchStart(touchEvent) {
    if (this.touching) {
      return;
    }
    this.touchStart = touchEvent.touches[0];
    this.touching = true;
    this.moved = false;
    const touchStartCopy = this.touchStart;
    window.setTimeout(() => {
      const touchesMatch = this.touchStart === touchStartCopy;
      if (this.touching && touchesMatch && !this.moved) {
        this.moved = true;
        const event = {
          type: _TouchListener.EVENT_LONG_TAP,
          touchStart: this.touchStart,
          touchEvent
        };
        this.eventService.dispatchEvent(event);
      }
    }, 500);
  }
  onTouchMove(touchEvent) {
    if (!this.touching) {
      return;
    }
    const touch = this.getActiveTouch(touchEvent.touches);
    if (!touch) {
      return;
    }
    const eventIsFarAway = !areEventsNear(touch, this.touchStart, 4);
    if (eventIsFarAway) {
      this.moved = true;
    }
  }
  onTouchEnd(touchEvent) {
    if (!this.touching) {
      return;
    }
    if (!this.moved) {
      const event = {
        type: _TouchListener.EVENT_TAP,
        touchStart: this.touchStart
      };
      this.eventService.dispatchEvent(event);
      this.checkForDoubleTap();
    }
    if (this.preventMouseClick && touchEvent.cancelable) {
      touchEvent.preventDefault();
    }
    this.touching = false;
  }
  checkForDoubleTap() {
    const now = (/* @__PURE__ */ new Date()).getTime();
    if (this.lastTapTime && this.lastTapTime > 0) {
      const interval = now - this.lastTapTime;
      if (interval > _TouchListener.DOUBLE_TAP_MILLIS) {
        const event = {
          type: _TouchListener.EVENT_DOUBLE_TAP,
          touchStart: this.touchStart
        };
        this.eventService.dispatchEvent(event);
        this.lastTapTime = null;
      } else {
        this.lastTapTime = now;
      }
    } else {
      this.lastTapTime = now;
    }
  }
  destroy() {
    this.destroyFuncs.forEach((func) => func());
  }
};
_TouchListener.EVENT_TAP = "tap";
_TouchListener.EVENT_DOUBLE_TAP = "doubleTap";
_TouchListener.EVENT_LONG_TAP = "longTap";
_TouchListener.DOUBLE_TAP_MILLIS = 500;
var TouchListener = _TouchListener;

// community-modules/core/src/headerRendering/cells/column/sortIndicatorComp.ts
var _SortIndicatorComp = class _SortIndicatorComp extends Component {
  constructor(skipTemplate) {
    super();
    if (!skipTemplate) {
      this.setTemplate(_SortIndicatorComp.TEMPLATE);
    }
  }
  attachCustomElements(eSortOrder, eSortAsc, eSortDesc, eSortMixed, eSortNone) {
    this.eSortOrder = eSortOrder;
    this.eSortAsc = eSortAsc;
    this.eSortDesc = eSortDesc;
    this.eSortMixed = eSortMixed;
    this.eSortNone = eSortNone;
  }
  setupSort(column, suppressOrder = false) {
    this.column = column;
    this.suppressOrder = suppressOrder;
    this.setupMultiSortIndicator();
    if (!this.column.isSortable() && !this.column.getColDef().showRowGroup) {
      return;
    }
    this.addInIcon("sortAscending", this.eSortAsc, column);
    this.addInIcon("sortDescending", this.eSortDesc, column);
    this.addInIcon("sortUnSort", this.eSortNone, column);
    this.addManagedPropertyListener("unSortIcon", () => this.updateIcons());
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, () => this.updateIcons());
    this.addManagedListener(this.eventService, Events.EVENT_SORT_CHANGED, () => this.onSortChanged());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, () => this.onSortChanged());
    this.onSortChanged();
  }
  addInIcon(iconName, eParent, column) {
    if (eParent == null) {
      return;
    }
    const eIcon = createIconNoSpan(iconName, this.gos, column);
    if (eIcon) {
      eParent.appendChild(eIcon);
    }
  }
  onSortChanged() {
    this.updateIcons();
    if (!this.suppressOrder) {
      this.updateSortOrder();
    }
  }
  updateIcons() {
    const sortDirection = this.sortController.getDisplaySortForColumn(this.column);
    if (this.eSortAsc) {
      const isAscending = sortDirection === "asc";
      setDisplayed(this.eSortAsc, isAscending, { skipAriaHidden: true });
    }
    if (this.eSortDesc) {
      const isDescending = sortDirection === "desc";
      setDisplayed(this.eSortDesc, isDescending, { skipAriaHidden: true });
    }
    if (this.eSortNone) {
      const alwaysHideNoSort = !this.column.getColDef().unSortIcon && !this.gos.get("unSortIcon");
      const isNone = sortDirection === null || sortDirection === void 0;
      setDisplayed(this.eSortNone, !alwaysHideNoSort && isNone, { skipAriaHidden: true });
    }
  }
  setupMultiSortIndicator() {
    this.addInIcon("sortUnSort", this.eSortMixed, this.column);
    const isColumnShowingRowGroup = this.column.getColDef().showRowGroup;
    const areGroupsCoupled = this.gos.isColumnsSortingCoupledToGroup();
    if (areGroupsCoupled && isColumnShowingRowGroup) {
      this.addManagedListener(this.eventService, Events.EVENT_SORT_CHANGED, () => this.updateMultiSortIndicator());
      this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, () => this.updateMultiSortIndicator());
      this.updateMultiSortIndicator();
    }
  }
  updateMultiSortIndicator() {
    if (this.eSortMixed) {
      const isMixedSort = this.sortController.getDisplaySortForColumn(this.column) === "mixed";
      setDisplayed(this.eSortMixed, isMixedSort, { skipAriaHidden: true });
    }
  }
  // we listen here for global sort events, NOT column sort events, as we want to do this
  // when sorting has been set on all column (if we listened just for our col (where we
  // set the asc / desc icons) then it's possible other cols are yet to get their sorting state.
  updateSortOrder() {
    var _a;
    if (!this.eSortOrder) {
      return;
    }
    const allColumnsWithSorting = this.sortController.getColumnsWithSortingOrdered();
    const indexThisCol = (_a = this.sortController.getDisplaySortIndexForColumn(this.column)) != null ? _a : -1;
    const moreThanOneColSorting = allColumnsWithSorting.some((col) => {
      var _a2;
      return (_a2 = this.sortController.getDisplaySortIndexForColumn(col)) != null ? _a2 : -1 >= 1;
    });
    const showIndex = indexThisCol >= 0 && moreThanOneColSorting;
    setDisplayed(this.eSortOrder, showIndex, { skipAriaHidden: true });
    if (indexThisCol >= 0) {
      this.eSortOrder.textContent = (indexThisCol + 1).toString();
    } else {
      clearElement(this.eSortOrder);
    }
  }
};
_SortIndicatorComp.TEMPLATE = /* html */
`<span class="ag-sort-indicator-container">
            <span ref="eSortOrder" class="ag-sort-indicator-icon ag-sort-order ag-hidden" aria-hidden="true"></span>
            <span ref="eSortAsc" class="ag-sort-indicator-icon ag-sort-ascending-icon ag-hidden" aria-hidden="true"></span>
            <span ref="eSortDesc" class="ag-sort-indicator-icon ag-sort-descending-icon ag-hidden" aria-hidden="true"></span>
            <span ref="eSortMixed" class="ag-sort-indicator-icon ag-sort-mixed-icon ag-hidden" aria-hidden="true"></span>
            <span ref="eSortNone" class="ag-sort-indicator-icon ag-sort-none-icon ag-hidden" aria-hidden="true"></span>
        </span>`;
__decorateClass([
  RefSelector("eSortOrder")
], _SortIndicatorComp.prototype, "eSortOrder", 2);
__decorateClass([
  RefSelector("eSortAsc")
], _SortIndicatorComp.prototype, "eSortAsc", 2);
__decorateClass([
  RefSelector("eSortDesc")
], _SortIndicatorComp.prototype, "eSortDesc", 2);
__decorateClass([
  RefSelector("eSortMixed")
], _SortIndicatorComp.prototype, "eSortMixed", 2);
__decorateClass([
  RefSelector("eSortNone")
], _SortIndicatorComp.prototype, "eSortNone", 2);
__decorateClass([
  Autowired("columnModel")
], _SortIndicatorComp.prototype, "columnModel", 2);
__decorateClass([
  Autowired("sortController")
], _SortIndicatorComp.prototype, "sortController", 2);
var SortIndicatorComp = _SortIndicatorComp;

// community-modules/core/src/headerRendering/cells/column/headerComp.ts
var _HeaderComp = class _HeaderComp extends Component {
  constructor() {
    super(...arguments);
    this.lastMovingChanged = 0;
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
  refresh(params) {
    const oldParams = this.params;
    this.params = params;
    if (this.workOutTemplate() != this.currentTemplate || this.workOutShowMenu() != this.currentShowMenu || this.workOutSort() != this.currentSort || this.shouldSuppressMenuHide() != this.currentSuppressMenuHide || oldParams.enableFilterButton != params.enableFilterButton || oldParams.enableFilterIcon != params.enableFilterIcon) {
      return false;
    }
    this.setDisplayName(params);
    return true;
  }
  workOutTemplate() {
    var _a;
    let template = (_a = this.params.template) != null ? _a : _HeaderComp.TEMPLATE;
    template = template && template.trim ? template.trim() : template;
    return template;
  }
  init(params) {
    this.params = params;
    this.currentTemplate = this.workOutTemplate();
    this.setTemplate(this.currentTemplate);
    this.setupTap();
    this.setMenu();
    this.setupSort();
    this.setupFilterIcon();
    this.setupFilterButton();
    this.setDisplayName(params);
  }
  setDisplayName(params) {
    if (this.currentDisplayName != params.displayName) {
      this.currentDisplayName = params.displayName;
      const displayNameSanitised = escapeString(this.currentDisplayName, true);
      if (this.eText) {
        this.eText.textContent = displayNameSanitised;
      }
    }
  }
  addInIcon(iconName, eParent, column) {
    if (eParent == null) {
      return;
    }
    const eIcon = createIconNoSpan(iconName, this.gos, column);
    if (eIcon) {
      eParent.appendChild(eIcon);
    }
  }
  setupTap() {
    const { gos } = this;
    if (gos.get("suppressTouch")) {
      return;
    }
    const touchListener = new TouchListener(this.getGui(), true);
    const suppressMenuHide = this.shouldSuppressMenuHide();
    const tapMenuButton = suppressMenuHide && exists(this.eMenu);
    const menuTouchListener = tapMenuButton ? new TouchListener(this.eMenu, true) : touchListener;
    if (this.params.enableMenu) {
      const eventType = tapMenuButton ? "EVENT_TAP" : "EVENT_LONG_TAP";
      const showMenuFn = (event) => this.params.showColumnMenuAfterMouseClick(event.touchStart);
      this.addManagedListener(menuTouchListener, TouchListener[eventType], showMenuFn);
    }
    if (this.params.enableSorting) {
      const tapListener = (event) => {
        var _a, _b;
        const target = event.touchStart.target;
        if (suppressMenuHide && (((_a = this.eMenu) == null ? void 0 : _a.contains(target)) || ((_b = this.eFilterButton) == null ? void 0 : _b.contains(target)))) {
          return;
        }
        this.sortController.progressSort(this.params.column, false, "uiColumnSorted");
      };
      this.addManagedListener(touchListener, TouchListener.EVENT_TAP, tapListener);
    }
    if (this.params.enableFilterButton) {
      const filterButtonTouchListener = new TouchListener(this.eFilterButton, true);
      this.addManagedListener(filterButtonTouchListener, "tap", () => this.params.showFilter(this.eFilterButton));
      this.addDestroyFunc(() => filterButtonTouchListener.destroy());
    }
    this.addDestroyFunc(() => touchListener.destroy());
    if (tapMenuButton) {
      this.addDestroyFunc(() => menuTouchListener.destroy());
    }
  }
  workOutShowMenu() {
    return this.params.enableMenu && this.menuService.isHeaderMenuButtonEnabled();
  }
  shouldSuppressMenuHide() {
    return this.menuService.isHeaderMenuButtonAlwaysShowEnabled();
  }
  setMenu() {
    if (!this.eMenu) {
      return;
    }
    this.currentShowMenu = this.workOutShowMenu();
    if (!this.currentShowMenu) {
      removeFromParent(this.eMenu);
      this.eMenu = void 0;
      return;
    }
    const isLegacyMenu = this.menuService.isLegacyMenuEnabled();
    this.addInIcon(isLegacyMenu ? "menu" : "menuAlt", this.eMenu, this.params.column);
    this.eMenu.classList.toggle("ag-header-menu-icon", !isLegacyMenu);
    this.currentSuppressMenuHide = this.shouldSuppressMenuHide();
    this.addManagedListener(this.eMenu, "click", () => this.params.showColumnMenu(this.eMenu));
    this.eMenu.classList.toggle("ag-header-menu-always-show", this.currentSuppressMenuHide);
  }
  onMenuKeyboardShortcut(isFilterShortcut) {
    var _a, _b, _c, _d;
    const { column } = this.params;
    const isLegacyMenuEnabled = this.menuService.isLegacyMenuEnabled();
    if (isFilterShortcut && !isLegacyMenuEnabled) {
      if (this.menuService.isFilterMenuInHeaderEnabled(column)) {
        this.params.showFilter((_b = (_a = this.eFilterButton) != null ? _a : this.eMenu) != null ? _b : this.getGui());
        return true;
      }
    } else if (this.params.enableMenu) {
      this.params.showColumnMenu((_d = (_c = this.eMenu) != null ? _c : this.eFilterButton) != null ? _d : this.getGui());
      return true;
    }
    return false;
  }
  workOutSort() {
    return this.params.enableSorting;
  }
  setupSort() {
    this.currentSort = this.params.enableSorting;
    if (!this.eSortIndicator) {
      this.eSortIndicator = this.context.createBean(new SortIndicatorComp(true));
      this.eSortIndicator.attachCustomElements(
        this.eSortOrder,
        this.eSortAsc,
        this.eSortDesc,
        this.eSortMixed,
        this.eSortNone
      );
    }
    this.eSortIndicator.setupSort(this.params.column);
    if (!this.currentSort) {
      return;
    }
    this.addManagedListener(this.params.column, Column.EVENT_MOVING_CHANGED, () => {
      this.lastMovingChanged = (/* @__PURE__ */ new Date()).getTime();
    });
    if (this.eLabel) {
      this.addManagedListener(this.eLabel, "click", (event) => {
        const moving = this.params.column.isMoving();
        const nowTime = (/* @__PURE__ */ new Date()).getTime();
        const movedRecently = nowTime - this.lastMovingChanged < 50;
        const columnMoving = moving || movedRecently;
        if (!columnMoving) {
          const sortUsingCtrl = this.gos.get("multiSortKey") === "ctrl";
          const multiSort = sortUsingCtrl ? event.ctrlKey || event.metaKey : event.shiftKey;
          this.params.progressSort(multiSort);
        }
      });
    }
    const onSortingChanged = () => {
      this.addOrRemoveCssClass("ag-header-cell-sorted-asc", this.params.column.isSortAscending());
      this.addOrRemoveCssClass("ag-header-cell-sorted-desc", this.params.column.isSortDescending());
      this.addOrRemoveCssClass("ag-header-cell-sorted-none", this.params.column.isSortNone());
      if (this.params.column.getColDef().showRowGroup) {
        const sourceColumns = this.columnModel.getSourceColumnsForGroupColumn(this.params.column);
        const sortDirectionsMatch = sourceColumns == null ? void 0 : sourceColumns.every((sourceCol) => this.params.column.getSort() == sourceCol.getSort());
        const isMultiSorting = !sortDirectionsMatch;
        this.addOrRemoveCssClass("ag-header-cell-sorted-mixed", isMultiSorting);
      }
    };
    this.addManagedListener(this.eventService, Events.EVENT_SORT_CHANGED, onSortingChanged);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, onSortingChanged);
  }
  setupFilterIcon() {
    if (!this.eFilter) {
      return;
    }
    this.configureFilter(this.params.enableFilterIcon, this.eFilter, this.onFilterChangedIcon.bind(this));
  }
  setupFilterButton() {
    if (!this.eFilterButton) {
      return;
    }
    const configured = this.configureFilter(
      this.params.enableFilterButton,
      this.eFilterButton,
      this.onFilterChangedButton.bind(this)
    );
    if (configured) {
      this.addManagedListener(this.eFilterButton, "click", () => this.params.showFilter(this.eFilterButton));
    } else {
      this.eFilterButton = void 0;
    }
  }
  configureFilter(enabled, element, filterChangedCallback) {
    if (!enabled) {
      removeFromParent(element);
      return false;
    }
    const { column } = this.params;
    this.addInIcon("filter", element, column);
    this.addManagedListener(column, Column.EVENT_FILTER_CHANGED, filterChangedCallback);
    filterChangedCallback();
    return true;
  }
  onFilterChangedIcon() {
    const filterPresent = this.params.column.isFilterActive();
    setDisplayed(this.eFilter, filterPresent, { skipAriaHidden: true });
  }
  onFilterChangedButton() {
    const filterPresent = this.params.column.isFilterActive();
    this.eFilterButton.classList.toggle("ag-filter-active", filterPresent);
  }
  getAnchorElementForMenu(isFilter) {
    var _a, _b, _c, _d;
    if (isFilter) {
      return (_b = (_a = this.eFilterButton) != null ? _a : this.eMenu) != null ? _b : this.getGui();
    }
    return (_d = (_c = this.eMenu) != null ? _c : this.eFilterButton) != null ? _d : this.getGui();
  }
};
_HeaderComp.TEMPLATE = /* html */
`<div class="ag-cell-label-container" role="presentation">
            <span ref="eMenu" class="ag-header-icon ag-header-cell-menu-button" aria-hidden="true"></span>
            <span ref="eFilterButton" class="ag-header-icon ag-header-cell-filter-button" aria-hidden="true"></span>
            <div ref="eLabel" class="ag-header-cell-label" role="presentation">
                <span ref="eText" class="ag-header-cell-text"></span>
                <span ref="eFilter" class="ag-header-icon ag-header-label-icon ag-filter-icon" aria-hidden="true"></span>
                <ag-sort-indicator ref="eSortIndicator"></ag-sort-indicator>
            </div>
        </div>`;
__decorateClass([
  Autowired("sortController")
], _HeaderComp.prototype, "sortController", 2);
__decorateClass([
  Autowired("menuService")
], _HeaderComp.prototype, "menuService", 2);
__decorateClass([
  Autowired("columnModel")
], _HeaderComp.prototype, "columnModel", 2);
__decorateClass([
  RefSelector("eFilter")
], _HeaderComp.prototype, "eFilter", 2);
__decorateClass([
  RefSelector("eFilterButton")
], _HeaderComp.prototype, "eFilterButton", 2);
__decorateClass([
  RefSelector("eSortIndicator")
], _HeaderComp.prototype, "eSortIndicator", 2);
__decorateClass([
  RefSelector("eMenu")
], _HeaderComp.prototype, "eMenu", 2);
__decorateClass([
  RefSelector("eLabel")
], _HeaderComp.prototype, "eLabel", 2);
__decorateClass([
  RefSelector("eText")
], _HeaderComp.prototype, "eText", 2);
__decorateClass([
  RefSelector("eSortOrder")
], _HeaderComp.prototype, "eSortOrder", 2);
__decorateClass([
  RefSelector("eSortAsc")
], _HeaderComp.prototype, "eSortAsc", 2);
__decorateClass([
  RefSelector("eSortDesc")
], _HeaderComp.prototype, "eSortDesc", 2);
__decorateClass([
  RefSelector("eSortMixed")
], _HeaderComp.prototype, "eSortMixed", 2);
__decorateClass([
  RefSelector("eSortNone")
], _HeaderComp.prototype, "eSortNone", 2);
var HeaderComp = _HeaderComp;

// community-modules/core/src/headerRendering/cells/columnGroup/headerGroupComp.ts
var _HeaderGroupComp = class _HeaderGroupComp extends Component {
  constructor() {
    super(_HeaderGroupComp.TEMPLATE);
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
  init(params) {
    this.params = params;
    this.checkWarnings();
    this.setupLabel();
    this.addGroupExpandIcon();
    this.setupExpandIcons();
  }
  checkWarnings() {
    const paramsAny = this.params;
    if (paramsAny.template) {
      warnOnce(`A template was provided for Header Group Comp - templates are only supported for Header Comps (not groups)`);
    }
  }
  setupExpandIcons() {
    this.addInIcon("columnGroupOpened", "agOpened");
    this.addInIcon("columnGroupClosed", "agClosed");
    const expandAction = (event) => {
      if (isStopPropagationForAgGrid(event)) {
        return;
      }
      const newExpandedValue = !this.params.columnGroup.isExpanded();
      this.columnModel.setColumnGroupOpened(this.params.columnGroup.getProvidedColumnGroup(), newExpandedValue, "uiColumnExpanded");
    };
    this.addTouchAndClickListeners(this.eCloseIcon, expandAction);
    this.addTouchAndClickListeners(this.eOpenIcon, expandAction);
    const stopPropagationAction = (event) => {
      stopPropagationForAgGrid(event);
    };
    this.addManagedListener(this.eCloseIcon, "dblclick", stopPropagationAction);
    this.addManagedListener(this.eOpenIcon, "dblclick", stopPropagationAction);
    this.addManagedListener(this.getGui(), "dblclick", expandAction);
    this.updateIconVisibility();
    const providedColumnGroup = this.params.columnGroup.getProvidedColumnGroup();
    this.addManagedListener(providedColumnGroup, ProvidedColumnGroup.EVENT_EXPANDED_CHANGED, this.updateIconVisibility.bind(this));
    this.addManagedListener(providedColumnGroup, ProvidedColumnGroup.EVENT_EXPANDABLE_CHANGED, this.updateIconVisibility.bind(this));
  }
  addTouchAndClickListeners(eElement, action) {
    const touchListener = new TouchListener(eElement, true);
    this.addManagedListener(touchListener, TouchListener.EVENT_TAP, action);
    this.addDestroyFunc(() => touchListener.destroy());
    this.addManagedListener(eElement, "click", action);
  }
  updateIconVisibility() {
    const columnGroup = this.params.columnGroup;
    if (columnGroup.isExpandable()) {
      const expanded = this.params.columnGroup.isExpanded();
      setDisplayed(this.eOpenIcon, expanded);
      setDisplayed(this.eCloseIcon, !expanded);
    } else {
      setDisplayed(this.eOpenIcon, false);
      setDisplayed(this.eCloseIcon, false);
    }
  }
  addInIcon(iconName, refName) {
    const eIcon = createIconNoSpan(iconName, this.gos, null);
    if (eIcon) {
      this.getRefElement(refName).appendChild(eIcon);
    }
  }
  addGroupExpandIcon() {
    if (!this.params.columnGroup.isExpandable()) {
      setDisplayed(this.eOpenIcon, false);
      setDisplayed(this.eCloseIcon, false);
      return;
    }
  }
  setupLabel() {
    var _a;
    const { displayName, columnGroup } = this.params;
    if (exists(displayName)) {
      const displayNameSanitised = escapeString(displayName, true);
      this.getRefElement("agLabel").textContent = displayNameSanitised;
    }
    this.addOrRemoveCssClass("ag-sticky-label", !((_a = columnGroup.getColGroupDef()) == null ? void 0 : _a.suppressStickyLabel));
  }
};
_HeaderGroupComp.TEMPLATE = /* html */
`<div class="ag-header-group-cell-label" ref="agContainer" role="presentation">
            <span ref="agLabel" class="ag-header-group-text" role="presentation"></span>
            <span ref="agOpened" class="ag-header-icon ag-header-expand-icon ag-header-expand-icon-expanded"></span>
            <span ref="agClosed" class="ag-header-icon ag-header-expand-icon ag-header-expand-icon-collapsed"></span>
        </div>`;
__decorateClass([
  Autowired("columnModel")
], _HeaderGroupComp.prototype, "columnModel", 2);
__decorateClass([
  RefSelector("agOpened")
], _HeaderGroupComp.prototype, "eOpenIcon", 2);
__decorateClass([
  RefSelector("agClosed")
], _HeaderGroupComp.prototype, "eCloseIcon", 2);
var HeaderGroupComp = _HeaderGroupComp;

// community-modules/core/src/widgets/popupComponent.ts
var PopupComponent = class extends Component {
  isPopup() {
    return true;
  }
  setParentComponent(container) {
    container.addCssClass("ag-has-popup");
    super.setParentComponent(container);
  }
  destroy() {
    const parentComp = this.parentComponent;
    const hasParent = parentComp && parentComp.isAlive();
    if (hasParent) {
      parentComp.getGui().classList.remove("ag-has-popup");
    }
    super.destroy();
  }
};

// community-modules/core/src/rendering/cellEditors/largeTextCellEditor.ts
var _LargeTextCellEditor = class _LargeTextCellEditor extends PopupComponent {
  constructor() {
    super(_LargeTextCellEditor.TEMPLATE);
  }
  init(params) {
    this.params = params;
    this.focusAfterAttached = params.cellStartedEdit;
    this.eTextArea.setMaxLength(params.maxLength || 200).setCols(params.cols || 60).setRows(params.rows || 10);
    if (exists(params.value, true)) {
      this.eTextArea.setValue(params.value.toString(), true);
    }
    this.addGuiEventListener("keydown", this.onKeyDown.bind(this));
    this.activateTabIndex();
  }
  onKeyDown(event) {
    const key = event.key;
    if (key === KeyCode.LEFT || key === KeyCode.UP || key === KeyCode.RIGHT || key === KeyCode.DOWN || event.shiftKey && key === KeyCode.ENTER) {
      event.stopPropagation();
    }
  }
  afterGuiAttached() {
    const translate = this.localeService.getLocaleTextFunc();
    this.eTextArea.setInputAriaLabel(translate("ariaInputEditor", "Input Editor"));
    if (this.focusAfterAttached) {
      this.eTextArea.getFocusableElement().focus();
    }
  }
  getValue() {
    const value = this.eTextArea.getValue();
    if (!exists(value) && !exists(this.params.value)) {
      return this.params.value;
    }
    return this.params.parseValue(value);
  }
};
_LargeTextCellEditor.TEMPLATE = /* html */
`<div class="ag-large-text">
            <ag-input-text-area ref="eTextArea" class="ag-large-text-input"></ag-input-text-area>
        </div>`;
__decorateClass([
  RefSelector("eTextArea")
], _LargeTextCellEditor.prototype, "eTextArea", 2);
var LargeTextCellEditor = _LargeTextCellEditor;

// community-modules/core/src/rendering/cellEditors/selectCellEditor.ts
var SelectCellEditor = class extends PopupComponent {
  constructor() {
    super(
      /* html */
      `<div class="ag-cell-edit-wrapper">
                <ag-select class="ag-cell-editor" ref="eSelect"></ag-select>
            </div>`
    );
    this.startedByEnter = false;
  }
  init(params) {
    this.focusAfterAttached = params.cellStartedEdit;
    const { eSelect, valueService, gos } = this;
    const { values: values2, value, eventKey } = params;
    if (missing(values2)) {
      console.warn("AG Grid: no values found for select cellEditor");
      return;
    }
    this.startedByEnter = eventKey != null ? eventKey === KeyCode.ENTER : false;
    let hasValue = false;
    values2.forEach((currentValue) => {
      const option = { value: currentValue };
      const valueFormatted = valueService.formatValue(params.column, null, currentValue);
      const valueFormattedExits = valueFormatted !== null && valueFormatted !== void 0;
      option.text = valueFormattedExits ? valueFormatted : currentValue;
      eSelect.addOption(option);
      hasValue = hasValue || value === currentValue;
    });
    if (hasValue) {
      eSelect.setValue(params.value, true);
    } else if (params.values.length) {
      eSelect.setValue(params.values[0], true);
    }
    const { valueListGap, valueListMaxWidth, valueListMaxHeight } = params;
    if (valueListGap != null) {
      eSelect.setPickerGap(valueListGap);
    }
    if (valueListMaxHeight != null) {
      eSelect.setPickerMaxHeight(valueListMaxHeight);
    }
    if (valueListMaxWidth != null) {
      eSelect.setPickerMaxWidth(valueListMaxWidth);
    }
    if (gos.get("editType") !== "fullRow") {
      this.addManagedListener(this.eSelect, AgSelect.EVENT_ITEM_SELECTED, () => params.stopEditing());
    }
  }
  afterGuiAttached() {
    if (this.focusAfterAttached) {
      this.eSelect.getFocusableElement().focus();
    }
    if (this.startedByEnter) {
      setTimeout(() => {
        if (this.isAlive()) {
          this.eSelect.showPicker();
        }
      });
    }
  }
  focusIn() {
    this.eSelect.getFocusableElement().focus();
  }
  getValue() {
    return this.eSelect.getValue();
  }
  isPopup() {
    return false;
  }
};
__decorateClass([
  Autowired("valueService")
], SelectCellEditor.prototype, "valueService", 2);
__decorateClass([
  RefSelector("eSelect")
], SelectCellEditor.prototype, "eSelect", 2);

// community-modules/core/src/rendering/cellEditors/simpleCellEditor.ts
var SimpleCellEditor = class extends PopupComponent {
  constructor(cellEditorInput) {
    super(
      /* html */
      `
            <div class="ag-cell-edit-wrapper">
                ${cellEditorInput.getTemplate()}
            </div>`
    );
    this.cellEditorInput = cellEditorInput;
  }
  init(params) {
    this.params = params;
    const eInput = this.eInput;
    this.cellEditorInput.init(eInput, params);
    let startValue;
    if (params.cellStartedEdit) {
      this.focusAfterAttached = true;
      const eventKey = params.eventKey;
      if (eventKey === KeyCode.BACKSPACE || params.eventKey === KeyCode.DELETE) {
        startValue = "";
      } else if (eventKey && eventKey.length === 1) {
        startValue = eventKey;
      } else {
        startValue = this.cellEditorInput.getStartValue();
        if (eventKey !== KeyCode.F2) {
          this.highlightAllOnFocus = true;
        }
      }
    } else {
      this.focusAfterAttached = false;
      startValue = this.cellEditorInput.getStartValue();
    }
    if (startValue != null) {
      eInput.setStartValue(startValue);
    }
    this.addManagedListener(eInput.getGui(), "keydown", (event) => {
      const { key } = event;
      if (key === KeyCode.PAGE_UP || key === KeyCode.PAGE_DOWN) {
        event.preventDefault();
      }
    });
  }
  afterGuiAttached() {
    var _a, _b;
    const translate = this.localeService.getLocaleTextFunc();
    const eInput = this.eInput;
    eInput.setInputAriaLabel(translate("ariaInputEditor", "Input Editor"));
    if (!this.focusAfterAttached) {
      return;
    }
    if (!isBrowserSafari()) {
      eInput.getFocusableElement().focus();
    }
    const inputEl = eInput.getInputElement();
    if (this.highlightAllOnFocus) {
      inputEl.select();
    } else {
      (_b = (_a = this.cellEditorInput).setCaret) == null ? void 0 : _b.call(_a);
    }
  }
  // gets called when tabbing through cells and in full row edit mode
  focusIn() {
    const eInput = this.eInput;
    const focusEl = eInput.getFocusableElement();
    const inputEl = eInput.getInputElement();
    focusEl.focus();
    inputEl.select();
  }
  getValue() {
    return this.cellEditorInput.getValue();
  }
  isPopup() {
    return false;
  }
};
__decorateClass([
  RefSelector("eInput")
], SimpleCellEditor.prototype, "eInput", 2);

// community-modules/core/src/rendering/cellEditors/textCellEditor.ts
var TextCellEditorInput = class {
  getTemplate() {
    return (
      /* html */
      `<ag-input-text-field class="ag-cell-editor" ref="eInput"></ag-input-text-field>`
    );
  }
  init(eInput, params) {
    this.eInput = eInput;
    this.params = params;
    if (params.maxLength != null) {
      eInput.setMaxLength(params.maxLength);
    }
  }
  getValue() {
    const value = this.eInput.getValue();
    if (!exists(value) && !exists(this.params.value)) {
      return this.params.value;
    }
    return this.params.parseValue(value);
  }
  getStartValue() {
    const formatValue = this.params.useFormatter || this.params.column.getColDef().refData;
    return formatValue ? this.params.formatValue(this.params.value) : this.params.value;
  }
  setCaret() {
    const value = this.eInput.getValue();
    const len = exists(value) && value.length || 0;
    if (len) {
      this.eInput.getInputElement().setSelectionRange(len, len);
    }
  }
};
var TextCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(new TextCellEditorInput());
  }
};

// community-modules/core/src/rendering/cellRenderers/animateShowChangeCellRenderer.ts
var ARROW_UP = "\u2191";
var ARROW_DOWN = "\u2193";
var AnimateShowChangeCellRenderer = class extends Component {
  constructor() {
    super();
    this.refreshCount = 0;
    const template = document.createElement("span");
    const delta = document.createElement("span");
    delta.setAttribute("class", "ag-value-change-delta");
    const value = document.createElement("span");
    value.setAttribute("class", "ag-value-change-value");
    template.appendChild(delta);
    template.appendChild(value);
    this.setTemplateFromElement(template);
  }
  init(params) {
    this.eValue = this.queryForHtmlElement(".ag-value-change-value");
    this.eDelta = this.queryForHtmlElement(".ag-value-change-delta");
    this.refresh(params, true);
  }
  showDelta(params, delta) {
    const absDelta = Math.abs(delta);
    const valueFormatted = params.formatValue(absDelta);
    const valueToUse = exists(valueFormatted) ? valueFormatted : absDelta;
    const deltaUp = delta >= 0;
    if (deltaUp) {
      this.eDelta.textContent = ARROW_UP + valueToUse;
    } else {
      this.eDelta.textContent = ARROW_DOWN + valueToUse;
    }
    this.eDelta.classList.toggle("ag-value-change-delta-up", deltaUp);
    this.eDelta.classList.toggle("ag-value-change-delta-down", !deltaUp);
  }
  setTimerToRemoveDelta() {
    this.refreshCount++;
    const refreshCountCopy = this.refreshCount;
    this.getFrameworkOverrides().wrapIncoming(() => {
      window.setTimeout(() => {
        if (refreshCountCopy === this.refreshCount) {
          this.hideDeltaValue();
        }
      }, 2e3);
    });
  }
  hideDeltaValue() {
    this.eValue.classList.remove("ag-value-change-value-highlight");
    clearElement(this.eDelta);
  }
  refresh(params, isInitialRender = false) {
    const value = params.value;
    if (value === this.lastValue) {
      return false;
    }
    if (exists(params.valueFormatted)) {
      this.eValue.textContent = params.valueFormatted;
    } else if (exists(params.value)) {
      this.eValue.textContent = value;
    } else {
      clearElement(this.eValue);
    }
    if (this.filterManager.isSuppressFlashingCellsBecauseFiltering()) {
      return false;
    }
    if (typeof value === "number" && typeof this.lastValue === "number") {
      const delta = value - this.lastValue;
      this.showDelta(params, delta);
    }
    if (this.lastValue) {
      this.eValue.classList.add("ag-value-change-value-highlight");
    }
    if (!isInitialRender) {
      this.setTimerToRemoveDelta();
    }
    this.lastValue = value;
    return true;
  }
};
__decorateClass([
  Autowired("filterManager")
], AnimateShowChangeCellRenderer.prototype, "filterManager", 2);

// community-modules/core/src/rendering/cellRenderers/animateSlideCellRenderer.ts
var AnimateSlideCellRenderer = class extends Component {
  constructor() {
    super();
    this.refreshCount = 0;
    const template = document.createElement("span");
    const slide = document.createElement("span");
    slide.setAttribute("class", "ag-value-slide-current");
    template.appendChild(slide);
    this.setTemplateFromElement(template);
    this.eCurrent = this.queryForHtmlElement(".ag-value-slide-current");
  }
  init(params) {
    this.refresh(params, true);
  }
  addSlideAnimation() {
    this.refreshCount++;
    const refreshCountCopy = this.refreshCount;
    if (this.ePrevious) {
      this.getGui().removeChild(this.ePrevious);
    }
    const prevElement = document.createElement("span");
    prevElement.setAttribute("class", "ag-value-slide-previous ag-value-slide-out");
    this.ePrevious = prevElement;
    this.ePrevious.textContent = this.eCurrent.textContent;
    this.getGui().insertBefore(this.ePrevious, this.eCurrent);
    this.getFrameworkOverrides().wrapIncoming(() => {
      window.setTimeout(() => {
        if (refreshCountCopy !== this.refreshCount) {
          return;
        }
        this.ePrevious.classList.add("ag-value-slide-out-end");
      }, 50);
      window.setTimeout(() => {
        if (refreshCountCopy !== this.refreshCount) {
          return;
        }
        this.getGui().removeChild(this.ePrevious);
        this.ePrevious = null;
      }, 3e3);
    });
  }
  refresh(params, isInitialRender = false) {
    let value = params.value;
    if (missing(value)) {
      value = "";
    }
    if (value === this.lastValue) {
      return false;
    }
    if (this.filterManager.isSuppressFlashingCellsBecauseFiltering()) {
      return false;
    }
    if (!isInitialRender) {
      this.addSlideAnimation();
    }
    this.lastValue = value;
    if (exists(params.valueFormatted)) {
      this.eCurrent.textContent = params.valueFormatted;
    } else if (exists(params.value)) {
      this.eCurrent.textContent = value;
    } else {
      clearElement(this.eCurrent);
    }
    return true;
  }
};
__decorateClass([
  Autowired("filterManager")
], AnimateSlideCellRenderer.prototype, "filterManager", 2);

// community-modules/core/src/entities/rowNode.ts
var _RowNode = class _RowNode {
  constructor(beans) {
    /** The current row index. If the row is filtered out or in a collapsed group, this value will be `null`. */
    this.rowIndex = null;
    /** The key for the group eg Ireland, UK, USA */
    this.key = null;
    /** Children mapped by the pivot columns. */
    this.childrenMapped = {};
    /**
     * This will be `true` if it has a rowIndex assigned, otherwise `false`.
     */
    this.displayed = false;
    /** The row top position in pixels. */
    this.rowTop = null;
    /** The top pixel for this row last time, makes sense if data set was ordered or filtered,
     * it is used so new rows can animate in from their old position. */
    this.oldRowTop = null;
    /** `true` by default - can be overridden via gridOptions.isRowSelectable(rowNode) */
    this.selectable = true;
    /** Used by sorting service - to give deterministic sort to groups. Previously we
     * just id for this, however id is a string and had slower sorting compared to numbers. */
    this.__objectId = _RowNode.OBJECT_ID_SEQUENCE++;
    /** When one or more Columns are using autoHeight, this keeps track of height of each autoHeight Cell,
     * indexed by the Column ID. */
    this.__autoHeights = {};
    /** `true` when nodes with the same id are being removed and added as part of the same batch transaction */
    this.alreadyRendered = false;
    this.highlighted = null;
    this.hovered = false;
    this.selected = false;
    this.beans = beans;
  }
  /**
   * Replaces the data on the `rowNode`. When this method is called, the grid will refresh the entire rendered row if it is displayed.
   */
  setData(data) {
    this.setDataCommon(data, false);
  }
  // similar to setRowData, however it is expected that the data is the same data item. this
  // is intended to be used with Redux type stores, where the whole data can be changed. we are
  // guaranteed that the data is the same entity (so grid doesn't need to worry about the id of the
  // underlying data changing, hence doesn't need to worry about selection). the grid, upon receiving
  // dataChanged event, will refresh the cells rather than rip them all out (so user can show transitions).
  /**
   * Updates the data on the `rowNode`. When this method is called, the grid will refresh the entire rendered row if it is displayed.
   */
  updateData(data) {
    this.setDataCommon(data, true);
  }
  setDataCommon(data, update) {
    const oldData = this.data;
    this.data = data;
    this.beans.valueCache.onDataChanged();
    this.updateDataOnDetailNode();
    this.checkRowSelectable();
    this.resetQuickFilterAggregateText();
    const event = this.createDataChangedEvent(data, oldData, update);
    this.dispatchLocalEvent(event);
  }
  // when we are doing master / detail, the detail node is lazy created, but then kept around.
  // so if we show / hide the detail, the same detail rowNode is used. so we need to keep the data
  // in sync, otherwise expand/collapse of the detail would still show the old values.
  updateDataOnDetailNode() {
    if (this.detailNode) {
      this.detailNode.data = this.data;
    }
  }
  createDataChangedEvent(newData, oldData, update) {
    return {
      type: _RowNode.EVENT_DATA_CHANGED,
      node: this,
      oldData,
      newData,
      update
    };
  }
  createLocalRowEvent(type) {
    return {
      type,
      node: this
    };
  }
  getRowIndexString() {
    if (this.rowPinned === "top") {
      return "t-" + this.rowIndex;
    }
    if (this.rowPinned === "bottom") {
      return "b-" + this.rowIndex;
    }
    return this.rowIndex.toString();
  }
  createDaemonNode() {
    const oldNode = new _RowNode(this.beans);
    oldNode.id = this.id;
    oldNode.data = this.data;
    oldNode.__daemon = true;
    oldNode.selected = this.selected;
    oldNode.level = this.level;
    return oldNode;
  }
  setDataAndId(data, id) {
    const oldNode = exists(this.id) ? this.createDaemonNode() : null;
    const oldData = this.data;
    this.data = data;
    this.updateDataOnDetailNode();
    this.setId(id);
    this.checkRowSelectable();
    this.beans.selectionService.syncInRowNode(this, oldNode);
    const event = this.createDataChangedEvent(data, oldData, false);
    this.dispatchLocalEvent(event);
  }
  checkRowSelectable() {
    const isRowSelectableFunc = this.beans.gos.get("isRowSelectable");
    this.setRowSelectable(isRowSelectableFunc ? isRowSelectableFunc(this) : true);
  }
  setRowSelectable(newVal, suppressSelectionUpdate) {
    if (this.selectable !== newVal) {
      this.selectable = newVal;
      if (this.eventService) {
        this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_SELECTABLE_CHANGED));
      }
      if (suppressSelectionUpdate) {
        return;
      }
      const isGroupSelectsChildren = this.beans.gos.get("groupSelectsChildren");
      if (isGroupSelectsChildren) {
        const selected = this.calculateSelectedFromChildren();
        this.setSelectedParams({
          newValue: selected != null ? selected : false,
          source: "selectableChanged"
        });
        return;
      }
      if (this.isSelected() && !this.selectable) {
        this.setSelectedParams({
          newValue: false,
          source: "selectableChanged"
        });
      }
    }
  }
  setId(id) {
    const getRowIdFunc = this.beans.gos.getCallback("getRowId");
    if (getRowIdFunc) {
      if (this.data) {
        const parentKeys = this.getGroupKeys(true);
        this.id = getRowIdFunc({
          data: this.data,
          parentKeys: parentKeys.length > 0 ? parentKeys : void 0,
          level: this.level
        });
        if (this.id !== null && typeof this.id === "string" && this.id.startsWith(_RowNode.ID_PREFIX_ROW_GROUP)) {
          console.error(`AG Grid: Row IDs cannot start with ${_RowNode.ID_PREFIX_ROW_GROUP}, this is a reserved prefix for AG Grid's row grouping feature.`);
        }
        if (this.id !== null && typeof this.id !== "string") {
          this.id = "" + this.id;
        }
      } else {
        this.id = void 0;
      }
    } else {
      this.id = id;
    }
  }
  getGroupKeys(excludeSelf = false) {
    const keys2 = [];
    let pointer = this;
    if (excludeSelf) {
      pointer = pointer.parent;
    }
    while (pointer && pointer.level >= 0) {
      keys2.push(pointer.key);
      pointer = pointer.parent;
    }
    keys2.reverse();
    return keys2;
  }
  isPixelInRange(pixel) {
    if (!exists(this.rowTop) || !exists(this.rowHeight)) {
      return false;
    }
    return pixel >= this.rowTop && pixel < this.rowTop + this.rowHeight;
  }
  setFirstChild(firstChild) {
    if (this.firstChild === firstChild) {
      return;
    }
    this.firstChild = firstChild;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_FIRST_CHILD_CHANGED));
    }
  }
  setLastChild(lastChild) {
    if (this.lastChild === lastChild) {
      return;
    }
    this.lastChild = lastChild;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_LAST_CHILD_CHANGED));
    }
  }
  setChildIndex(childIndex) {
    if (this.childIndex === childIndex) {
      return;
    }
    this.childIndex = childIndex;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_CHILD_INDEX_CHANGED));
    }
  }
  setRowTop(rowTop) {
    this.oldRowTop = this.rowTop;
    if (this.rowTop === rowTop) {
      return;
    }
    this.rowTop = rowTop;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_TOP_CHANGED));
    }
    this.setDisplayed(rowTop !== null);
  }
  clearRowTopAndRowIndex() {
    this.oldRowTop = null;
    this.setRowTop(null);
    this.setRowIndex(null);
  }
  setDisplayed(displayed) {
    if (this.displayed === displayed) {
      return;
    }
    this.displayed = displayed;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_DISPLAYED_CHANGED));
    }
  }
  setDragging(dragging) {
    if (this.dragging === dragging) {
      return;
    }
    this.dragging = dragging;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_DRAGGING_CHANGED));
    }
  }
  setHighlighted(highlighted) {
    if (highlighted === this.highlighted) {
      return;
    }
    this.highlighted = highlighted;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_HIGHLIGHT_CHANGED));
    }
  }
  setHovered(hovered) {
    if (this.hovered === hovered) {
      return;
    }
    this.hovered = hovered;
  }
  isHovered() {
    return this.hovered;
  }
  setAllChildrenCount(allChildrenCount) {
    if (this.allChildrenCount === allChildrenCount) {
      return;
    }
    this.allChildrenCount = allChildrenCount;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_ALL_CHILDREN_COUNT_CHANGED));
    }
  }
  setMaster(master) {
    if (this.master === master) {
      return;
    }
    if (this.master && !master) {
      this.expanded = false;
    }
    this.master = master;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_MASTER_CHANGED));
    }
  }
  setGroup(group) {
    if (this.group === group) {
      return;
    }
    if (this.group && !group) {
      this.expanded = false;
    }
    this.group = group;
    this.updateHasChildren();
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_GROUP_CHANGED));
    }
  }
  /**
   * Sets the row height.
   * Call if you want to change the height initially assigned to the row.
   * After calling, you must call `api.onRowHeightChanged()` so the grid knows it needs to work out the placement of the rows. */
  setRowHeight(rowHeight, estimated = false) {
    this.rowHeight = rowHeight;
    this.rowHeightEstimated = estimated;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_HEIGHT_CHANGED));
    }
  }
  setRowAutoHeight(cellHeight, column) {
    if (!this.__autoHeights) {
      this.__autoHeights = {};
    }
    this.__autoHeights[column.getId()] = cellHeight;
    if (cellHeight != null) {
      if (this.checkAutoHeightsDebounced == null) {
        this.checkAutoHeightsDebounced = debounce(this.checkAutoHeights.bind(this), 1);
      }
      this.checkAutoHeightsDebounced();
    }
  }
  checkAutoHeights() {
    let notAllPresent = false;
    let nonePresent = true;
    let newRowHeight = 0;
    const autoHeights = this.__autoHeights;
    if (autoHeights == null) {
      return;
    }
    const displayedAutoHeightCols = this.beans.columnModel.getAllDisplayedAutoHeightCols();
    displayedAutoHeightCols.forEach((col) => {
      let cellHeight = autoHeights[col.getId()];
      if (cellHeight == null) {
        if (this.beans.columnModel.isColSpanActive()) {
          let activeColsForRow = [];
          switch (col.getPinned()) {
            case "left":
              activeColsForRow = this.beans.columnModel.getDisplayedLeftColumnsForRow(this);
              break;
            case "right":
              activeColsForRow = this.beans.columnModel.getDisplayedRightColumnsForRow(this);
              break;
            case null:
              activeColsForRow = this.beans.columnModel.getViewportCenterColumnsForRow(this);
              break;
          }
          if (activeColsForRow.includes(col)) {
            notAllPresent = true;
            return;
          }
          cellHeight = -1;
        } else {
          notAllPresent = true;
          return;
        }
      } else {
        nonePresent = false;
      }
      if (cellHeight > newRowHeight) {
        newRowHeight = cellHeight;
      }
    });
    if (notAllPresent) {
      return;
    }
    if (nonePresent || newRowHeight < 10) {
      newRowHeight = this.beans.gos.getRowHeightForNode(this).height;
    }
    if (newRowHeight == this.rowHeight) {
      return;
    }
    this.setRowHeight(newRowHeight);
    const rowModel = this.beans.rowModel;
    if (rowModel.onRowHeightChangedDebounced) {
      rowModel.onRowHeightChangedDebounced();
    }
  }
  setRowIndex(rowIndex) {
    if (this.rowIndex === rowIndex) {
      return;
    }
    this.rowIndex = rowIndex;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_ROW_INDEX_CHANGED));
    }
  }
  setUiLevel(uiLevel) {
    if (this.uiLevel === uiLevel) {
      return;
    }
    this.uiLevel = uiLevel;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_UI_LEVEL_CHANGED));
    }
  }
  /**
   * Set the expanded state of this rowNode. Pass `true` to expand and `false` to collapse.
   */
  setExpanded(expanded, e, forceSync) {
    if (this.expanded === expanded) {
      return;
    }
    this.expanded = expanded;
    if (this.eventService) {
      this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_EXPANDED_CHANGED));
    }
    const event = Object.assign({}, this.createGlobalRowEvent(Events.EVENT_ROW_GROUP_OPENED), {
      expanded,
      event: e || null
    });
    this.beans.rowNodeEventThrottle.dispatchExpanded(event, forceSync);
    this.beans.rowRenderer.refreshCells({ rowNodes: [this] });
  }
  createGlobalRowEvent(type) {
    return this.beans.gos.addGridCommonParams({
      type,
      node: this,
      data: this.data,
      rowIndex: this.rowIndex,
      rowPinned: this.rowPinned
    });
  }
  dispatchLocalEvent(event) {
    if (this.eventService) {
      this.eventService.dispatchEvent(event);
    }
  }
  /**
   * Replaces the value on the `rowNode` for the specified column. When complete,
   * the grid will refresh the rendered cell on the required row only.
   * **Note**: This method only fires `onCellEditRequest` when the Grid is in **Read Only** mode.
   *
   * @param colKey The column where the value should be updated
   * @param newValue The new value
   * @param eventSource The source of the event
   * @returns `true` if the value was changed, otherwise `false`.
   */
  setDataValue(colKey, newValue, eventSource) {
    const getColumnFromKey = () => {
      var _a;
      if (typeof colKey !== "string") {
        return colKey;
      }
      return (_a = this.beans.columnModel.getGridColumn(colKey)) != null ? _a : this.beans.columnModel.getPrimaryColumn(colKey);
    };
    const column = getColumnFromKey();
    const oldValue = this.getValueFromValueService(column);
    if (this.beans.gos.get("readOnlyEdit")) {
      this.dispatchEventForSaveValueReadOnly(column, oldValue, newValue, eventSource);
      return false;
    }
    const valueChanged = this.beans.valueService.setValue(this, column, newValue, eventSource);
    this.dispatchCellChangedEvent(column, newValue, oldValue);
    this.checkRowSelectable();
    return valueChanged;
  }
  getValueFromValueService(column) {
    var _a, _b;
    const lockedClosedGroup = this.leafGroup && this.beans.columnModel.isPivotMode();
    const isOpenGroup = this.group && this.expanded && !this.footer && !lockedClosedGroup;
    let includeFooter = false;
    const groupIncludeFooterOpt = (_a = this.beans.gos.get("groupTotalRow")) != null ? _a : this.beans.gos.get("groupIncludeFooter");
    if (typeof groupIncludeFooterOpt !== "function") {
      includeFooter = !!groupIncludeFooterOpt;
    } else {
      const groupIncludeFooterCb = (_b = this.beans.gos.getCallback("groupTotalRow")) != null ? _b : this.beans.gos.getCallback("groupIncludeFooter");
      includeFooter = !!groupIncludeFooterCb({ node: this });
    }
    const groupAlwaysShowAggData = this.beans.gos.get("groupSuppressBlankHeader");
    const ignoreAggData = isOpenGroup && includeFooter && !groupAlwaysShowAggData;
    const value = this.beans.valueService.getValue(column, this, false, ignoreAggData);
    return value;
  }
  dispatchEventForSaveValueReadOnly(column, oldValue, newValue, eventSource) {
    const event = this.beans.gos.addGridCommonParams({
      type: Events.EVENT_CELL_EDIT_REQUEST,
      event: null,
      rowIndex: this.rowIndex,
      rowPinned: this.rowPinned,
      column,
      colDef: column.getColDef(),
      data: this.data,
      node: this,
      oldValue,
      newValue,
      value: newValue,
      source: eventSource
    });
    this.beans.eventService.dispatchEvent(event);
  }
  setGroupValue(colKey, newValue) {
    const column = this.beans.columnModel.getGridColumn(colKey);
    if (missing(this.groupData)) {
      this.groupData = {};
    }
    const columnId = column.getColId();
    const oldValue = this.groupData[columnId];
    if (oldValue === newValue) {
      return;
    }
    this.groupData[columnId] = newValue;
    this.dispatchCellChangedEvent(column, newValue, oldValue);
  }
  // sets the data for an aggregation
  setAggData(newAggData) {
    const oldAggData = this.aggData;
    this.aggData = newAggData;
    if (this.eventService) {
      const eventFunc = (colId) => {
        const value = this.aggData ? this.aggData[colId] : void 0;
        const oldValue = oldAggData ? oldAggData[colId] : void 0;
        if (value === oldValue) {
          return;
        }
        const column = this.beans.columnModel.lookupGridColumn(colId);
        if (!column) {
          return;
        }
        this.dispatchCellChangedEvent(column, value, oldValue);
      };
      for (const key in this.aggData) {
        eventFunc(key);
      }
      for (const key in newAggData) {
        if (key in this.aggData) {
          continue;
        }
        eventFunc(key);
      }
    }
  }
  updateHasChildren() {
    let newValue = this.group && !this.footer || this.childrenAfterGroup && this.childrenAfterGroup.length > 0;
    const isSsrm = this.beans.gos.isRowModelType("serverSide");
    if (isSsrm) {
      const isTreeData = this.beans.gos.get("treeData");
      const isGroupFunc = this.beans.gos.get("isServerSideGroup");
      newValue = !this.stub && !this.footer && (isTreeData ? !!isGroupFunc && isGroupFunc(this.data) : !!this.group);
    }
    if (newValue !== this.__hasChildren) {
      this.__hasChildren = !!newValue;
      if (this.eventService) {
        this.eventService.dispatchEvent(this.createLocalRowEvent(_RowNode.EVENT_HAS_CHILDREN_CHANGED));
      }
    }
  }
  hasChildren() {
    if (this.__hasChildren == null) {
      this.updateHasChildren();
    }
    return this.__hasChildren;
  }
  isEmptyRowGroupNode() {
    return this.group && missingOrEmpty(this.childrenAfterGroup);
  }
  dispatchCellChangedEvent(column, newValue, oldValue) {
    const cellChangedEvent = {
      type: _RowNode.EVENT_CELL_CHANGED,
      node: this,
      column,
      newValue,
      oldValue
    };
    this.dispatchLocalEvent(cellChangedEvent);
  }
  /**
   * The first time `quickFilter` runs, the grid creates a one-off string representation of the row.
   * This string is then used for the quick filter instead of hitting each column separately.
   * When you edit, using grid editing, this string gets cleared down.
   * However if you edit without using grid editing, you will need to clear this string down for the row to be updated with the new values.
   * Otherwise new values will not work with the `quickFilter`. */
  resetQuickFilterAggregateText() {
    this.quickFilterAggregateText = null;
  }
  /** Returns:
  * - `true` if the node can be expanded, i.e it is a group or master row.
  * - `false` if the node cannot be expanded
  */
  isExpandable() {
    if (this.footer) {
      return false;
    }
    if (this.beans.columnModel.isPivotMode()) {
      return this.hasChildren() && !this.leafGroup;
    }
    return this.hasChildren() || !!this.master;
  }
  /** Returns:
   * - `true` if node is selected,
   * - `false` if the node isn't selected
   * - `undefined` if it's partially selected (group where not all children are selected). */
  isSelected() {
    if (this.footer) {
      return this.sibling.isSelected();
    }
    return this.selected;
  }
  /** Perform a depth-first search of this node and its children. */
  depthFirstSearch(callback) {
    if (this.childrenAfterGroup) {
      this.childrenAfterGroup.forEach((child) => child.depthFirstSearch(callback));
    }
    callback(this);
  }
  // + selectionController.calculatedSelectedForAllGroupNodes()
  calculateSelectedFromChildren() {
    var _a;
    let atLeastOneSelected = false;
    let atLeastOneDeSelected = false;
    let atLeastOneMixed = false;
    if (!((_a = this.childrenAfterGroup) == null ? void 0 : _a.length)) {
      return this.selectable ? this.selected : null;
    }
    for (let i = 0; i < this.childrenAfterGroup.length; i++) {
      const child = this.childrenAfterGroup[i];
      let childState = child.isSelected();
      if (!child.selectable) {
        const selectable = child.calculateSelectedFromChildren();
        if (selectable === null) {
          continue;
        }
        childState = selectable;
      }
      switch (childState) {
        case true:
          atLeastOneSelected = true;
          break;
        case false:
          atLeastOneDeSelected = true;
          break;
        default:
          atLeastOneMixed = true;
          break;
      }
    }
    if (atLeastOneMixed || atLeastOneSelected && atLeastOneDeSelected) {
      return void 0;
    }
    if (atLeastOneSelected) {
      return true;
    }
    if (atLeastOneDeSelected) {
      return false;
    }
    if (!this.selectable) {
      return null;
    }
    return this.selected;
  }
  setSelectedInitialValue(selected) {
    this.selected = selected;
  }
  selectThisNode(newValue, e, source = "api") {
    const selectionNotAllowed = !this.selectable && newValue;
    const selectionNotChanged = this.selected === newValue;
    if (selectionNotAllowed || selectionNotChanged) {
      return false;
    }
    this.selected = newValue;
    if (this.eventService) {
      this.dispatchLocalEvent(this.createLocalRowEvent(_RowNode.EVENT_ROW_SELECTED));
    }
    const sibling = this.sibling;
    if (sibling && sibling.footer && sibling.eventService) {
      sibling.dispatchLocalEvent(sibling.createLocalRowEvent(_RowNode.EVENT_ROW_SELECTED));
    }
    const event = __spreadProps(__spreadValues({}, this.createGlobalRowEvent(Events.EVENT_ROW_SELECTED)), {
      event: e || null,
      source
    });
    this.beans.eventService.dispatchEvent(event);
    return true;
  }
  /**
   * Select (or deselect) the node.
   * @param newValue -`true` for selection, `false` for deselection.
   * @param clearSelection - If selecting, then passing `true` will select the node exclusively (i.e. NOT do multi select). If doing deselection, `clearSelection` has no impact.
   * @param source - Source property that will appear in the `selectionChanged` event.
   */
  setSelected(newValue, clearSelection = false, source = "api") {
    if (typeof source === "boolean") {
      console.warn("AG Grid: since version v30, rowNode.setSelected() property `suppressFinishActions` has been removed, please use `gridApi.setNodesSelected()` for bulk actions, and the event `source` property for ignoring events instead.");
      return;
    }
    this.setSelectedParams({
      newValue,
      clearSelection,
      rangeSelect: false,
      source
    });
  }
  // this is for internal use only. To make calling code more readable, this is the same method as setSelected except it takes names parameters
  setSelectedParams(params) {
    if (this.rowPinned) {
      console.warn("AG Grid: cannot select pinned rows");
      return 0;
    }
    if (this.id === void 0) {
      console.warn("AG Grid: cannot select node until id for node is known");
      return 0;
    }
    return this.beans.selectionService.setNodesSelected(__spreadProps(__spreadValues({}, params), { nodes: [this.footer ? this.sibling : this] }));
  }
  /**
   * Returns:
   * - `true` if node is either pinned to the `top` or `bottom`
   * - `false` if the node isn't pinned
   */
  isRowPinned() {
    return this.rowPinned === "top" || this.rowPinned === "bottom";
  }
  isParentOfNode(potentialParent) {
    let parentNode = this.parent;
    while (parentNode) {
      if (parentNode === potentialParent) {
        return true;
      }
      parentNode = parentNode.parent;
    }
    return false;
  }
  /** Add an event listener. */
  addEventListener(eventType, userListener) {
    var _a, _b;
    if (!this.eventService) {
      this.eventService = new EventService();
    }
    if (this.beans.frameworkOverrides.shouldWrapOutgoing && !this.frameworkEventListenerService) {
      this.eventService.setFrameworkOverrides(this.beans.frameworkOverrides);
      this.frameworkEventListenerService = new FrameworkEventListenerService(this.beans.frameworkOverrides);
    }
    const listener = (_b = (_a = this.frameworkEventListenerService) == null ? void 0 : _a.wrap(userListener)) != null ? _b : userListener;
    this.eventService.addEventListener(eventType, listener);
  }
  /** Remove event listener. */
  removeEventListener(eventType, userListener) {
    var _a, _b;
    if (!this.eventService) {
      return;
    }
    const listener = (_b = (_a = this.frameworkEventListenerService) == null ? void 0 : _a.unwrap(userListener)) != null ? _b : userListener;
    this.eventService.removeEventListener(eventType, listener);
    if (this.eventService.noRegisteredListenersExist()) {
      this.eventService = null;
    }
  }
  onMouseEnter() {
    this.dispatchLocalEvent(this.createLocalRowEvent(_RowNode.EVENT_MOUSE_ENTER));
  }
  onMouseLeave() {
    this.dispatchLocalEvent(this.createLocalRowEvent(_RowNode.EVENT_MOUSE_LEAVE));
  }
  getFirstChildOfFirstChild(rowGroupColumn) {
    let currentRowNode = this;
    let isCandidate = true;
    let foundFirstChildPath = false;
    let nodeToSwapIn = null;
    while (isCandidate && !foundFirstChildPath) {
      const parentRowNode = currentRowNode.parent;
      const firstChild = exists(parentRowNode) && currentRowNode.firstChild;
      if (firstChild) {
        if (parentRowNode.rowGroupColumn === rowGroupColumn) {
          foundFirstChildPath = true;
          nodeToSwapIn = parentRowNode;
        }
      } else {
        isCandidate = false;
      }
      currentRowNode = parentRowNode;
    }
    return foundFirstChildPath ? nodeToSwapIn : null;
  }
  /**
   * Returns:
   * - `true` if the node is a full width cell
   * - `false` if the node is not a full width cell
   */
  isFullWidthCell() {
    if (this.detail) {
      return true;
    }
    const isFullWidthCellFunc = this.beans.gos.getCallback("isFullWidthRow");
    return isFullWidthCellFunc ? isFullWidthCellFunc({ rowNode: this }) : false;
  }
  /**
   * Returns the route of the row node. If the Row Node is a group, it returns the route to that Row Node.
   * If the Row Node is not a group, it returns `undefined`.
   */
  getRoute() {
    if (this.key == null) {
      return;
    }
    const res = [];
    let pointer = this;
    while (pointer.key != null) {
      res.push(pointer.key);
      pointer = pointer.parent;
    }
    return res.reverse();
  }
  createFooter() {
    if (this.sibling) {
      return;
    }
    const ignoredProperties = /* @__PURE__ */ new Set([
      "eventService",
      "__objectId",
      "sticky"
    ]);
    const footerNode = new _RowNode(this.beans);
    Object.keys(this).forEach((key) => {
      if (ignoredProperties.has(key)) {
        return;
      }
      footerNode[key] = this[key];
    });
    footerNode.footer = true;
    footerNode.setRowTop(null);
    footerNode.setRowIndex(null);
    footerNode.oldRowTop = null;
    footerNode.id = "rowGroupFooter_" + this.id;
    footerNode.sibling = this;
    this.sibling = footerNode;
  }
  // Only used by SSRM. In CSRM this is never used as footers should always be present for
  // the purpose of exporting collapsed groups. In SSRM it is not possible to export collapsed
  // groups anyway, so can destroy footers.
  destroyFooter() {
    if (!this.sibling) {
      return;
    }
    this.sibling.setRowTop(null);
    this.sibling.setRowIndex(null);
    this.sibling = void 0;
  }
};
_RowNode.ID_PREFIX_ROW_GROUP = "row-group-";
_RowNode.ID_PREFIX_TOP_PINNED = "t-";
_RowNode.ID_PREFIX_BOTTOM_PINNED = "b-";
_RowNode.OBJECT_ID_SEQUENCE = 0;
_RowNode.EVENT_ROW_SELECTED = "rowSelected";
_RowNode.EVENT_DATA_CHANGED = "dataChanged";
_RowNode.EVENT_CELL_CHANGED = "cellChanged";
_RowNode.EVENT_ALL_CHILDREN_COUNT_CHANGED = "allChildrenCountChanged";
_RowNode.EVENT_MASTER_CHANGED = "masterChanged";
_RowNode.EVENT_GROUP_CHANGED = "groupChanged";
_RowNode.EVENT_MOUSE_ENTER = "mouseEnter";
_RowNode.EVENT_MOUSE_LEAVE = "mouseLeave";
_RowNode.EVENT_HEIGHT_CHANGED = "heightChanged";
_RowNode.EVENT_TOP_CHANGED = "topChanged";
_RowNode.EVENT_DISPLAYED_CHANGED = "displayedChanged";
_RowNode.EVENT_FIRST_CHILD_CHANGED = "firstChildChanged";
_RowNode.EVENT_LAST_CHILD_CHANGED = "lastChildChanged";
_RowNode.EVENT_CHILD_INDEX_CHANGED = "childIndexChanged";
_RowNode.EVENT_ROW_INDEX_CHANGED = "rowIndexChanged";
_RowNode.EVENT_EXPANDED_CHANGED = "expandedChanged";
_RowNode.EVENT_HAS_CHILDREN_CHANGED = "hasChildrenChanged";
_RowNode.EVENT_SELECTABLE_CHANGED = "selectableChanged";
_RowNode.EVENT_UI_LEVEL_CHANGED = "uiLevelChanged";
_RowNode.EVENT_HIGHLIGHT_CHANGED = "rowHighlightChanged";
_RowNode.EVENT_DRAGGING_CHANGED = "draggingChanged";
var RowNode = _RowNode;

// community-modules/core/src/rendering/checkboxSelectionComponent.ts
var CheckboxSelectionComponent = class extends Component {
  constructor() {
    super(
      /* html*/
      `
            <div class="ag-selection-checkbox" role="presentation">
                <ag-checkbox role="presentation" ref="eCheckbox"></ag-checkbox>
            </div>`
    );
  }
  postConstruct() {
    this.eCheckbox.setPassive(true);
  }
  getCheckboxId() {
    return this.eCheckbox.getInputElement().id;
  }
  onDataChanged() {
    this.onSelectionChanged();
  }
  onSelectableChanged() {
    this.showOrHideSelect();
  }
  onSelectionChanged() {
    const translate = this.localeService.getLocaleTextFunc();
    const state = this.rowNode.isSelected();
    const stateName = getAriaCheckboxStateName(translate, state);
    const [ariaKey, ariaLabel] = this.rowNode.selectable ? ["ariaRowToggleSelection", "Press Space to toggle row selection"] : ["ariaRowSelectionDisabled", "Row Selection is disabled for this row"];
    const translatedLabel = translate(ariaKey, ariaLabel);
    this.eCheckbox.setValue(state, true);
    this.eCheckbox.setInputAriaLabel(`${translatedLabel} (${stateName})`);
  }
  onClicked(newValue, groupSelectsFiltered, event) {
    return this.rowNode.setSelectedParams({ newValue, rangeSelect: event.shiftKey, groupSelectsFiltered, event, source: "checkboxSelected" });
  }
  init(params) {
    this.rowNode = params.rowNode;
    this.column = params.column;
    this.overrides = params.overrides;
    this.onSelectionChanged();
    this.addManagedListener(this.eCheckbox.getInputElement(), "dblclick", (event) => {
      stopPropagationForAgGrid(event);
    });
    this.addManagedListener(this.eCheckbox.getInputElement(), "click", (event) => {
      stopPropagationForAgGrid(event);
      const groupSelectsFiltered = this.gos.get("groupSelectsFiltered");
      const isSelected = this.eCheckbox.getValue();
      if (this.shouldHandleIndeterminateState(isSelected, groupSelectsFiltered)) {
        const result = this.onClicked(true, groupSelectsFiltered, event || {});
        if (result === 0) {
          this.onClicked(false, groupSelectsFiltered, event);
        }
      } else if (isSelected) {
        this.onClicked(false, groupSelectsFiltered, event);
      } else {
        this.onClicked(true, groupSelectsFiltered, event || {});
      }
    });
    this.addManagedListener(this.rowNode, RowNode.EVENT_ROW_SELECTED, this.onSelectionChanged.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_DATA_CHANGED, this.onDataChanged.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_SELECTABLE_CHANGED, this.onSelectableChanged.bind(this));
    const isRowSelectableFunc = this.gos.get("isRowSelectable");
    const checkboxVisibleIsDynamic = isRowSelectableFunc || typeof this.getIsVisible() === "function";
    if (checkboxVisibleIsDynamic) {
      const showOrHideSelectListener = this.showOrHideSelect.bind(this);
      this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, showOrHideSelectListener);
      this.addManagedListener(this.rowNode, RowNode.EVENT_DATA_CHANGED, showOrHideSelectListener);
      this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, showOrHideSelectListener);
      this.showOrHideSelect();
    }
    this.eCheckbox.getInputElement().setAttribute("tabindex", "-1");
  }
  shouldHandleIndeterminateState(isSelected, groupSelectsFiltered) {
    return groupSelectsFiltered && (this.eCheckbox.getPreviousValue() === void 0 || isSelected === void 0) && this.gos.isRowModelType("clientSide");
  }
  showOrHideSelect() {
    var _a, _b, _c;
    let selectable = this.rowNode.selectable;
    const isVisible2 = this.getIsVisible();
    if (selectable) {
      if (typeof isVisible2 === "function") {
        const extraParams = (_a = this.overrides) == null ? void 0 : _a.callbackParams;
        if (!this.column) {
          selectable = isVisible2(__spreadProps(__spreadValues({}, extraParams), { node: this.rowNode, data: this.rowNode.data }));
        } else {
          const params = this.column.createColumnFunctionCallbackParams(this.rowNode);
          selectable = isVisible2(__spreadValues(__spreadValues({}, extraParams), params));
        }
      } else {
        selectable = isVisible2 != null ? isVisible2 : false;
      }
    }
    const disableInsteadOfHide = (_b = this.column) == null ? void 0 : _b.getColDef().showDisabledCheckboxes;
    if (disableInsteadOfHide) {
      this.eCheckbox.setDisabled(!selectable);
      this.setVisible(true);
      this.setDisplayed(true);
      return;
    }
    if ((_c = this.overrides) == null ? void 0 : _c.removeHidden) {
      this.setDisplayed(selectable);
      return;
    }
    this.setVisible(selectable);
  }
  getIsVisible() {
    var _a, _b;
    if (this.overrides) {
      return this.overrides.isVisible;
    }
    return (_b = (_a = this.column) == null ? void 0 : _a.getColDef()) == null ? void 0 : _b.checkboxSelection;
  }
};
__decorateClass([
  RefSelector("eCheckbox")
], CheckboxSelectionComponent.prototype, "eCheckbox", 2);
__decorateClass([
  PostConstruct
], CheckboxSelectionComponent.prototype, "postConstruct", 1);

// community-modules/core/src/constants/direction.ts
var VerticalDirection = /* @__PURE__ */ ((VerticalDirection2) => {
  VerticalDirection2[VerticalDirection2["Up"] = 0] = "Up";
  VerticalDirection2[VerticalDirection2["Down"] = 1] = "Down";
  return VerticalDirection2;
})(VerticalDirection || {});
var HorizontalDirection = /* @__PURE__ */ ((HorizontalDirection2) => {
  HorizontalDirection2[HorizontalDirection2["Left"] = 0] = "Left";
  HorizontalDirection2[HorizontalDirection2["Right"] = 1] = "Right";
  return HorizontalDirection2;
})(HorizontalDirection || {});

// community-modules/core/src/dragAndDrop/dragAndDropService.ts
var DragSourceType = /* @__PURE__ */ ((DragSourceType4) => {
  DragSourceType4[DragSourceType4["ToolPanel"] = 0] = "ToolPanel";
  DragSourceType4[DragSourceType4["HeaderCell"] = 1] = "HeaderCell";
  DragSourceType4[DragSourceType4["RowDrag"] = 2] = "RowDrag";
  DragSourceType4[DragSourceType4["ChartPanel"] = 3] = "ChartPanel";
  DragSourceType4[DragSourceType4["AdvancedFilterBuilder"] = 4] = "AdvancedFilterBuilder";
  return DragSourceType4;
})(DragSourceType || {});
var DragAndDropService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.dragSourceAndParamsList = [];
    this.dropTargets = [];
  }
  init() {
    this.ePinnedIcon = createIcon("columnMovePin", this.gos, null);
    this.eHideIcon = createIcon("columnMoveHide", this.gos, null);
    this.eMoveIcon = createIcon("columnMoveMove", this.gos, null);
    this.eLeftIcon = createIcon("columnMoveLeft", this.gos, null);
    this.eRightIcon = createIcon("columnMoveRight", this.gos, null);
    this.eGroupIcon = createIcon("columnMoveGroup", this.gos, null);
    this.eAggregateIcon = createIcon("columnMoveValue", this.gos, null);
    this.ePivotIcon = createIcon("columnMovePivot", this.gos, null);
    this.eDropNotAllowedIcon = createIcon("dropNotAllowed", this.gos, null);
  }
  addDragSource(dragSource, allowTouch = false) {
    const params = {
      eElement: dragSource.eElement,
      dragStartPixels: dragSource.dragStartPixels,
      onDragStart: this.onDragStart.bind(this, dragSource),
      onDragStop: this.onDragStop.bind(this),
      onDragging: this.onDragging.bind(this),
      includeTouch: allowTouch
    };
    this.dragSourceAndParamsList.push({ params, dragSource });
    this.dragService.addDragSource(params);
  }
  removeDragSource(dragSource) {
    const sourceAndParams = this.dragSourceAndParamsList.find((item) => item.dragSource === dragSource);
    if (sourceAndParams) {
      this.dragService.removeDragSource(sourceAndParams.params);
      removeFromArray(this.dragSourceAndParamsList, sourceAndParams);
    }
  }
  clearDragSourceParamsList() {
    this.dragSourceAndParamsList.forEach((sourceAndParams) => this.dragService.removeDragSource(sourceAndParams.params));
    this.dragSourceAndParamsList.length = 0;
    this.dropTargets.length = 0;
  }
  nudge() {
    if (this.dragging) {
      this.onDragging(this.eventLastTime, true);
    }
  }
  onDragStart(dragSource, mouseEvent) {
    this.dragging = true;
    this.dragSource = dragSource;
    this.eventLastTime = mouseEvent;
    this.dragItem = this.dragSource.getDragItem();
    this.lastDropTarget = void 0;
    if (this.dragSource.onDragStarted) {
      this.dragSource.onDragStarted();
    }
    this.createGhost();
  }
  onDragStop(mouseEvent) {
    this.eventLastTime = null;
    this.dragging = false;
    if (this.dragSource.onDragStopped) {
      this.dragSource.onDragStopped();
    }
    if (this.lastDropTarget && this.lastDropTarget.onDragStop) {
      const draggingEvent = this.createDropTargetEvent(this.lastDropTarget, mouseEvent, null, null, false);
      this.lastDropTarget.onDragStop(draggingEvent);
    }
    this.lastDropTarget = null;
    this.dragItem = null;
    this.removeGhost();
  }
  onDragging(mouseEvent, fromNudge) {
    var _a, _b, _c, _d;
    const hDirection = this.getHorizontalDirection(mouseEvent);
    const vDirection = this.getVerticalDirection(mouseEvent);
    this.eventLastTime = mouseEvent;
    this.positionGhost(mouseEvent);
    const validDropTargets = this.dropTargets.filter((target) => this.isMouseOnDropTarget(mouseEvent, target));
    const dropTarget = this.findCurrentDropTarget(mouseEvent, validDropTargets);
    if (dropTarget !== this.lastDropTarget) {
      this.leaveLastTargetIfExists(mouseEvent, hDirection, vDirection, fromNudge);
      if (this.lastDropTarget !== null && dropTarget === null) {
        (_b = (_a = this.dragSource).onGridExit) == null ? void 0 : _b.call(_a, this.dragItem);
      }
      if (this.lastDropTarget === null && dropTarget !== null) {
        (_d = (_c = this.dragSource).onGridEnter) == null ? void 0 : _d.call(_c, this.dragItem);
      }
      this.enterDragTargetIfExists(dropTarget, mouseEvent, hDirection, vDirection, fromNudge);
      this.lastDropTarget = dropTarget;
    } else if (dropTarget && dropTarget.onDragging) {
      const draggingEvent = this.createDropTargetEvent(dropTarget, mouseEvent, hDirection, vDirection, fromNudge);
      dropTarget.onDragging(draggingEvent);
    }
  }
  getAllContainersFromDropTarget(dropTarget) {
    const secondaryContainers = dropTarget.getSecondaryContainers ? dropTarget.getSecondaryContainers() : null;
    const containers = [[dropTarget.getContainer()]];
    return secondaryContainers ? containers.concat(secondaryContainers) : containers;
  }
  allContainersIntersect(mouseEvent, containers) {
    for (const container of containers) {
      const rect = container.getBoundingClientRect();
      if (rect.width === 0 || rect.height === 0) {
        return false;
      }
      const horizontalFit = mouseEvent.clientX >= rect.left && mouseEvent.clientX < rect.right;
      const verticalFit = mouseEvent.clientY >= rect.top && mouseEvent.clientY < rect.bottom;
      if (!horizontalFit || !verticalFit) {
        return false;
      }
    }
    return true;
  }
  // checks if the mouse is on the drop target. it checks eContainer and eSecondaryContainers
  isMouseOnDropTarget(mouseEvent, dropTarget) {
    const allContainersFromDropTarget = this.getAllContainersFromDropTarget(dropTarget);
    let mouseOverTarget = false;
    for (const currentContainers of allContainersFromDropTarget) {
      if (this.allContainersIntersect(mouseEvent, currentContainers)) {
        mouseOverTarget = true;
        break;
      }
    }
    if (dropTarget.targetContainsSource && !dropTarget.getContainer().contains(this.dragSource.eElement)) {
      return false;
    }
    return mouseOverTarget && dropTarget.isInterestedIn(this.dragSource.type, this.dragSource.eElement);
  }
  findCurrentDropTarget(mouseEvent, validDropTargets) {
    const len = validDropTargets.length;
    if (len === 0) {
      return null;
    }
    if (len === 1) {
      return validDropTargets[0];
    }
    const rootNode = this.gos.getRootNode();
    const elementStack = rootNode.elementsFromPoint(mouseEvent.clientX, mouseEvent.clientY);
    for (const el of elementStack) {
      for (const dropTarget of validDropTargets) {
        const containers = flatten(this.getAllContainersFromDropTarget(dropTarget));
        if (containers.indexOf(el) !== -1) {
          return dropTarget;
        }
      }
    }
    return null;
  }
  enterDragTargetIfExists(dropTarget, mouseEvent, hDirection, vDirection, fromNudge) {
    if (!dropTarget) {
      return;
    }
    if (dropTarget.onDragEnter) {
      const dragEnterEvent = this.createDropTargetEvent(dropTarget, mouseEvent, hDirection, vDirection, fromNudge);
      dropTarget.onDragEnter(dragEnterEvent);
    }
    this.setGhostIcon(dropTarget.getIconName ? dropTarget.getIconName() : null);
  }
  leaveLastTargetIfExists(mouseEvent, hDirection, vDirection, fromNudge) {
    if (!this.lastDropTarget) {
      return;
    }
    if (this.lastDropTarget.onDragLeave) {
      const dragLeaveEvent = this.createDropTargetEvent(this.lastDropTarget, mouseEvent, hDirection, vDirection, fromNudge);
      this.lastDropTarget.onDragLeave(dragLeaveEvent);
    }
    this.setGhostIcon(null);
  }
  addDropTarget(dropTarget) {
    this.dropTargets.push(dropTarget);
  }
  removeDropTarget(dropTarget) {
    this.dropTargets = this.dropTargets.filter((target) => target.getContainer() !== dropTarget.getContainer());
  }
  hasExternalDropZones() {
    return this.dropTargets.some((zones) => zones.external);
  }
  findExternalZone(params) {
    const externalTargets = this.dropTargets.filter((target) => target.external);
    return externalTargets.find((zone) => zone.getContainer() === params.getContainer()) || null;
  }
  getHorizontalDirection(event) {
    const clientX = this.eventLastTime && this.eventLastTime.clientX;
    const eClientX = event.clientX;
    if (clientX === eClientX) {
      return null;
    }
    return clientX > eClientX ? 0 /* Left */ : 1 /* Right */;
  }
  getVerticalDirection(event) {
    const clientY = this.eventLastTime && this.eventLastTime.clientY;
    const eClientY = event.clientY;
    if (clientY === eClientY) {
      return null;
    }
    return clientY > eClientY ? 0 /* Up */ : 1 /* Down */;
  }
  createDropTargetEvent(dropTarget, event, hDirection, vDirection, fromNudge) {
    const dropZoneTarget = dropTarget.getContainer();
    const rect = dropZoneTarget.getBoundingClientRect();
    const { gridApi: api, columnApi, dragItem, dragSource } = this;
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    return { event, x, y, vDirection, hDirection, dragSource, fromNudge, dragItem, api, columnApi, dropZoneTarget };
  }
  positionGhost(event) {
    const ghost = this.eGhost;
    if (!ghost) {
      return;
    }
    const ghostRect = ghost.getBoundingClientRect();
    const ghostHeight = ghostRect.height;
    const browserWidth = getBodyWidth() - 2;
    const browserHeight = getBodyHeight() - 2;
    const offsetParentSize = getElementRectWithOffset(ghost.offsetParent);
    const { clientY, clientX } = event;
    let top = clientY - offsetParentSize.top - ghostHeight / 2;
    let left = clientX - offsetParentSize.left - 10;
    const eDocument = this.gos.getDocument();
    const win = eDocument.defaultView || window;
    const windowScrollY = win.pageYOffset || eDocument.documentElement.scrollTop;
    const windowScrollX = win.pageXOffset || eDocument.documentElement.scrollLeft;
    if (browserWidth > 0 && left + ghost.clientWidth > browserWidth + windowScrollX) {
      left = browserWidth + windowScrollX - ghost.clientWidth;
    }
    if (left < 0) {
      left = 0;
    }
    if (browserHeight > 0 && top + ghost.clientHeight > browserHeight + windowScrollY) {
      top = browserHeight + windowScrollY - ghost.clientHeight;
    }
    if (top < 0) {
      top = 0;
    }
    ghost.style.left = `${left}px`;
    ghost.style.top = `${top}px`;
  }
  removeGhost() {
    if (this.eGhost && this.eGhostParent) {
      this.eGhostParent.removeChild(this.eGhost);
    }
    this.eGhost = null;
  }
  createGhost() {
    this.eGhost = loadTemplate(DragAndDropService.GHOST_TEMPLATE);
    this.mouseEventService.stampTopLevelGridCompWithGridInstance(this.eGhost);
    const { theme } = this.environment.getTheme();
    if (theme) {
      this.eGhost.classList.add(theme);
    }
    this.eGhostIcon = this.eGhost.querySelector(".ag-dnd-ghost-icon");
    this.setGhostIcon(null);
    const eText = this.eGhost.querySelector(".ag-dnd-ghost-label");
    let dragItemName = this.dragSource.dragItemName;
    if (isFunction(dragItemName)) {
      dragItemName = dragItemName();
    }
    eText.innerHTML = escapeString(dragItemName) || "";
    this.eGhost.style.height = "25px";
    this.eGhost.style.top = "20px";
    this.eGhost.style.left = "20px";
    const eDocument = this.gos.getDocument();
    let rootNode = null;
    let targetEl = null;
    try {
      rootNode = eDocument.fullscreenElement;
    } catch (e) {
    } finally {
      if (!rootNode) {
        rootNode = this.gos.getRootNode();
      }
      const body = rootNode.querySelector("body");
      if (body) {
        targetEl = body;
      } else if (rootNode instanceof ShadowRoot) {
        targetEl = rootNode;
      } else if (rootNode instanceof Document) {
        targetEl = rootNode == null ? void 0 : rootNode.documentElement;
      } else {
        targetEl = rootNode;
      }
    }
    this.eGhostParent = targetEl;
    if (!this.eGhostParent) {
      console.warn("AG Grid: could not find document body, it is needed for dragging columns");
    } else {
      this.eGhostParent.appendChild(this.eGhost);
    }
  }
  setGhostIcon(iconName, shake = false) {
    clearElement(this.eGhostIcon);
    let eIcon = null;
    if (!iconName) {
      iconName = this.dragSource.getDefaultIconName ? this.dragSource.getDefaultIconName() : DragAndDropService.ICON_NOT_ALLOWED;
    }
    switch (iconName) {
      case DragAndDropService.ICON_PINNED:
        eIcon = this.ePinnedIcon;
        break;
      case DragAndDropService.ICON_MOVE:
        eIcon = this.eMoveIcon;
        break;
      case DragAndDropService.ICON_LEFT:
        eIcon = this.eLeftIcon;
        break;
      case DragAndDropService.ICON_RIGHT:
        eIcon = this.eRightIcon;
        break;
      case DragAndDropService.ICON_GROUP:
        eIcon = this.eGroupIcon;
        break;
      case DragAndDropService.ICON_AGGREGATE:
        eIcon = this.eAggregateIcon;
        break;
      case DragAndDropService.ICON_PIVOT:
        eIcon = this.ePivotIcon;
        break;
      case DragAndDropService.ICON_NOT_ALLOWED:
        eIcon = this.eDropNotAllowedIcon;
        break;
      case DragAndDropService.ICON_HIDE:
        eIcon = this.eHideIcon;
        break;
    }
    this.eGhostIcon.classList.toggle("ag-shake-left-to-right", shake);
    if (eIcon === this.eHideIcon && this.gos.get("suppressDragLeaveHidesColumns")) {
      return;
    }
    if (eIcon) {
      this.eGhostIcon.appendChild(eIcon);
    }
  }
};
DragAndDropService.ICON_PINNED = "pinned";
DragAndDropService.ICON_MOVE = "move";
DragAndDropService.ICON_LEFT = "left";
DragAndDropService.ICON_RIGHT = "right";
DragAndDropService.ICON_GROUP = "group";
DragAndDropService.ICON_AGGREGATE = "aggregate";
DragAndDropService.ICON_PIVOT = "pivot";
DragAndDropService.ICON_NOT_ALLOWED = "notAllowed";
DragAndDropService.ICON_HIDE = "hide";
DragAndDropService.GHOST_TEMPLATE = /* html */
`<div class="ag-dnd-ghost ag-unselectable">
            <span class="ag-dnd-ghost-icon ag-shake-left-to-right"></span>
            <div class="ag-dnd-ghost-label"></div>
        </div>`;
__decorateClass([
  Autowired("dragService")
], DragAndDropService.prototype, "dragService", 2);
__decorateClass([
  Autowired("mouseEventService")
], DragAndDropService.prototype, "mouseEventService", 2);
__decorateClass([
  Autowired("columnApi")
], DragAndDropService.prototype, "columnApi", 2);
__decorateClass([
  Autowired("gridApi")
], DragAndDropService.prototype, "gridApi", 2);
__decorateClass([
  PostConstruct
], DragAndDropService.prototype, "init", 1);
__decorateClass([
  PreDestroy
], DragAndDropService.prototype, "clearDragSourceParamsList", 1);
DragAndDropService = __decorateClass([
  Bean("dragAndDropService")
], DragAndDropService);

// community-modules/core/src/rendering/row/rowDragComp.ts
var RowDragComp = class extends Component {
  constructor(cellValueFn, rowNode, column, customGui, dragStartPixels, suppressVisibilityChange) {
    super();
    this.cellValueFn = cellValueFn;
    this.rowNode = rowNode;
    this.column = column;
    this.customGui = customGui;
    this.dragStartPixels = dragStartPixels;
    this.suppressVisibilityChange = suppressVisibilityChange;
    this.dragSource = null;
  }
  isCustomGui() {
    return this.customGui != null;
  }
  postConstruct() {
    if (!this.customGui) {
      this.setTemplate(
        /* html */
        `<div class="ag-drag-handle ag-row-drag" aria-hidden="true"></div>`
      );
      this.getGui().appendChild(createIconNoSpan("rowDrag", this.gos, null));
      this.addDragSource();
    } else {
      this.setDragElement(this.customGui, this.dragStartPixels);
    }
    this.checkCompatibility();
    if (!this.suppressVisibilityChange) {
      const strategy = this.gos.get("rowDragManaged") ? new ManagedVisibilityStrategy(this, this.beans, this.rowNode, this.column) : new NonManagedVisibilityStrategy(this, this.beans, this.rowNode, this.column);
      this.createManagedBean(strategy, this.beans.context);
    }
  }
  setDragElement(dragElement, dragStartPixels) {
    this.setTemplateFromElement(dragElement);
    this.addDragSource(dragStartPixels);
  }
  getSelectedNodes() {
    const isRowDragMultiRow = this.gos.get("rowDragMultiRow");
    if (!isRowDragMultiRow) {
      return [this.rowNode];
    }
    const selection = this.beans.selectionService.getSelectedNodes();
    return selection.indexOf(this.rowNode) !== -1 ? selection : [this.rowNode];
  }
  // returns true if all compatibility items work out
  checkCompatibility() {
    const managed = this.gos.get("rowDragManaged");
    const treeData = this.gos.get("treeData");
    if (treeData && managed) {
      warnOnce("If using row drag with tree data, you cannot have rowDragManaged=true");
    }
  }
  getDragItem() {
    return {
      rowNode: this.rowNode,
      rowNodes: this.getSelectedNodes(),
      columns: this.column ? [this.column] : void 0,
      defaultTextValue: this.cellValueFn()
    };
  }
  getRowDragText(column) {
    if (column) {
      const colDef = column.getColDef();
      if (colDef.rowDragText) {
        return colDef.rowDragText;
      }
    }
    return this.gos.get("rowDragText");
  }
  addDragSource(dragStartPixels = 4) {
    if (this.dragSource) {
      this.removeDragSource();
    }
    const translate = this.localeService.getLocaleTextFunc();
    this.dragSource = {
      type: 2 /* RowDrag */,
      eElement: this.getGui(),
      dragItemName: () => {
        var _a;
        const dragItem = this.getDragItem();
        const dragItemCount = ((_a = dragItem.rowNodes) == null ? void 0 : _a.length) || 1;
        const rowDragText = this.getRowDragText(this.column);
        if (rowDragText) {
          return rowDragText(dragItem, dragItemCount);
        }
        return dragItemCount === 1 ? this.cellValueFn() : `${dragItemCount} ${translate("rowDragRows", "rows")}`;
      },
      getDragItem: () => this.getDragItem(),
      dragStartPixels,
      dragSourceDomDataKey: this.gos.getDomDataKey()
    };
    this.beans.dragAndDropService.addDragSource(this.dragSource, true);
  }
  removeDragSource() {
    if (this.dragSource) {
      this.beans.dragAndDropService.removeDragSource(this.dragSource);
    }
    this.dragSource = null;
  }
};
__decorateClass([
  Autowired("beans")
], RowDragComp.prototype, "beans", 2);
__decorateClass([
  PostConstruct
], RowDragComp.prototype, "postConstruct", 1);
__decorateClass([
  PreDestroy
], RowDragComp.prototype, "removeDragSource", 1);
var VisibilityStrategy = class extends BeanStub {
  constructor(parent, rowNode, column) {
    super();
    this.parent = parent;
    this.rowNode = rowNode;
    this.column = column;
  }
  setDisplayedOrVisible(neverDisplayed) {
    const displayedOptions = { skipAriaHidden: true };
    if (neverDisplayed) {
      this.parent.setDisplayed(false, displayedOptions);
    } else {
      let shown = true;
      let isShownSometimes = false;
      if (this.column) {
        shown = this.column.isRowDrag(this.rowNode) || this.parent.isCustomGui();
        isShownSometimes = isFunction(this.column.getColDef().rowDrag);
      }
      if (isShownSometimes) {
        this.parent.setDisplayed(true, displayedOptions);
        this.parent.setVisible(shown, displayedOptions);
      } else {
        this.parent.setDisplayed(shown, displayedOptions);
        this.parent.setVisible(true, displayedOptions);
      }
    }
  }
};
var NonManagedVisibilityStrategy = class extends VisibilityStrategy {
  constructor(parent, beans, rowNode, column) {
    super(parent, rowNode, column);
    this.beans = beans;
  }
  postConstruct() {
    this.addManagedPropertyListener("suppressRowDrag", this.onSuppressRowDrag.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_DATA_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.beans.eventService, Events.EVENT_NEW_COLUMNS_LOADED, this.workOutVisibility.bind(this));
    this.workOutVisibility();
  }
  onSuppressRowDrag() {
    this.workOutVisibility();
  }
  workOutVisibility() {
    const neverDisplayed = this.gos.get("suppressRowDrag");
    this.setDisplayedOrVisible(neverDisplayed);
  }
};
__decorateClass([
  PostConstruct
], NonManagedVisibilityStrategy.prototype, "postConstruct", 1);
var ManagedVisibilityStrategy = class extends VisibilityStrategy {
  constructor(parent, beans, rowNode, column) {
    super(parent, rowNode, column);
    this.beans = beans;
  }
  postConstruct() {
    this.addManagedListener(this.beans.eventService, Events.EVENT_SORT_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.beans.eventService, Events.EVENT_FILTER_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.beans.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.beans.eventService, Events.EVENT_NEW_COLUMNS_LOADED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_DATA_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, this.workOutVisibility.bind(this));
    this.addManagedPropertyListener("suppressRowDrag", this.onSuppressRowDrag.bind(this));
    this.workOutVisibility();
  }
  onSuppressRowDrag() {
    this.workOutVisibility();
  }
  workOutVisibility() {
    const gridBodyCon = this.beans.ctrlsService.getGridBodyCtrl();
    const rowDragFeature = gridBodyCon.getRowDragFeature();
    const shouldPreventRowMove = rowDragFeature && rowDragFeature.shouldPreventRowMove();
    const suppressRowDrag = this.gos.get("suppressRowDrag");
    const hasExternalDropZones = this.beans.dragAndDropService.hasExternalDropZones();
    const neverDisplayed = shouldPreventRowMove && !hasExternalDropZones || suppressRowDrag;
    this.setDisplayedOrVisible(neverDisplayed);
  }
};
__decorateClass([
  PostConstruct
], ManagedVisibilityStrategy.prototype, "postConstruct", 1);

// community-modules/core/src/rendering/cellRenderers/groupCellRendererCtrl.ts
var GroupCellRendererCtrl = class extends BeanStub {
  init(comp, eGui, eCheckbox, eExpanded, eContracted, compClass, params) {
    var _a, _b, _c, _d;
    this.params = params;
    this.eGui = eGui;
    this.eCheckbox = eCheckbox;
    this.eExpanded = eExpanded;
    this.eContracted = eContracted;
    this.comp = comp;
    this.compClass = compClass;
    const { node, value, colDef } = params;
    const topLevelFooter = this.isTopLevelFooter();
    if (!topLevelFooter) {
      const embeddedRowMismatch = this.isEmbeddedRowMismatch();
      if (embeddedRowMismatch) {
        return;
      }
      if (node.footer && this.gos.get("groupHideOpenParents")) {
        const showRowGroup = colDef && colDef.showRowGroup;
        const rowGroupColumnId = node.rowGroupColumn && node.rowGroupColumn.getColId();
        if (showRowGroup !== rowGroupColumnId) {
          return;
        }
      }
    }
    this.setupShowingValueForOpenedParent();
    this.findDisplayedGroupNode();
    if (!topLevelFooter) {
      const showingFooterTotal = params.node.footer && params.node.rowGroupIndex === this.columnModel.getRowGroupColumns().findIndex((c) => {
        var _a2;
        return c.getColId() === ((_a2 = params.colDef) == null ? void 0 : _a2.showRowGroup);
      });
      const isAlwaysShowing = this.gos.get("groupDisplayType") != "multipleColumns" || this.gos.get("treeData");
      const showOpenGroupValue = isAlwaysShowing || this.gos.get("showOpenedGroup") && !params.node.footer && (!params.node.group || params.node.rowGroupIndex != null && params.node.rowGroupIndex > this.columnModel.getRowGroupColumns().findIndex((c) => {
        var _a2;
        return c.getColId() === ((_a2 = params.colDef) == null ? void 0 : _a2.showRowGroup);
      }));
      const leafWithValues = !node.group && (((_a = this.params.colDef) == null ? void 0 : _a.field) || ((_b = this.params.colDef) == null ? void 0 : _b.valueGetter));
      const isExpandable = this.isExpandable();
      const showPivotModeLeafValue = this.columnModel.isPivotMode() && node.leafGroup && ((_c = node.rowGroupColumn) == null ? void 0 : _c.getColId()) === ((_d = params.column) == null ? void 0 : _d.getColDef().showRowGroup);
      const canSkipRenderingCell = !this.showingValueForOpenedParent && !isExpandable && !leafWithValues && !showOpenGroupValue && !showingFooterTotal && !showPivotModeLeafValue;
      if (canSkipRenderingCell) {
        return;
      }
    }
    this.addExpandAndContract();
    this.addFullWidthRowDraggerIfNeeded();
    this.addCheckboxIfNeeded();
    this.addValueElement();
    this.setupIndent();
    this.refreshAriaExpanded();
  }
  getCellAriaRole() {
    var _a, _b;
    const colDefAriaRole = (_a = this.params.colDef) == null ? void 0 : _a.cellAriaRole;
    const columnColDefAriaRole = (_b = this.params.column) == null ? void 0 : _b.getColDef().cellAriaRole;
    return colDefAriaRole || columnColDefAriaRole || "gridcell";
  }
  destroy() {
    super.destroy();
    this.expandListener = null;
  }
  refreshAriaExpanded() {
    const { node, eGridCell } = this.params;
    if (this.expandListener) {
      this.expandListener = this.expandListener();
    }
    if (!this.isExpandable()) {
      removeAriaExpanded(eGridCell);
      return;
    }
    const listener = () => {
      setAriaExpanded(eGridCell, !!node.expanded);
    };
    this.expandListener = this.addManagedListener(node, RowNode.EVENT_EXPANDED_CHANGED, listener) || null;
    listener();
  }
  isTopLevelFooter() {
    const totalRow = this.gos.getGrandTotalRow();
    if (!totalRow) {
      return false;
    }
    if (this.params.value != null || this.params.node.level != -1) {
      return false;
    }
    const colDef = this.params.colDef;
    const doingFullWidth = colDef == null;
    if (doingFullWidth) {
      return true;
    }
    if (colDef.showRowGroup === true) {
      return true;
    }
    const rowGroupCols = this.columnModel.getRowGroupColumns();
    if (!rowGroupCols || rowGroupCols.length === 0) {
      return true;
    }
    const firstRowGroupCol = rowGroupCols[0];
    return firstRowGroupCol.getId() === colDef.showRowGroup;
  }
  // if we are doing embedded full width rows, we only show the renderer when
  // in the body, or if pinning in the pinned section, or if pinning and RTL,
  // in the right section. otherwise we would have the cell repeated in each section.
  isEmbeddedRowMismatch() {
    if (!this.params.fullWidth || !this.gos.get("embedFullWidthRows")) {
      return false;
    }
    const pinnedLeftCell = this.params.pinned === "left";
    const pinnedRightCell = this.params.pinned === "right";
    const bodyCell = !pinnedLeftCell && !pinnedRightCell;
    if (this.gos.get("enableRtl")) {
      if (this.columnModel.isPinningLeft()) {
        return !pinnedRightCell;
      }
      return !bodyCell;
    }
    if (this.columnModel.isPinningLeft()) {
      return !pinnedLeftCell;
    }
    return !bodyCell;
  }
  findDisplayedGroupNode() {
    const column = this.params.column;
    const rowNode = this.params.node;
    if (this.showingValueForOpenedParent) {
      let pointer = rowNode.parent;
      while (pointer != null) {
        if (pointer.rowGroupColumn && column.isRowGroupDisplayed(pointer.rowGroupColumn.getId())) {
          this.displayedGroupNode = pointer;
          break;
        }
        pointer = pointer.parent;
      }
    }
    if (missing(this.displayedGroupNode)) {
      this.displayedGroupNode = rowNode;
    }
  }
  setupShowingValueForOpenedParent() {
    const rowNode = this.params.node;
    const column = this.params.column;
    if (!this.gos.get("groupHideOpenParents")) {
      this.showingValueForOpenedParent = false;
      return;
    }
    if (!rowNode.groupData) {
      this.showingValueForOpenedParent = false;
      return;
    }
    const showingGroupNode = rowNode.rowGroupColumn != null;
    if (showingGroupNode) {
      const keyOfGroupingColumn = rowNode.rowGroupColumn.getId();
      const configuredToShowThisGroupLevel = column.isRowGroupDisplayed(keyOfGroupingColumn);
      if (configuredToShowThisGroupLevel) {
        this.showingValueForOpenedParent = false;
        return;
      }
    }
    const valPresent = rowNode.groupData[column.getId()] != null;
    this.showingValueForOpenedParent = valPresent;
  }
  addValueElement() {
    if (this.displayedGroupNode.footer) {
      this.addFooterValue();
    } else {
      this.addGroupValue();
      this.addChildCount();
    }
  }
  addGroupValue() {
    var _a;
    const paramsAdjusted = this.adjustParamsWithDetailsFromRelatedColumn();
    const innerCompDetails = this.getInnerCompDetails(paramsAdjusted);
    const { valueFormatted, value } = paramsAdjusted;
    let valueWhenNoRenderer = valueFormatted;
    if (valueWhenNoRenderer == null) {
      const isGroupColForNode = this.displayedGroupNode.rowGroupColumn && ((_a = this.params.column) == null ? void 0 : _a.isRowGroupDisplayed(this.displayedGroupNode.rowGroupColumn.getId()));
      if (this.displayedGroupNode.key === "" && this.displayedGroupNode.group && isGroupColForNode) {
        const localeTextFunc = this.localeService.getLocaleTextFunc();
        valueWhenNoRenderer = localeTextFunc("blanks", "(Blanks)");
      } else {
        valueWhenNoRenderer = value != null ? value : null;
      }
    }
    this.comp.setInnerRenderer(innerCompDetails, valueWhenNoRenderer);
  }
  adjustParamsWithDetailsFromRelatedColumn() {
    const relatedColumn = this.displayedGroupNode.rowGroupColumn;
    const column = this.params.column;
    if (!relatedColumn) {
      return this.params;
    }
    const notFullWidth = column != null;
    if (notFullWidth) {
      const showingThisRowGroup = column.isRowGroupDisplayed(relatedColumn.getId());
      if (!showingThisRowGroup) {
        return this.params;
      }
    }
    const params = this.params;
    const { value, node } = this.params;
    const valueFormatted = this.valueService.formatValue(relatedColumn, node, value);
    const paramsAdjusted = __spreadProps(__spreadValues({}, params), {
      valueFormatted
    });
    return paramsAdjusted;
  }
  addFooterValue() {
    let footerValueGetter = this.params.totalValueGetter;
    if (!footerValueGetter) {
      const legacyGetter = this.params.footerValueGetter;
      if (legacyGetter) {
        footerValueGetter = legacyGetter;
        warnOnce("As of v31.3, footerValueGetter is deprecated. Use `totalValueGetter` instead.");
      }
    }
    let footerValue = "";
    if (footerValueGetter) {
      const paramsClone = cloneObject(this.params);
      paramsClone.value = this.params.value;
      if (typeof footerValueGetter === "function") {
        footerValue = footerValueGetter(paramsClone);
      } else if (typeof footerValueGetter === "string") {
        footerValue = this.expressionService.evaluate(footerValueGetter, paramsClone);
      } else {
        console.warn("AG Grid: footerValueGetter should be either a function or a string (expression)");
      }
    } else {
      const localeTextFunc = this.localeService.getLocaleTextFunc();
      const footerTotalPrefix = localeTextFunc("footerTotal", "Total");
      footerValue = footerTotalPrefix + " " + (this.params.value != null ? this.params.value : "");
    }
    const innerCompDetails = this.getInnerCompDetails(this.params);
    this.comp.setInnerRenderer(innerCompDetails, footerValue);
  }
  getInnerCompDetails(params) {
    if (params.fullWidth) {
      return this.userComponentFactory.getFullWidthGroupRowInnerCellRenderer(
        this.gos.get("groupRowRendererParams"),
        params
      );
    }
    const innerCompDetails = this.userComponentFactory.getInnerRendererDetails(params, params);
    const isGroupRowRenderer = (details) => details && details.componentClass == this.compClass;
    if (innerCompDetails && !isGroupRowRenderer(innerCompDetails)) {
      return innerCompDetails;
    }
    const relatedColumn = this.displayedGroupNode.rowGroupColumn;
    const relatedColDef = relatedColumn ? relatedColumn.getColDef() : void 0;
    if (!relatedColDef) {
      return;
    }
    const relatedCompDetails = this.userComponentFactory.getCellRendererDetails(relatedColDef, params);
    if (relatedCompDetails && !isGroupRowRenderer(relatedCompDetails)) {
      return relatedCompDetails;
    }
    if (isGroupRowRenderer(relatedCompDetails) && relatedColDef.cellRendererParams && relatedColDef.cellRendererParams.innerRenderer) {
      const res = this.userComponentFactory.getInnerRendererDetails(relatedColDef.cellRendererParams, params);
      return res;
    }
  }
  addChildCount() {
    if (this.params.suppressCount) {
      return;
    }
    this.addManagedListener(this.displayedGroupNode, RowNode.EVENT_ALL_CHILDREN_COUNT_CHANGED, this.updateChildCount.bind(this));
    this.updateChildCount();
  }
  updateChildCount() {
    const allChildrenCount = this.displayedGroupNode.allChildrenCount;
    const showingGroupForThisNode = this.isShowRowGroupForThisRow();
    const showCount = showingGroupForThisNode && allChildrenCount != null && allChildrenCount >= 0;
    const countString = showCount ? `(${allChildrenCount})` : ``;
    this.comp.setChildCount(countString);
  }
  isShowRowGroupForThisRow() {
    if (this.gos.get("treeData")) {
      return true;
    }
    const rowGroupColumn = this.displayedGroupNode.rowGroupColumn;
    if (!rowGroupColumn) {
      return false;
    }
    const column = this.params.column;
    const thisColumnIsInterested = column == null || column.isRowGroupDisplayed(rowGroupColumn.getId());
    return thisColumnIsInterested;
  }
  addExpandAndContract() {
    var _a;
    const params = this.params;
    const eExpandedIcon = createIconNoSpan("groupExpanded", this.gos, null);
    const eContractedIcon = createIconNoSpan("groupContracted", this.gos, null);
    if (eExpandedIcon) {
      this.eExpanded.appendChild(eExpandedIcon);
    }
    if (eContractedIcon) {
      this.eContracted.appendChild(eContractedIcon);
    }
    const eGroupCell = params.eGridCell;
    const isDoubleClickEdit = ((_a = this.params.column) == null ? void 0 : _a.isCellEditable(params.node)) && this.gos.get("enableGroupEdit");
    if (!isDoubleClickEdit && this.isExpandable() && !params.suppressDoubleClickExpand) {
      this.addManagedListener(eGroupCell, "dblclick", this.onCellDblClicked.bind(this));
    }
    this.addManagedListener(this.eExpanded, "click", this.onExpandClicked.bind(this));
    this.addManagedListener(this.eContracted, "click", this.onExpandClicked.bind(this));
    this.addManagedListener(eGroupCell, "keydown", this.onKeyDown.bind(this));
    this.addManagedListener(params.node, RowNode.EVENT_EXPANDED_CHANGED, this.showExpandAndContractIcons.bind(this));
    this.showExpandAndContractIcons();
    const expandableChangedListener = this.onRowNodeIsExpandableChanged.bind(this);
    this.addManagedListener(this.displayedGroupNode, RowNode.EVENT_ALL_CHILDREN_COUNT_CHANGED, expandableChangedListener);
    this.addManagedListener(this.displayedGroupNode, RowNode.EVENT_MASTER_CHANGED, expandableChangedListener);
    this.addManagedListener(this.displayedGroupNode, RowNode.EVENT_GROUP_CHANGED, expandableChangedListener);
    this.addManagedListener(this.displayedGroupNode, RowNode.EVENT_HAS_CHILDREN_CHANGED, expandableChangedListener);
  }
  onExpandClicked(mouseEvent) {
    if (isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    stopPropagationForAgGrid(mouseEvent);
    this.onExpandOrContract(mouseEvent);
  }
  onExpandOrContract(e) {
    const rowNode = this.displayedGroupNode;
    const nextExpandState = !rowNode.expanded;
    if (!nextExpandState && rowNode.sticky) {
      this.scrollToStickyNode(rowNode);
    }
    rowNode.setExpanded(nextExpandState, e);
  }
  scrollToStickyNode(rowNode) {
    const gridBodyCtrl = this.ctrlsService.getGridBodyCtrl();
    const scrollFeature = gridBodyCtrl.getScrollFeature();
    scrollFeature.setVerticalScrollPosition(rowNode.rowTop - rowNode.stickyRowTop);
  }
  isExpandable() {
    if (this.showingValueForOpenedParent) {
      return true;
    }
    const rowNode = this.displayedGroupNode;
    const reducedLeafNode = this.columnModel.isPivotMode() && rowNode.leafGroup;
    const expandableGroup = rowNode.isExpandable() && !rowNode.footer && !reducedLeafNode;
    if (!expandableGroup) {
      return false;
    }
    const column = this.params.column;
    const displayingForOneColumnOnly = column != null && typeof column.getColDef().showRowGroup === "string";
    if (displayingForOneColumnOnly) {
      const showing = this.isShowRowGroupForThisRow();
      return showing;
    }
    return true;
  }
  showExpandAndContractIcons() {
    const { params, displayedGroupNode: displayedGroup, columnModel } = this;
    const { node } = params;
    const isExpandable = this.isExpandable();
    if (isExpandable) {
      const expanded = this.showingValueForOpenedParent ? true : node.expanded;
      this.comp.setExpandedDisplayed(expanded);
      this.comp.setContractedDisplayed(!expanded);
    } else {
      this.comp.setExpandedDisplayed(false);
      this.comp.setContractedDisplayed(false);
    }
    const pivotMode = columnModel.isPivotMode();
    const pivotModeAndLeafGroup = pivotMode && displayedGroup.leafGroup;
    const addExpandableCss = isExpandable && !pivotModeAndLeafGroup;
    const isTotalFooterNode = node.footer && node.level === -1;
    this.comp.addOrRemoveCssClass("ag-cell-expandable", addExpandableCss);
    this.comp.addOrRemoveCssClass("ag-row-group", addExpandableCss);
    if (pivotMode) {
      this.comp.addOrRemoveCssClass("ag-pivot-leaf-group", pivotModeAndLeafGroup);
    } else if (!isTotalFooterNode) {
      this.comp.addOrRemoveCssClass("ag-row-group-leaf-indent", !addExpandableCss);
    }
  }
  onRowNodeIsExpandableChanged() {
    this.showExpandAndContractIcons();
    this.setIndent();
    this.refreshAriaExpanded();
  }
  setupIndent() {
    const node = this.params.node;
    const suppressPadding = this.params.suppressPadding;
    if (!suppressPadding) {
      this.addManagedListener(node, RowNode.EVENT_UI_LEVEL_CHANGED, this.setIndent.bind(this));
      this.setIndent();
    }
  }
  setIndent() {
    if (this.gos.get("groupHideOpenParents")) {
      return;
    }
    const params = this.params;
    const rowNode = params.node;
    const fullWithRow = !!params.colDef;
    const treeData = this.gos.get("treeData");
    const manyDimensionThisColumn = !fullWithRow || treeData || params.colDef.showRowGroup === true;
    const paddingCount = manyDimensionThisColumn ? rowNode.uiLevel : 0;
    if (this.indentClass) {
      this.comp.addOrRemoveCssClass(this.indentClass, false);
    }
    this.indentClass = "ag-row-group-indent-" + paddingCount;
    this.comp.addOrRemoveCssClass(this.indentClass, true);
  }
  addFullWidthRowDraggerIfNeeded() {
    if (!this.params.fullWidth || !this.params.rowDrag) {
      return;
    }
    const rowDragComp = new RowDragComp(() => this.params.value, this.params.node);
    this.createManagedBean(rowDragComp, this.context);
    this.eGui.insertAdjacentElement("afterbegin", rowDragComp.getGui());
  }
  isUserWantsSelected() {
    const paramsCheckbox = this.params.checkbox;
    return typeof paramsCheckbox === "function" || paramsCheckbox === true;
  }
  addCheckboxIfNeeded() {
    const rowNode = this.displayedGroupNode;
    const checkboxNeeded = this.isUserWantsSelected() && // footers cannot be selected
    !rowNode.footer && // pinned rows cannot be selected
    !rowNode.rowPinned && // details cannot be selected
    !rowNode.detail;
    if (checkboxNeeded) {
      const cbSelectionComponent = new CheckboxSelectionComponent();
      this.getContext().createBean(cbSelectionComponent);
      cbSelectionComponent.init({
        rowNode: this.params.node,
        // when groupHideOpenParents = true and group expanded, we want the checkbox to refer to leaf node state (not group node state)
        column: this.params.column,
        overrides: {
          isVisible: this.params.checkbox,
          callbackParams: this.params,
          removeHidden: true
        }
      });
      this.eCheckbox.appendChild(cbSelectionComponent.getGui());
      this.addDestroyFunc(() => this.getContext().destroyBean(cbSelectionComponent));
    }
    this.comp.setCheckboxVisible(checkboxNeeded);
  }
  onKeyDown(event) {
    const isEnterKey = event.key === KeyCode.ENTER;
    if (!isEnterKey || this.params.suppressEnterExpand) {
      return;
    }
    const cellEditable = this.params.column && this.params.column.isCellEditable(this.params.node);
    if (cellEditable) {
      return;
    }
    this.onExpandOrContract(event);
  }
  onCellDblClicked(mouseEvent) {
    if (isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    const targetIsExpandIcon = isElementInEventPath(this.eExpanded, mouseEvent) || isElementInEventPath(this.eContracted, mouseEvent);
    if (!targetIsExpandIcon) {
      this.onExpandOrContract(mouseEvent);
    }
  }
};
__decorateClass([
  Autowired("expressionService")
], GroupCellRendererCtrl.prototype, "expressionService", 2);
__decorateClass([
  Autowired("valueService")
], GroupCellRendererCtrl.prototype, "valueService", 2);
__decorateClass([
  Autowired("columnModel")
], GroupCellRendererCtrl.prototype, "columnModel", 2);
__decorateClass([
  Autowired("userComponentFactory")
], GroupCellRendererCtrl.prototype, "userComponentFactory", 2);
__decorateClass([
  Autowired("ctrlsService")
], GroupCellRendererCtrl.prototype, "ctrlsService", 2);

// community-modules/core/src/rendering/cellRenderers/groupCellRenderer.ts
var _GroupCellRenderer = class _GroupCellRenderer extends Component {
  constructor() {
    super(_GroupCellRenderer.TEMPLATE);
  }
  init(params) {
    const compProxy = {
      setInnerRenderer: (compDetails, valueToDisplay) => this.setRenderDetails(compDetails, valueToDisplay),
      setChildCount: (count) => this.eChildCount.textContent = count,
      addOrRemoveCssClass: (cssClass, value) => this.addOrRemoveCssClass(cssClass, value),
      setContractedDisplayed: (expanded) => setDisplayed(this.eContracted, expanded),
      setExpandedDisplayed: (expanded) => setDisplayed(this.eExpanded, expanded),
      setCheckboxVisible: (visible) => this.eCheckbox.classList.toggle("ag-invisible", !visible)
    };
    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) {
      setAriaRole(eGui, ctrl.getCellAriaRole());
    }
  }
  setRenderDetails(compDetails, valueToDisplay) {
    if (compDetails) {
      const componentPromise = compDetails.newAgStackInstance();
      if (!componentPromise) {
        return;
      }
      componentPromise.then((comp) => {
        if (!comp) {
          return;
        }
        const destroyComp = () => this.context.destroyBean(comp);
        if (this.isAlive()) {
          this.eValue.appendChild(comp.getGui());
          this.addDestroyFunc(destroyComp);
        } else {
          destroyComp();
        }
      });
    } else {
      this.eValue.innerText = valueToDisplay;
    }
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to have public here instead of private or protected
  destroy() {
    this.getContext().destroyBean(this.innerCellRenderer);
    super.destroy();
  }
  refresh() {
    return false;
  }
};
_GroupCellRenderer.TEMPLATE = /* html */
`<span class="ag-cell-wrapper">
            <span class="ag-group-expanded" ref="eExpanded"></span>
            <span class="ag-group-contracted" ref="eContracted"></span>
            <span class="ag-group-checkbox ag-invisible" ref="eCheckbox"></span>
            <span class="ag-group-value" ref="eValue"></span>
            <span class="ag-group-child-count" ref="eChildCount"></span>
        </span>`;
__decorateClass([
  RefSelector("eExpanded")
], _GroupCellRenderer.prototype, "eExpanded", 2);
__decorateClass([
  RefSelector("eContracted")
], _GroupCellRenderer.prototype, "eContracted", 2);
__decorateClass([
  RefSelector("eCheckbox")
], _GroupCellRenderer.prototype, "eCheckbox", 2);
__decorateClass([
  RefSelector("eValue")
], _GroupCellRenderer.prototype, "eValue", 2);
__decorateClass([
  RefSelector("eChildCount")
], _GroupCellRenderer.prototype, "eChildCount", 2);
var GroupCellRenderer = _GroupCellRenderer;

// community-modules/core/src/rendering/cellRenderers/loadingCellRenderer.ts
var _LoadingCellRenderer = class _LoadingCellRenderer extends Component {
  constructor() {
    super(_LoadingCellRenderer.TEMPLATE);
  }
  init(params) {
    params.node.failedLoad ? this.setupFailed() : this.setupLoading();
  }
  setupFailed() {
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    this.eLoadingText.innerText = localeTextFunc("loadingError", "ERR");
  }
  setupLoading() {
    const eLoadingIcon = createIconNoSpan("groupLoading", this.gos, null);
    if (eLoadingIcon) {
      this.eLoadingIcon.appendChild(eLoadingIcon);
    }
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    this.eLoadingText.innerText = localeTextFunc("loadingOoo", "Loading");
  }
  refresh(params) {
    return false;
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
};
_LoadingCellRenderer.TEMPLATE = `<div class="ag-loading">
            <span class="ag-loading-icon" ref="eLoadingIcon"></span>
            <span class="ag-loading-text" ref="eLoadingText"></span>
        </div>`;
__decorateClass([
  RefSelector("eLoadingIcon")
], _LoadingCellRenderer.prototype, "eLoadingIcon", 2);
__decorateClass([
  RefSelector("eLoadingText")
], _LoadingCellRenderer.prototype, "eLoadingText", 2);
var LoadingCellRenderer = _LoadingCellRenderer;

// community-modules/core/src/rendering/cellRenderers/skeletonCellRenderer.ts
var _SkeletonCellRenderer = class _SkeletonCellRenderer extends Component {
  constructor() {
    super(_SkeletonCellRenderer.TEMPLATE);
  }
  init(params) {
    const id = `ag-cell-skeleton-renderer-${this.getCompId()}`;
    this.getGui().setAttribute("id", id);
    this.addDestroyFunc(() => setAriaLabelledBy(params.eParentOfValue));
    setAriaLabelledBy(params.eParentOfValue, id);
    params.node.failedLoad ? this.setupFailed() : this.setupLoading();
  }
  setupFailed() {
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    this.getGui().innerText = localeTextFunc("loadingError", "ERR");
    const ariaFailed = localeTextFunc("ariaSkeletonCellLoadingFailed", "Row failed to load");
    setAriaLabel(this.getGui(), ariaFailed);
  }
  setupLoading() {
    const eDocument = this.gos.getDocument();
    const skeletonEffect = eDocument.createElement("div");
    skeletonEffect.classList.add("ag-skeleton-effect");
    this.getGui().appendChild(skeletonEffect);
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    const ariaLoading = localeTextFunc("ariaSkeletonCellLoading", "Row data is loading");
    setAriaLabel(this.getGui(), ariaLoading);
  }
  refresh(params) {
    return false;
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
};
_SkeletonCellRenderer.TEMPLATE = `<div class="ag-skeleton-container"></div>`;
var SkeletonCellRenderer = _SkeletonCellRenderer;

// community-modules/core/src/rendering/overlays/loadingOverlayComponent.ts
var _LoadingOverlayComponent = class _LoadingOverlayComponent extends Component {
  constructor() {
    super();
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
  init(params) {
    const customTemplate = this.gos.get("overlayLoadingTemplate");
    this.setTemplate(customTemplate != null ? customTemplate : _LoadingOverlayComponent.DEFAULT_LOADING_OVERLAY_TEMPLATE);
    if (!customTemplate) {
      const localeTextFunc = this.localeService.getLocaleTextFunc();
      setTimeout(() => {
        this.getGui().textContent = localeTextFunc("loadingOoo", "Loading...");
      });
    }
  }
};
_LoadingOverlayComponent.DEFAULT_LOADING_OVERLAY_TEMPLATE = /* html */
`<span aria-live="polite" aria-atomic="true" class="ag-overlay-loading-center"></span>`;
var LoadingOverlayComponent = _LoadingOverlayComponent;

// community-modules/core/src/rendering/overlays/noRowsOverlayComponent.ts
var _NoRowsOverlayComponent = class _NoRowsOverlayComponent extends Component {
  constructor() {
    super();
  }
  // this is a user component, and IComponent has "public destroy()" as part of the interface.
  // so we need to override destroy() just to make the method public.
  destroy() {
    super.destroy();
  }
  init(params) {
    const customTemplate = this.gos.get("overlayNoRowsTemplate");
    this.setTemplate(customTemplate != null ? customTemplate : _NoRowsOverlayComponent.DEFAULT_NO_ROWS_TEMPLATE);
    if (!customTemplate) {
      const localeTextFunc = this.localeService.getLocaleTextFunc();
      setTimeout(() => {
        this.getGui().textContent = localeTextFunc("noRowsToShow", "No Rows To Show");
      });
    }
  }
};
_NoRowsOverlayComponent.DEFAULT_NO_ROWS_TEMPLATE = /* html */
`<span class="ag-overlay-no-rows-center"></span>`;
var NoRowsOverlayComponent = _NoRowsOverlayComponent;

// community-modules/core/src/rendering/tooltipComponent.ts
var TooltipComponent = class extends PopupComponent {
  constructor() {
    super(
      /* html */
      `<div class="ag-tooltip"></div>`
    );
  }
  // will need to type params
  init(params) {
    const { value } = params;
    this.getGui().textContent = escapeString(value, true);
  }
};

// community-modules/core/src/rendering/cellEditors/numberCellEditor.ts
var NumberCellEditorInput = class {
  getTemplate() {
    return (
      /* html */
      `<ag-input-number-field class="ag-cell-editor" ref="eInput"></ag-input-number-field>`
    );
  }
  init(eInput, params) {
    this.eInput = eInput;
    this.params = params;
    if (params.max != null) {
      eInput.setMax(params.max);
    }
    if (params.min != null) {
      eInput.setMin(params.min);
    }
    if (params.precision != null) {
      eInput.setPrecision(params.precision);
    }
    if (params.step != null) {
      eInput.setStep(params.step);
    }
    const inputEl = eInput.getInputElement();
    if (params.preventStepping) {
      eInput.addManagedListener(inputEl, "keydown", this.preventStepping);
    } else if (params.showStepperButtons) {
      inputEl.classList.add("ag-number-field-input-stepper");
    }
  }
  preventStepping(e) {
    if (e.key === KeyCode.UP || e.key === KeyCode.DOWN) {
      e.preventDefault();
    }
  }
  getValue() {
    const value = this.eInput.getValue();
    if (!exists(value) && !exists(this.params.value)) {
      return this.params.value;
    }
    let parsedValue = this.params.parseValue(value);
    if (parsedValue == null) {
      return parsedValue;
    }
    if (typeof parsedValue === "string") {
      if (parsedValue === "") {
        return null;
      }
      parsedValue = Number(parsedValue);
    }
    return isNaN(parsedValue) ? null : parsedValue;
  }
  getStartValue() {
    return this.params.value;
  }
};
var NumberCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(new NumberCellEditorInput());
  }
};

// community-modules/core/src/rendering/cellEditors/dateCellEditor.ts
var DateCellEditorInput = class {
  getTemplate() {
    return (
      /* html */
      `<ag-input-date-field class="ag-cell-editor" ref="eInput"></ag-input-date-field>`
    );
  }
  init(eInput, params) {
    this.eInput = eInput;
    this.params = params;
    if (params.min != null) {
      eInput.setMin(params.min);
    }
    if (params.max != null) {
      eInput.setMax(params.max);
    }
    if (params.step != null) {
      eInput.setStep(params.step);
    }
  }
  getValue() {
    const value = this.eInput.getDate();
    if (!exists(value) && !exists(this.params.value)) {
      return this.params.value;
    }
    return value != null ? value : null;
  }
  getStartValue() {
    const { value } = this.params;
    if (!(value instanceof Date)) {
      return void 0;
    }
    return serialiseDate(value, false);
  }
};
var DateCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(new DateCellEditorInput());
  }
};

// community-modules/core/src/rendering/cellEditors/dateStringCellEditor.ts
var DateStringCellEditorInput = class {
  constructor(getDataTypeService) {
    this.getDataTypeService = getDataTypeService;
  }
  getTemplate() {
    return (
      /* html */
      `<ag-input-date-field class="ag-cell-editor" ref="eInput"></ag-input-date-field>`
    );
  }
  init(eInput, params) {
    this.eInput = eInput;
    this.params = params;
    if (params.min != null) {
      eInput.setMin(params.min);
    }
    if (params.max != null) {
      eInput.setMax(params.max);
    }
    if (params.step != null) {
      eInput.setStep(params.step);
    }
  }
  getValue() {
    const value = this.formatDate(this.eInput.getDate());
    if (!exists(value) && !exists(this.params.value)) {
      return this.params.value;
    }
    return this.params.parseValue(value != null ? value : "");
  }
  getStartValue() {
    var _a, _b;
    return serialiseDate((_b = this.parseDate((_a = this.params.value) != null ? _a : void 0)) != null ? _b : null, false);
  }
  parseDate(value) {
    return this.getDataTypeService().getDateParserFunction(this.params.column)(value);
  }
  formatDate(value) {
    return this.getDataTypeService().getDateFormatterFunction(this.params.column)(value);
  }
};
var DateStringCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(new DateStringCellEditorInput(() => this.dataTypeService));
  }
};
__decorateClass([
  Autowired("dataTypeService")
], DateStringCellEditor.prototype, "dataTypeService", 2);

// community-modules/core/src/rendering/cellRenderers/checkboxCellRenderer.ts
var _CheckboxCellRenderer = class _CheckboxCellRenderer extends Component {
  constructor() {
    super(_CheckboxCellRenderer.TEMPLATE);
  }
  init(params) {
    this.params = params;
    this.updateCheckbox(params);
    const inputEl = this.eCheckbox.getInputElement();
    inputEl.setAttribute("tabindex", "-1");
    setAriaLive(inputEl, "polite");
    this.addManagedListener(inputEl, "click", (event) => {
      stopPropagationForAgGrid(event);
      if (this.eCheckbox.isDisabled()) {
        return;
      }
      const isSelected = this.eCheckbox.getValue();
      this.onCheckboxChanged(isSelected);
    });
    this.addManagedListener(inputEl, "dblclick", (event) => {
      stopPropagationForAgGrid(event);
    });
    this.addManagedListener(this.params.eGridCell, "keydown", (event) => {
      if (event.key === KeyCode.SPACE && !this.eCheckbox.isDisabled()) {
        if (this.params.eGridCell === this.gos.getActiveDomElement()) {
          this.eCheckbox.toggle();
        }
        const isSelected = this.eCheckbox.getValue();
        this.onCheckboxChanged(isSelected);
        event.preventDefault();
      }
    });
  }
  refresh(params) {
    this.params = params;
    this.updateCheckbox(params);
    return true;
  }
  updateCheckbox(params) {
    var _a, _b, _c;
    let isSelected;
    let displayed = true;
    if (params.node.group && params.column) {
      const colId = params.column.getColId();
      if (colId.startsWith(GROUP_AUTO_COLUMN_ID)) {
        isSelected = params.value == null || params.value === "" ? void 0 : params.value === "true";
      } else if (params.node.aggData && params.node.aggData[colId] !== void 0) {
        isSelected = (_a = params.value) != null ? _a : void 0;
      } else {
        displayed = false;
      }
    } else {
      isSelected = (_b = params.value) != null ? _b : void 0;
    }
    if (!displayed) {
      this.eCheckbox.setDisplayed(false);
      return;
    }
    this.eCheckbox.setValue(isSelected);
    const disabled = params.disabled != null ? params.disabled : !((_c = params.column) == null ? void 0 : _c.isCellEditable(params.node));
    this.eCheckbox.setDisabled(disabled);
    const translate = this.localeService.getLocaleTextFunc();
    const stateName = getAriaCheckboxStateName(translate, isSelected);
    const ariaLabel = disabled ? stateName : `${translate("ariaToggleCellValue", "Press SPACE to toggle cell value")} (${stateName})`;
    this.eCheckbox.setInputAriaLabel(ariaLabel);
  }
  onCheckboxChanged(isSelected) {
    const { column, node, rowIndex, value } = this.params;
    const eventStarted = {
      type: Events.EVENT_CELL_EDITING_STARTED,
      column,
      colDef: column == null ? void 0 : column.getColDef(),
      data: node.data,
      node,
      rowIndex,
      rowPinned: node.rowPinned,
      value
    };
    this.eventService.dispatchEvent(eventStarted);
    const valueChanged = this.params.node.setDataValue(this.params.column, isSelected, "edit");
    const eventStopped = {
      type: Events.EVENT_CELL_EDITING_STOPPED,
      column,
      colDef: column == null ? void 0 : column.getColDef(),
      data: node.data,
      node,
      rowIndex,
      rowPinned: node.rowPinned,
      value,
      oldValue: value,
      newValue: isSelected,
      valueChanged
    };
    this.eventService.dispatchEvent(eventStopped);
  }
};
_CheckboxCellRenderer.TEMPLATE = /* html*/
`
        <div class="ag-cell-wrapper ag-checkbox-cell" role="presentation">
            <ag-checkbox role="presentation" ref="eCheckbox"></ag-checkbox>
        </div>`;
__decorateClass([
  RefSelector("eCheckbox")
], _CheckboxCellRenderer.prototype, "eCheckbox", 2);
var CheckboxCellRenderer = _CheckboxCellRenderer;

// community-modules/core/src/rendering/cellEditors/checkboxCellEditor.ts
var CheckboxCellEditor = class extends PopupComponent {
  constructor() {
    super(
      /* html */
      `
            <div class="ag-cell-wrapper ag-cell-edit-wrapper ag-checkbox-edit">
                <ag-checkbox role="presentation" ref="eCheckbox"></ag-checkbox>
            </div>`
    );
  }
  init(params) {
    var _a;
    this.params = params;
    const isSelected = (_a = params.value) != null ? _a : void 0;
    this.eCheckbox.setValue(isSelected);
    const inputEl = this.eCheckbox.getInputElement();
    inputEl.setAttribute("tabindex", "-1");
    this.setAriaLabel(isSelected);
    this.addManagedListener(
      this.eCheckbox,
      Events.EVENT_FIELD_VALUE_CHANGED,
      (event) => this.setAriaLabel(event.selected)
    );
  }
  getValue() {
    return this.eCheckbox.getValue();
  }
  focusIn() {
    this.eCheckbox.getFocusableElement().focus();
  }
  afterGuiAttached() {
    if (this.params.cellStartedEdit) {
      this.focusIn();
    }
  }
  isPopup() {
    return false;
  }
  setAriaLabel(isSelected) {
    const translate = this.localeService.getLocaleTextFunc();
    const stateName = getAriaCheckboxStateName(translate, isSelected);
    const ariaLabel = translate("ariaToggleCellValue", "Press SPACE to toggle cell value");
    this.eCheckbox.setInputAriaLabel(`${ariaLabel} (${stateName})`);
  }
};
__decorateClass([
  RefSelector("eCheckbox")
], CheckboxCellEditor.prototype, "eCheckbox", 2);

// community-modules/core/src/widgets/agMenuItemRenderer.ts
var AgMenuItemRenderer = class extends Component {
  constructor() {
    super();
    this.setTemplate(
      /* html */
      `<div></div>`
    );
  }
  init(params) {
    var _a;
    this.params = params;
    this.cssClassPrefix = (_a = this.params.cssClassPrefix) != null ? _a : "ag-menu-option";
    this.addIcon();
    this.addName();
    this.addShortcut();
    this.addSubMenu();
  }
  configureDefaults() {
    return true;
  }
  addIcon() {
    if (this.params.isCompact) {
      return;
    }
    const icon = loadTemplate(
      /* html */
      `<span ref="eIcon" class="${this.getClassName("part")} ${this.getClassName("icon")}" role="presentation"></span>`
    );
    if (this.params.checked) {
      icon.appendChild(createIconNoSpan("check", this.gos));
    } else if (this.params.icon) {
      if (isNodeOrElement(this.params.icon)) {
        icon.appendChild(this.params.icon);
      } else if (typeof this.params.icon === "string") {
        icon.innerHTML = this.params.icon;
      } else {
        console.warn("AG Grid: menu item icon must be DOM node or string");
      }
    }
    this.getGui().appendChild(icon);
  }
  addName() {
    const name = loadTemplate(
      /* html */
      `<span ref="eName" class="${this.getClassName("part")} ${this.getClassName("text")}">${this.params.name || ""}</span>`
    );
    this.getGui().appendChild(name);
  }
  addShortcut() {
    if (this.params.isCompact) {
      return;
    }
    const shortcut = loadTemplate(
      /* html */
      `<span ref="eShortcut" class="${this.getClassName("part")} ${this.getClassName("shortcut")}">${this.params.shortcut || ""}</span>`
    );
    this.getGui().appendChild(shortcut);
  }
  addSubMenu() {
    const pointer = loadTemplate(
      /* html */
      `<span ref="ePopupPointer" class="${this.getClassName("part")} ${this.getClassName("popup-pointer")}"></span>`
    );
    const eGui = this.getGui();
    if (this.params.subMenu) {
      const iconName = this.gos.get("enableRtl") ? "smallLeft" : "smallRight";
      setAriaExpanded(eGui, false);
      pointer.appendChild(createIconNoSpan(iconName, this.gos));
    }
    eGui.appendChild(pointer);
  }
  getClassName(suffix) {
    return `${this.cssClassPrefix}-${suffix}`;
  }
  destroy() {
    super.destroy();
  }
};

// community-modules/core/src/components/framework/userComponentRegistry.ts
var UserComponentRegistry = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.agGridDefaults = {
      //date
      agDateInput: DefaultDateComponent,
      //header
      agColumnHeader: HeaderComp,
      agColumnGroupHeader: HeaderGroupComp,
      agSortIndicator: SortIndicatorComp,
      //floating filters
      agTextColumnFloatingFilter: TextFloatingFilter,
      agNumberColumnFloatingFilter: NumberFloatingFilter,
      agDateColumnFloatingFilter: DateFloatingFilter,
      agReadOnlyFloatingFilter: ReadOnlyFloatingFilter,
      // renderers
      agAnimateShowChangeCellRenderer: AnimateShowChangeCellRenderer,
      agAnimateSlideCellRenderer: AnimateSlideCellRenderer,
      agGroupCellRenderer: GroupCellRenderer,
      agGroupRowRenderer: GroupCellRenderer,
      agLoadingCellRenderer: LoadingCellRenderer,
      agSkeletonCellRenderer: SkeletonCellRenderer,
      agCheckboxCellRenderer: CheckboxCellRenderer,
      //editors
      agCellEditor: TextCellEditor,
      agTextCellEditor: TextCellEditor,
      agNumberCellEditor: NumberCellEditor,
      agDateCellEditor: DateCellEditor,
      agDateStringCellEditor: DateStringCellEditor,
      agSelectCellEditor: SelectCellEditor,
      agLargeTextCellEditor: LargeTextCellEditor,
      agCheckboxCellEditor: CheckboxCellEditor,
      //filter
      agTextColumnFilter: TextFilter,
      agNumberColumnFilter: NumberFilter,
      agDateColumnFilter: DateFilter,
      //overlays
      agLoadingOverlay: LoadingOverlayComponent,
      agNoRowsOverlay: NoRowsOverlayComponent,
      // tooltips
      agTooltipComponent: TooltipComponent,
      // menu item
      agMenuItem: AgMenuItemRenderer
    };
    /** Used to provide useful error messages if a user is trying to use an enterprise component without loading the module. */
    this.enterpriseAgDefaultCompsModule = {
      agSetColumnFilter: "@ag-grid-enterprise/set-filter" /* SetFilterModule */,
      agSetColumnFloatingFilter: "@ag-grid-enterprise/set-filter" /* SetFilterModule */,
      agMultiColumnFilter: "@ag-grid-enterprise/multi-filter" /* MultiFilterModule */,
      agMultiColumnFloatingFilter: "@ag-grid-enterprise/multi-filter" /* MultiFilterModule */,
      agGroupColumnFilter: "@ag-grid-enterprise/row-grouping" /* RowGroupingModule */,
      agGroupColumnFloatingFilter: "@ag-grid-enterprise/row-grouping" /* RowGroupingModule */,
      agRichSelect: "@ag-grid-enterprise/rich-select" /* RichSelectModule */,
      agRichSelectCellEditor: "@ag-grid-enterprise/rich-select" /* RichSelectModule */,
      agDetailCellRenderer: "@ag-grid-enterprise/master-detail" /* MasterDetailModule */,
      agSparklineCellRenderer: "@ag-grid-enterprise/sparklines" /* SparklinesModule */
    };
    this.jsComps = {};
  }
  init() {
    const comps = this.gos.get("components");
    if (comps != null) {
      iterateObject(comps, (key, component) => this.registerJsComponent(key, component));
    }
  }
  registerDefaultComponent(name, component) {
    if (this.agGridDefaults[name]) {
      console.error(`Trying to overwrite a default component. You should call registerComponent`);
      return;
    }
    this.agGridDefaults[name] = component;
  }
  registerJsComponent(name, component) {
    this.jsComps[name] = component;
  }
  retrieve(propertyName, name) {
    const createResult = (component, componentFromFramework) => ({ componentFromFramework, component });
    const registeredViaFrameworkComp = this.getFrameworkOverrides().frameworkComponent(name, this.gos.get("components"));
    if (registeredViaFrameworkComp != null) {
      return createResult(registeredViaFrameworkComp, true);
    }
    const jsComponent = this.jsComps[name];
    if (jsComponent) {
      const isFwkComp = this.getFrameworkOverrides().isFrameworkComponent(jsComponent);
      return createResult(jsComponent, isFwkComp);
    }
    const defaultComponent = this.agGridDefaults[name];
    if (defaultComponent) {
      return createResult(defaultComponent, false);
    }
    const moduleForComponent = this.enterpriseAgDefaultCompsModule[name];
    if (moduleForComponent) {
      ModuleRegistry.__assertRegistered(moduleForComponent, `AG Grid '${propertyName}' component: ${name}`, this.context.getGridId());
    } else {
      doOnce(() => {
        this.warnAboutMissingComponent(propertyName, name);
      }, "MissingComp" + name);
    }
    return null;
  }
  warnAboutMissingComponent(propertyName, componentName) {
    const validComponents = [
      // Don't include the old names / internals in potential suggestions
      ...Object.keys(this.agGridDefaults).filter((k) => !["agCellEditor", "agGroupRowRenderer", "agSortIndicator"].includes(k)),
      ...Object.keys(this.jsComps)
    ];
    const suggestions = fuzzySuggestions(componentName, validComponents, true, 0.8).values;
    console.warn(`AG Grid: Could not find '${componentName}' component. It was configured as "${propertyName}: '${componentName}'" but it wasn't found in the list of registered components.`);
    if (suggestions.length > 0) {
      console.warn(`         Did you mean: [${suggestions.slice(0, 3)}]?`);
    }
    console.warn(`If using a custom component check it has been registered as described in: ${this.getFrameworkOverrides().getDocLink("components/")}`);
  }
};
__decorateClass([
  PostConstruct
], UserComponentRegistry.prototype, "init", 1);
UserComponentRegistry = __decorateClass([
  Bean("userComponentRegistry")
], UserComponentRegistry);

// community-modules/core/src/components/framework/componentTypes.ts
var DateComponent = {
  propertyName: "dateComponent",
  cellRenderer: false
};
var HeaderComponent = {
  propertyName: "headerComponent",
  cellRenderer: false
};
var HeaderGroupComponent = {
  propertyName: "headerGroupComponent",
  cellRenderer: false
};
var CellRendererComponent = {
  propertyName: "cellRenderer",
  cellRenderer: true
};
var LoadingCellRendererComponent = {
  propertyName: "loadingCellRenderer",
  cellRenderer: true
};
var CellEditorComponent = {
  propertyName: "cellEditor",
  cellRenderer: false
};
var InnerRendererComponent = {
  propertyName: "innerRenderer",
  cellRenderer: true
};
var LoadingOverlayComponent2 = {
  propertyName: "loadingOverlayComponent",
  cellRenderer: false
};
var NoRowsOverlayComponent2 = {
  propertyName: "noRowsOverlayComponent",
  cellRenderer: false
};
var TooltipComponent2 = {
  propertyName: "tooltipComponent",
  cellRenderer: false
};
var FilterComponent = {
  propertyName: "filter",
  cellRenderer: false
};
var FloatingFilterComponent = {
  propertyName: "floatingFilterComponent",
  cellRenderer: false
};
var ToolPanelComponent = {
  propertyName: "toolPanel",
  cellRenderer: false
};
var StatusPanelComponent = {
  propertyName: "statusPanel",
  cellRenderer: false
};
var FullWidth = {
  propertyName: "fullWidthCellRenderer",
  cellRenderer: true
};
var FullWidthLoading = {
  propertyName: "loadingCellRenderer",
  cellRenderer: true
};
var FullWidthGroup = {
  propertyName: "groupRowRenderer",
  cellRenderer: true
};
var FullWidthDetail = {
  propertyName: "detailCellRenderer",
  cellRenderer: true
};
var MenuItemComponent = {
  propertyName: "menuItem",
  cellRenderer: false
};

// community-modules/core/src/filter/floating/floatingFilterMapper.ts
var FloatingFilterMapper = class {
  static getFloatingFilterType(filterType) {
    return this.filterToFloatingFilterMapping[filterType];
  }
};
FloatingFilterMapper.filterToFloatingFilterMapping = {
  set: "agSetColumnFloatingFilter",
  agSetColumnFilter: "agSetColumnFloatingFilter",
  multi: "agMultiColumnFloatingFilter",
  agMultiColumnFilter: "agMultiColumnFloatingFilter",
  group: "agGroupColumnFloatingFilter",
  agGroupColumnFilter: "agGroupColumnFloatingFilter",
  number: "agNumberColumnFloatingFilter",
  agNumberColumnFilter: "agNumberColumnFloatingFilter",
  date: "agDateColumnFloatingFilter",
  agDateColumnFilter: "agDateColumnFloatingFilter",
  text: "agTextColumnFloatingFilter",
  agTextColumnFilter: "agTextColumnFloatingFilter"
};

// community-modules/core/src/components/framework/userComponentFactory.ts
var UserComponentFactory = class extends BeanStub {
  getHeaderCompDetails(colDef, params) {
    return this.getCompDetails(colDef, HeaderComponent, "agColumnHeader", params);
  }
  getHeaderGroupCompDetails(params) {
    const colGroupDef = params.columnGroup.getColGroupDef();
    return this.getCompDetails(colGroupDef, HeaderGroupComponent, "agColumnGroupHeader", params);
  }
  // this one is unusual, as it can be LoadingCellRenderer, DetailCellRenderer, FullWidthCellRenderer or GroupRowRenderer.
  // so we have to pass the type in.
  getFullWidthCellRendererDetails(params) {
    return this.getCompDetails(this.gridOptions, FullWidth, null, params, true);
  }
  getFullWidthLoadingCellRendererDetails(params) {
    return this.getCompDetails(this.gridOptions, FullWidthLoading, "agLoadingCellRenderer", params, true);
  }
  getFullWidthGroupCellRendererDetails(params) {
    return this.getCompDetails(this.gridOptions, FullWidthGroup, "agGroupRowRenderer", params, true);
  }
  getFullWidthDetailCellRendererDetails(params) {
    return this.getCompDetails(this.gridOptions, FullWidthDetail, "agDetailCellRenderer", params, true);
  }
  // CELL RENDERER
  getInnerRendererDetails(def, params) {
    return this.getCompDetails(def, InnerRendererComponent, null, params);
  }
  getFullWidthGroupRowInnerCellRenderer(def, params) {
    return this.getCompDetails(def, InnerRendererComponent, null, params);
  }
  getCellRendererDetails(def, params) {
    return this.getCompDetails(def, CellRendererComponent, null, params);
  }
  getLoadingCellRendererDetails(def, params) {
    return this.getCompDetails(def, LoadingCellRendererComponent, "agSkeletonCellRenderer", params, true);
  }
  // CELL EDITOR
  getCellEditorDetails(def, params) {
    return this.getCompDetails(def, CellEditorComponent, "agCellEditor", params, true);
  }
  // FILTER
  getFilterDetails(def, params, defaultFilter) {
    return this.getCompDetails(def, FilterComponent, defaultFilter, params, true);
  }
  getDateCompDetails(params) {
    return this.getCompDetails(this.gridOptions, DateComponent, "agDateInput", params, true);
  }
  getLoadingOverlayCompDetails(params) {
    return this.getCompDetails(this.gridOptions, LoadingOverlayComponent2, "agLoadingOverlay", params, true);
  }
  getNoRowsOverlayCompDetails(params) {
    return this.getCompDetails(this.gridOptions, NoRowsOverlayComponent2, "agNoRowsOverlay", params, true);
  }
  getTooltipCompDetails(params) {
    return this.getCompDetails(params.colDef, TooltipComponent2, "agTooltipComponent", params, true);
  }
  getSetFilterCellRendererDetails(def, params) {
    return this.getCompDetails(def, CellRendererComponent, null, params);
  }
  getFloatingFilterCompDetails(def, params, defaultFloatingFilter) {
    return this.getCompDetails(def, FloatingFilterComponent, defaultFloatingFilter, params);
  }
  getToolPanelCompDetails(toolPanelDef, params) {
    return this.getCompDetails(toolPanelDef, ToolPanelComponent, null, params, true);
  }
  getStatusPanelCompDetails(def, params) {
    return this.getCompDetails(def, StatusPanelComponent, null, params, true);
  }
  getMenuItemCompDetails(def, params) {
    return this.getCompDetails(def, MenuItemComponent, "agMenuItem", params, true);
  }
  getCompDetails(defObject, type, defaultName, params, mandatory = false) {
    const { propertyName, cellRenderer } = type;
    let { compName, jsComp, fwComp, paramsFromSelector, popupFromSelector, popupPositionFromSelector } = this.getCompKeys(defObject, type, params);
    const lookupFromRegistry = (key) => {
      const item = this.userComponentRegistry.retrieve(propertyName, key);
      if (item) {
        jsComp = !item.componentFromFramework ? item.component : void 0;
        fwComp = item.componentFromFramework ? item.component : void 0;
      }
    };
    if (compName != null) {
      lookupFromRegistry(compName);
    }
    if (jsComp == null && fwComp == null && defaultName != null) {
      lookupFromRegistry(defaultName);
    }
    if (jsComp && cellRenderer && !this.agComponentUtils.doesImplementIComponent(jsComp)) {
      jsComp = this.agComponentUtils.adaptFunction(propertyName, jsComp);
    }
    if (!jsComp && !fwComp) {
      if (mandatory) {
        console.error(`AG Grid: Could not find component ${compName}, did you forget to configure this component?`);
      }
      return;
    }
    const paramsMerged = this.mergeParamsWithApplicationProvidedParams(defObject, type, params, paramsFromSelector);
    const componentFromFramework = jsComp == null;
    const componentClass = jsComp ? jsComp : fwComp;
    return {
      componentFromFramework,
      componentClass,
      params: paramsMerged,
      type,
      popupFromSelector,
      popupPositionFromSelector,
      newAgStackInstance: () => this.newAgStackInstance(componentClass, componentFromFramework, paramsMerged, type)
    };
  }
  getCompKeys(defObject, type, params) {
    const { propertyName } = type;
    let compName;
    let jsComp;
    let fwComp;
    let paramsFromSelector;
    let popupFromSelector;
    let popupPositionFromSelector;
    if (defObject) {
      const defObjectAny = defObject;
      const selectorFunc = defObjectAny[propertyName + "Selector"];
      const selectorRes = selectorFunc ? selectorFunc(params) : null;
      const assignComp = (providedJsComp) => {
        if (typeof providedJsComp === "string") {
          compName = providedJsComp;
        } else if (providedJsComp != null && providedJsComp !== true) {
          const isFwkComp = this.getFrameworkOverrides().isFrameworkComponent(providedJsComp);
          if (isFwkComp) {
            fwComp = providedJsComp;
          } else {
            jsComp = providedJsComp;
          }
        }
      };
      if (selectorRes) {
        assignComp(selectorRes.component);
        paramsFromSelector = selectorRes.params;
        popupFromSelector = selectorRes.popup;
        popupPositionFromSelector = selectorRes.popupPosition;
      } else {
        assignComp(defObjectAny[propertyName]);
      }
    }
    return { compName, jsComp, fwComp, paramsFromSelector, popupFromSelector, popupPositionFromSelector };
  }
  newAgStackInstance(ComponentClass, componentFromFramework, params, type) {
    const propertyName = type.propertyName;
    const jsComponent = !componentFromFramework;
    let instance;
    if (jsComponent) {
      instance = new ComponentClass();
    } else {
      const thisComponentConfig = this.componentMetadataProvider.retrieve(propertyName);
      instance = this.frameworkComponentWrapper.wrap(
        ComponentClass,
        thisComponentConfig.mandatoryMethodList,
        thisComponentConfig.optionalMethodList,
        type
      );
    }
    const deferredInit = this.initComponent(instance, params);
    if (deferredInit == null) {
      return AgPromise.resolve(instance);
    }
    return deferredInit.then(() => instance);
  }
  // used by Floating Filter
  mergeParamsWithApplicationProvidedParams(defObject, type, paramsFromGrid, paramsFromSelector = null) {
    const params = this.gos.getGridCommonParams();
    mergeDeep(params, paramsFromGrid);
    const defObjectAny = defObject;
    const userParams = defObjectAny && defObjectAny[type.propertyName + "Params"];
    if (typeof userParams === "function") {
      const userParamsFromFunc = userParams(paramsFromGrid);
      mergeDeep(params, userParamsFromFunc);
    } else if (typeof userParams === "object") {
      mergeDeep(params, userParams);
    }
    mergeDeep(params, paramsFromSelector);
    return params;
  }
  initComponent(component, params) {
    this.context.createBean(component);
    if (component.init == null) {
      return;
    }
    return component.init(params);
  }
  getDefaultFloatingFilterType(def, getFromDefault) {
    if (def == null) {
      return null;
    }
    let defaultFloatingFilterType = null;
    let { compName, jsComp, fwComp } = this.getCompKeys(def, FilterComponent);
    if (compName) {
      defaultFloatingFilterType = FloatingFilterMapper.getFloatingFilterType(compName);
    } else {
      const usingDefaultFilter = jsComp == null && fwComp == null && def.filter === true;
      if (usingDefaultFilter) {
        defaultFloatingFilterType = getFromDefault();
      }
    }
    return defaultFloatingFilterType;
  }
};
__decorateClass([
  Autowired("gridOptions")
], UserComponentFactory.prototype, "gridOptions", 2);
__decorateClass([
  Autowired("agComponentUtils")
], UserComponentFactory.prototype, "agComponentUtils", 2);
__decorateClass([
  Autowired("componentMetadataProvider")
], UserComponentFactory.prototype, "componentMetadataProvider", 2);
__decorateClass([
  Autowired("userComponentRegistry")
], UserComponentFactory.prototype, "userComponentRegistry", 2);
__decorateClass([
  Optional("frameworkComponentWrapper")
], UserComponentFactory.prototype, "frameworkComponentWrapper", 2);
UserComponentFactory = __decorateClass([
  Bean("userComponentFactory")
], UserComponentFactory);

// community-modules/core/src/interfaces/iExcelCreator.ts
var ExcelFactoryMode = /* @__PURE__ */ ((ExcelFactoryMode2) => {
  ExcelFactoryMode2[ExcelFactoryMode2["SINGLE_SHEET"] = 0] = "SINGLE_SHEET";
  ExcelFactoryMode2[ExcelFactoryMode2["MULTI_SHEET"] = 1] = "MULTI_SHEET";
  return ExcelFactoryMode2;
})(ExcelFactoryMode || {});

// community-modules/core/src/interfaces/iRowNode.ts
var RowHighlightPosition = /* @__PURE__ */ ((RowHighlightPosition2) => {
  RowHighlightPosition2[RowHighlightPosition2["Above"] = 0] = "Above";
  RowHighlightPosition2[RowHighlightPosition2["Below"] = 1] = "Below";
  return RowHighlightPosition2;
})(RowHighlightPosition || {});

// community-modules/core/src/autoScrollService.ts
var AutoScrollService = class {
  constructor(params) {
    this.tickingInterval = null;
    this.onScrollCallback = null;
    this.scrollContainer = params.scrollContainer;
    this.scrollHorizontally = params.scrollAxis.indexOf("x") !== -1;
    this.scrollVertically = params.scrollAxis.indexOf("y") !== -1;
    this.scrollByTick = params.scrollByTick != null ? params.scrollByTick : 20;
    if (params.onScrollCallback) {
      this.onScrollCallback = params.onScrollCallback;
    }
    if (this.scrollVertically) {
      this.getVerticalPosition = params.getVerticalPosition;
      this.setVerticalPosition = params.setVerticalPosition;
    }
    if (this.scrollHorizontally) {
      this.getHorizontalPosition = params.getHorizontalPosition;
      this.setHorizontalPosition = params.setHorizontalPosition;
    }
    this.shouldSkipVerticalScroll = params.shouldSkipVerticalScroll || (() => false);
    this.shouldSkipHorizontalScroll = params.shouldSkipHorizontalScroll || (() => false);
  }
  check(mouseEvent, forceSkipVerticalScroll = false) {
    const skipVerticalScroll = forceSkipVerticalScroll || this.shouldSkipVerticalScroll();
    if (skipVerticalScroll && this.shouldSkipHorizontalScroll()) {
      return;
    }
    const rect = this.scrollContainer.getBoundingClientRect();
    const scrollTick = this.scrollByTick;
    this.tickLeft = mouseEvent.clientX < rect.left + scrollTick;
    this.tickRight = mouseEvent.clientX > rect.right - scrollTick;
    this.tickUp = mouseEvent.clientY < rect.top + scrollTick && !skipVerticalScroll;
    this.tickDown = mouseEvent.clientY > rect.bottom - scrollTick && !skipVerticalScroll;
    if (this.tickLeft || this.tickRight || this.tickUp || this.tickDown) {
      this.ensureTickingStarted();
    } else {
      this.ensureCleared();
    }
  }
  ensureTickingStarted() {
    if (this.tickingInterval === null) {
      this.tickingInterval = window.setInterval(this.doTick.bind(this), 100);
      this.tickCount = 0;
    }
  }
  doTick() {
    this.tickCount++;
    let tickAmount;
    tickAmount = this.tickCount > 20 ? 200 : this.tickCount > 10 ? 80 : 40;
    if (this.scrollVertically) {
      const vScrollPosition = this.getVerticalPosition();
      if (this.tickUp) {
        this.setVerticalPosition(vScrollPosition - tickAmount);
      }
      if (this.tickDown) {
        this.setVerticalPosition(vScrollPosition + tickAmount);
      }
    }
    if (this.scrollHorizontally) {
      const hScrollPosition = this.getHorizontalPosition();
      if (this.tickLeft) {
        this.setHorizontalPosition(hScrollPosition - tickAmount);
      }
      if (this.tickRight) {
        this.setHorizontalPosition(hScrollPosition + tickAmount);
      }
    }
    if (this.onScrollCallback) {
      this.onScrollCallback();
    }
  }
  ensureCleared() {
    if (this.tickingInterval) {
      window.clearInterval(this.tickingInterval);
      this.tickingInterval = null;
    }
  }
};

// community-modules/core/src/gridBodyComp/rowDragFeature.ts
var RowDragFeature = class extends BeanStub {
  constructor(eContainer) {
    super();
    this.eContainer = eContainer;
  }
  postConstruct() {
    if (this.gos.isRowModelType("clientSide")) {
      this.clientSideRowModel = this.rowModel;
    }
    this.ctrlsService.whenReady((p) => {
      const gridBodyCon = p.gridBodyCtrl;
      this.autoScrollService = new AutoScrollService({
        scrollContainer: gridBodyCon.getBodyViewportElement(),
        scrollAxis: "y",
        getVerticalPosition: () => gridBodyCon.getScrollFeature().getVScrollPosition().top,
        setVerticalPosition: (position) => gridBodyCon.getScrollFeature().setVerticalScrollPosition(position),
        onScrollCallback: () => {
          this.onDragging(this.lastDraggingEvent);
        }
      });
    });
  }
  getContainer() {
    return this.eContainer;
  }
  isInterestedIn(type) {
    return type === 2 /* RowDrag */;
  }
  getIconName() {
    const managedDrag = this.gos.get("rowDragManaged");
    if (managedDrag && this.shouldPreventRowMove()) {
      return DragAndDropService.ICON_NOT_ALLOWED;
    }
    return DragAndDropService.ICON_MOVE;
  }
  shouldPreventRowMove() {
    const rowGroupCols = this.columnModel.getRowGroupColumns();
    if (rowGroupCols.length) {
      return true;
    }
    const isFilterPresent = this.filterManager.isAnyFilterPresent();
    if (isFilterPresent) {
      return true;
    }
    const isSortActive = this.sortController.isSortActive();
    if (isSortActive) {
      return true;
    }
    return false;
  }
  getRowNodes(draggingEvent) {
    if (!this.isFromThisGrid(draggingEvent)) {
      return draggingEvent.dragItem.rowNodes || [];
    }
    const currentNode = draggingEvent.dragItem.rowNode;
    const isRowDragMultiRow = this.gos.get("rowDragMultiRow");
    if (isRowDragMultiRow) {
      const selectedNodes = [...this.selectionService.getSelectedNodes()].sort(
        (a, b) => {
          if (a.rowIndex == null || b.rowIndex == null) {
            return 0;
          }
          return this.getRowIndexNumber(a) - this.getRowIndexNumber(b);
        }
      );
      if (selectedNodes.indexOf(currentNode) !== -1) {
        return selectedNodes;
      }
    }
    return [currentNode];
  }
  onDragEnter(draggingEvent) {
    draggingEvent.dragItem.rowNodes = this.getRowNodes(draggingEvent);
    this.dispatchGridEvent(Events.EVENT_ROW_DRAG_ENTER, draggingEvent);
    this.getRowNodes(draggingEvent).forEach((rowNode) => {
      rowNode.setDragging(true);
    });
    this.onEnterOrDragging(draggingEvent);
  }
  onDragging(draggingEvent) {
    this.onEnterOrDragging(draggingEvent);
  }
  isFromThisGrid(draggingEvent) {
    const { dragSourceDomDataKey } = draggingEvent.dragSource;
    return dragSourceDomDataKey === this.gos.getDomDataKey();
  }
  isDropZoneWithinThisGrid(draggingEvent) {
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    const gridGui = gridBodyCon.getGui();
    const { dropZoneTarget } = draggingEvent;
    return !gridGui.contains(dropZoneTarget);
  }
  onEnterOrDragging(draggingEvent) {
    this.dispatchGridEvent(Events.EVENT_ROW_DRAG_MOVE, draggingEvent);
    this.lastDraggingEvent = draggingEvent;
    const pixel = this.mouseEventService.getNormalisedPosition(draggingEvent).y;
    const managedDrag = this.gos.get("rowDragManaged");
    if (managedDrag) {
      this.doManagedDrag(draggingEvent, pixel);
    }
    this.autoScrollService.check(draggingEvent.event);
  }
  doManagedDrag(draggingEvent, pixel) {
    const isFromThisGrid = this.isFromThisGrid(draggingEvent);
    const managedDrag = this.gos.get("rowDragManaged");
    const rowNodes = draggingEvent.dragItem.rowNodes;
    if (managedDrag && this.shouldPreventRowMove()) {
      return;
    }
    if (this.gos.get("suppressMoveWhenRowDragging") || !isFromThisGrid) {
      if (!this.isDropZoneWithinThisGrid(draggingEvent)) {
        this.clientSideRowModel.highlightRowAtPixel(rowNodes[0], pixel);
      }
    } else {
      this.moveRows(rowNodes, pixel);
    }
  }
  getRowIndexNumber(rowNode) {
    return parseInt(last(rowNode.getRowIndexString().split("-")), 10);
  }
  moveRowAndClearHighlight(draggingEvent) {
    const lastHighlightedRowNode = this.clientSideRowModel.getLastHighlightedRowNode();
    const isBelow = lastHighlightedRowNode && lastHighlightedRowNode.highlighted === 1 /* Below */;
    const pixel = this.mouseEventService.getNormalisedPosition(draggingEvent).y;
    const rowNodes = draggingEvent.dragItem.rowNodes;
    let increment = isBelow ? 1 : 0;
    if (this.isFromThisGrid(draggingEvent)) {
      rowNodes.forEach((rowNode) => {
        if (rowNode.rowTop < pixel) {
          increment -= 1;
        }
      });
      this.moveRows(rowNodes, pixel, increment);
    } else {
      const getRowIdFunc = this.gos.getCallback("getRowId");
      let addIndex = this.clientSideRowModel.getRowIndexAtPixel(pixel) + 1;
      if (this.clientSideRowModel.getHighlightPosition(pixel) === 0 /* Above */) {
        addIndex--;
      }
      this.clientSideRowModel.updateRowData({
        add: rowNodes.map((node) => node.data).filter(
          (data) => !this.clientSideRowModel.getRowNode(
            getRowIdFunc ? getRowIdFunc({ data, level: 0 }) : data.id
          )
        ),
        addIndex
      });
    }
    this.clearRowHighlight();
  }
  clearRowHighlight() {
    this.clientSideRowModel.highlightRowAtPixel(null);
  }
  moveRows(rowNodes, pixel, increment = 0) {
    var _a;
    const rowWasMoved = this.clientSideRowModel.ensureRowsAtPixel(rowNodes, pixel, increment);
    if (rowWasMoved) {
      this.focusService.clearFocusedCell();
      (_a = this.rangeService) == null ? void 0 : _a.removeAllCellRanges();
    }
  }
  addRowDropZone(params) {
    if (!params.getContainer()) {
      warnOnce("addRowDropZone - A container target needs to be provided");
      return;
    }
    if (this.dragAndDropService.findExternalZone(params)) {
      console.warn("AG Grid: addRowDropZone - target already exists in the list of DropZones. Use `removeRowDropZone` before adding it again.");
      return;
    }
    let processedParams = {
      getContainer: params.getContainer
    };
    if (params.fromGrid) {
      processedParams = params;
    } else {
      if (params.onDragEnter) {
        processedParams.onDragEnter = (e) => {
          params.onDragEnter(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_ENTER, e));
        };
      }
      if (params.onDragLeave) {
        processedParams.onDragLeave = (e) => {
          params.onDragLeave(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_LEAVE, e));
        };
      }
      if (params.onDragging) {
        processedParams.onDragging = (e) => {
          params.onDragging(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_MOVE, e));
        };
      }
      if (params.onDragStop) {
        processedParams.onDragStop = (e) => {
          params.onDragStop(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_END, e));
        };
      }
    }
    this.dragAndDropService.addDropTarget(__spreadValues({
      isInterestedIn: (type) => type === 2 /* RowDrag */,
      getIconName: () => DragAndDropService.ICON_MOVE,
      external: true
    }, processedParams));
  }
  getRowDropZone(events) {
    const getContainer = this.getContainer.bind(this);
    const onDragEnter = this.onDragEnter.bind(this);
    const onDragLeave = this.onDragLeave.bind(this);
    const onDragging = this.onDragging.bind(this);
    const onDragStop = this.onDragStop.bind(this);
    if (!events) {
      return {
        getContainer,
        onDragEnter,
        onDragLeave,
        onDragging,
        onDragStop,
        /* @private */
        fromGrid: true
      };
    }
    return {
      getContainer,
      onDragEnter: events.onDragEnter ? (e) => {
        onDragEnter(e);
        events.onDragEnter(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_ENTER, e));
      } : onDragEnter,
      onDragLeave: events.onDragLeave ? (e) => {
        onDragLeave(e);
        events.onDragLeave(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_LEAVE, e));
      } : onDragLeave,
      onDragging: events.onDragging ? (e) => {
        onDragging(e);
        events.onDragging(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_MOVE, e));
      } : onDragging,
      onDragStop: events.onDragStop ? (e) => {
        onDragStop(e);
        events.onDragStop(this.draggingToRowDragEvent(Events.EVENT_ROW_DRAG_END, e));
      } : onDragStop,
      fromGrid: true
      /* @private */
    };
  }
  draggingToRowDragEvent(type, draggingEvent) {
    const yNormalised = this.mouseEventService.getNormalisedPosition(draggingEvent).y;
    const mouseIsPastLastRow = yNormalised > this.paginationProxy.getCurrentPageHeight();
    let overIndex = -1;
    let overNode;
    if (!mouseIsPastLastRow) {
      overIndex = this.rowModel.getRowIndexAtPixel(yNormalised);
      overNode = this.rowModel.getRow(overIndex);
    }
    let vDirectionString;
    switch (draggingEvent.vDirection) {
      case 1 /* Down */:
        vDirectionString = "down";
        break;
      case 0 /* Up */:
        vDirectionString = "up";
        break;
      default:
        vDirectionString = null;
        break;
    }
    const event = this.gos.addGridCommonParams({
      type,
      event: draggingEvent.event,
      node: draggingEvent.dragItem.rowNode,
      nodes: draggingEvent.dragItem.rowNodes,
      overIndex,
      overNode,
      y: yNormalised,
      vDirection: vDirectionString
    });
    return event;
  }
  dispatchGridEvent(type, draggingEvent) {
    const event = this.draggingToRowDragEvent(type, draggingEvent);
    this.eventService.dispatchEvent(event);
  }
  onDragLeave(draggingEvent) {
    this.dispatchGridEvent(Events.EVENT_ROW_DRAG_LEAVE, draggingEvent);
    this.stopDragging(draggingEvent);
    if (this.gos.get("rowDragManaged")) {
      this.clearRowHighlight();
    }
  }
  onDragStop(draggingEvent) {
    this.dispatchGridEvent(Events.EVENT_ROW_DRAG_END, draggingEvent);
    this.stopDragging(draggingEvent);
    if (this.gos.get("rowDragManaged") && (this.gos.get("suppressMoveWhenRowDragging") || !this.isFromThisGrid(draggingEvent)) && !this.isDropZoneWithinThisGrid(draggingEvent)) {
      this.moveRowAndClearHighlight(draggingEvent);
    }
  }
  stopDragging(draggingEvent) {
    this.autoScrollService.ensureCleared();
    this.getRowNodes(draggingEvent).forEach((rowNode) => {
      rowNode.setDragging(false);
    });
  }
};
__decorateClass([
  Autowired("dragAndDropService")
], RowDragFeature.prototype, "dragAndDropService", 2);
__decorateClass([
  Autowired("rowModel")
], RowDragFeature.prototype, "rowModel", 2);
__decorateClass([
  Autowired("paginationProxy")
], RowDragFeature.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("columnModel")
], RowDragFeature.prototype, "columnModel", 2);
__decorateClass([
  Autowired("focusService")
], RowDragFeature.prototype, "focusService", 2);
__decorateClass([
  Autowired("sortController")
], RowDragFeature.prototype, "sortController", 2);
__decorateClass([
  Autowired("filterManager")
], RowDragFeature.prototype, "filterManager", 2);
__decorateClass([
  Autowired("selectionService")
], RowDragFeature.prototype, "selectionService", 2);
__decorateClass([
  Autowired("mouseEventService")
], RowDragFeature.prototype, "mouseEventService", 2);
__decorateClass([
  Autowired("ctrlsService")
], RowDragFeature.prototype, "ctrlsService", 2);
__decorateClass([
  Optional("rangeService")
], RowDragFeature.prototype, "rangeService", 2);
__decorateClass([
  PostConstruct
], RowDragFeature.prototype, "postConstruct", 1);

// community-modules/core/src/dragAndDrop/dragService.ts
var DragService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.dragEndFunctions = [];
    this.dragSources = [];
  }
  removeAllListeners() {
    this.dragSources.forEach(this.removeListener.bind(this));
    this.dragSources.length = 0;
  }
  removeListener(dragSourceAndListener) {
    const element = dragSourceAndListener.dragSource.eElement;
    const mouseDownListener = dragSourceAndListener.mouseDownListener;
    element.removeEventListener("mousedown", mouseDownListener);
    if (dragSourceAndListener.touchEnabled) {
      const touchStartListener = dragSourceAndListener.touchStartListener;
      element.removeEventListener("touchstart", touchStartListener, { passive: true });
    }
  }
  removeDragSource(params) {
    const dragSourceAndListener = this.dragSources.find((item) => item.dragSource === params);
    if (!dragSourceAndListener) {
      return;
    }
    this.removeListener(dragSourceAndListener);
    removeFromArray(this.dragSources, dragSourceAndListener);
  }
  isDragging() {
    return this.dragging;
  }
  addDragSource(params) {
    const mouseListener = this.onMouseDown.bind(this, params);
    const { eElement, includeTouch, stopPropagationForTouch } = params;
    eElement.addEventListener("mousedown", mouseListener);
    let touchListener = null;
    const suppressTouch = this.gos.get("suppressTouch");
    if (includeTouch && !suppressTouch) {
      touchListener = (touchEvent) => {
        if (isFocusableFormField(touchEvent.target)) {
          return;
        }
        if (touchEvent.cancelable) {
          touchEvent.preventDefault();
          if (stopPropagationForTouch) {
            touchEvent.stopPropagation();
          }
        }
        this.onTouchStart(params, touchEvent);
      };
      eElement.addEventListener("touchstart", touchListener, { passive: false });
    }
    this.dragSources.push({
      dragSource: params,
      mouseDownListener: mouseListener,
      touchStartListener: touchListener,
      touchEnabled: !!includeTouch
    });
  }
  getStartTarget() {
    return this.startTarget;
  }
  // gets called whenever mouse down on any drag source
  onTouchStart(params, touchEvent) {
    this.currentDragParams = params;
    this.dragging = false;
    const touch = touchEvent.touches[0];
    this.touchLastTime = touch;
    this.touchStart = touch;
    const touchMoveEvent = (e) => this.onTouchMove(e, params.eElement);
    const touchEndEvent = (e) => this.onTouchUp(e, params.eElement);
    const documentTouchMove = (e) => {
      if (e.cancelable) {
        e.preventDefault();
      }
    };
    const target = touchEvent.target;
    const events = [
      // Prevents the page document from moving while we are dragging items around.
      // preventDefault needs to be called in the touchmove listener and never inside the
      // touchstart, because using touchstart causes the click event to be cancelled on touch devices.
      { target: this.gos.getRootNode(), type: "touchmove", listener: documentTouchMove, options: { passive: false } },
      { target, type: "touchmove", listener: touchMoveEvent, options: { passive: true } },
      { target, type: "touchend", listener: touchEndEvent, options: { passive: true } },
      { target, type: "touchcancel", listener: touchEndEvent, options: { passive: true } }
    ];
    this.addTemporaryEvents(events);
    if (params.dragStartPixels === 0) {
      this.onCommonMove(touch, this.touchStart, params.eElement);
    }
  }
  // gets called whenever mouse down on any drag source
  onMouseDown(params, mouseEvent) {
    const e = mouseEvent;
    if (params.skipMouseEvent && params.skipMouseEvent(mouseEvent)) {
      return;
    }
    if (e._alreadyProcessedByDragService) {
      return;
    }
    e._alreadyProcessedByDragService = true;
    if (mouseEvent.button !== 0) {
      return;
    }
    if (this.shouldPreventMouseEvent(mouseEvent)) {
      mouseEvent.preventDefault();
    }
    this.currentDragParams = params;
    this.dragging = false;
    this.mouseStartEvent = mouseEvent;
    this.startTarget = mouseEvent.target;
    const mouseMoveEvent = (event) => this.onMouseMove(event, params.eElement);
    const mouseUpEvent = (event) => this.onMouseUp(event, params.eElement);
    const contextEvent = (event) => event.preventDefault();
    const target = this.gos.getRootNode();
    const events = [
      { target, type: "mousemove", listener: mouseMoveEvent },
      { target, type: "mouseup", listener: mouseUpEvent },
      { target, type: "contextmenu", listener: contextEvent }
    ];
    this.addTemporaryEvents(events);
    if (params.dragStartPixels === 0) {
      this.onMouseMove(mouseEvent, params.eElement);
    }
  }
  addTemporaryEvents(events) {
    events.forEach((currentEvent) => {
      const { target, type, listener, options } = currentEvent;
      target.addEventListener(type, listener, options);
    });
    this.dragEndFunctions.push(() => {
      events.forEach((currentEvent) => {
        const { target, type, listener, options } = currentEvent;
        target.removeEventListener(type, listener, options);
      });
    });
  }
  // returns true if the event is close to the original event by X pixels either vertically or horizontally.
  // we only start dragging after X pixels so this allows us to know if we should start dragging yet.
  isEventNearStartEvent(currentEvent, startEvent) {
    const { dragStartPixels } = this.currentDragParams;
    const requiredPixelDiff = exists(dragStartPixels) ? dragStartPixels : 4;
    return areEventsNear(currentEvent, startEvent, requiredPixelDiff);
  }
  getFirstActiveTouch(touchList) {
    for (let i = 0; i < touchList.length; i++) {
      if (touchList[i].identifier === this.touchStart.identifier) {
        return touchList[i];
      }
    }
    return null;
  }
  onCommonMove(currentEvent, startEvent, el) {
    if (!this.dragging) {
      if (!this.dragging && this.isEventNearStartEvent(currentEvent, startEvent)) {
        return;
      }
      this.dragging = true;
      const event = {
        type: Events.EVENT_DRAG_STARTED,
        target: el
      };
      this.eventService.dispatchEvent(event);
      this.currentDragParams.onDragStart(startEvent);
      this.currentDragParams.onDragging(startEvent);
    }
    this.currentDragParams.onDragging(currentEvent);
  }
  onTouchMove(touchEvent, el) {
    const touch = this.getFirstActiveTouch(touchEvent.touches);
    if (!touch) {
      return;
    }
    this.onCommonMove(touch, this.touchStart, el);
  }
  // only gets called after a mouse down - as this is only added after mouseDown
  // and is removed when mouseUp happens
  onMouseMove(mouseEvent, el) {
    var _a;
    if (isBrowserSafari()) {
      const eDocument = this.gos.getDocument();
      (_a = eDocument.getSelection()) == null ? void 0 : _a.removeAllRanges();
    }
    if (this.shouldPreventMouseEvent(mouseEvent)) {
      mouseEvent.preventDefault();
    }
    this.onCommonMove(mouseEvent, this.mouseStartEvent, el);
  }
  shouldPreventMouseEvent(mouseEvent) {
    const isEnableCellTextSelect = this.gos.get("enableCellTextSelection");
    const isMouseMove = mouseEvent.type === "mousemove";
    return (
      // when `isEnableCellTextSelect` is `true`, we need to preventDefault on mouseMove
      // to avoid the grid text being selected while dragging components.
      isEnableCellTextSelect && isMouseMove && mouseEvent.cancelable && this.mouseEventService.isEventFromThisGrid(mouseEvent) && !this.isOverFormFieldElement(mouseEvent)
    );
  }
  isOverFormFieldElement(mouseEvent) {
    const el = mouseEvent.target;
    const tagName = el == null ? void 0 : el.tagName.toLocaleLowerCase();
    return !!(tagName == null ? void 0 : tagName.match("^a$|textarea|input|select|button"));
  }
  onTouchUp(touchEvent, el) {
    let touch = this.getFirstActiveTouch(touchEvent.changedTouches);
    if (!touch) {
      touch = this.touchLastTime;
    }
    this.onUpCommon(touch, el);
  }
  onMouseUp(mouseEvent, el) {
    this.onUpCommon(mouseEvent, el);
  }
  onUpCommon(eventOrTouch, el) {
    if (this.dragging) {
      this.dragging = false;
      this.currentDragParams.onDragStop(eventOrTouch);
      const event = {
        type: Events.EVENT_DRAG_STOPPED,
        target: el
      };
      this.eventService.dispatchEvent(event);
    }
    this.mouseStartEvent = null;
    this.startTarget = null;
    this.touchStart = null;
    this.touchLastTime = null;
    this.currentDragParams = null;
    this.dragEndFunctions.forEach((func) => func());
    this.dragEndFunctions.length = 0;
  }
};
__decorateClass([
  Autowired("mouseEventService")
], DragService.prototype, "mouseEventService", 2);
__decorateClass([
  PreDestroy
], DragService.prototype, "removeAllListeners", 1);
DragService = __decorateClass([
  Bean("dragService")
], DragService);

// community-modules/core/src/dragAndDrop/virtualListDragFeature.ts
var LIST_ITEM_HOVERED = "ag-list-item-hovered";
var VirtualListDragFeature = class extends BeanStub {
  constructor(comp, virtualList, params) {
    super();
    this.comp = comp;
    this.virtualList = virtualList;
    this.params = params;
    this.currentDragValue = null;
    this.lastHoveredListItem = null;
  }
  postConstruct() {
    this.addManagedListener(this.params.eventSource, this.params.listItemDragStartEvent, this.listItemDragStart.bind(this));
    this.addManagedListener(this.params.eventSource, this.params.listItemDragEndEvent, this.listItemDragEnd.bind(this));
    this.createDropTarget();
    this.createAutoScrollService();
  }
  listItemDragStart(event) {
    this.currentDragValue = this.params.getCurrentDragValue(event);
    this.moveBlocked = this.params.isMoveBlocked(this.currentDragValue);
  }
  listItemDragEnd() {
    window.setTimeout(() => {
      this.currentDragValue = null;
      this.moveBlocked = false;
    }, 10);
  }
  createDropTarget() {
    const dropTarget = {
      isInterestedIn: (type) => type === this.params.dragSourceType,
      getIconName: () => this.moveBlocked ? DragAndDropService.ICON_PINNED : DragAndDropService.ICON_MOVE,
      getContainer: () => this.comp.getGui(),
      onDragging: (e) => this.onDragging(e),
      onDragStop: () => this.onDragStop(),
      onDragLeave: () => this.onDragLeave()
    };
    this.dragAndDropService.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 = 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.clearHoveredItems();
    this.autoScrollService.ensureCleared();
  }
  onDragLeave() {
    this.clearHoveredItems();
    this.autoScrollService.ensureCleared();
  }
  clearHoveredItems() {
    const virtualListGui = this.virtualList.getGui();
    virtualListGui.querySelectorAll(`.${LIST_ITEM_HOVERED}`).forEach((el) => {
      [
        LIST_ITEM_HOVERED,
        "ag-item-highlight-top",
        "ag-item-highlight-bottom"
      ].forEach((cls) => {
        el.classList.remove(cls);
      });
    });
    this.lastHoveredListItem = null;
  }
};
__decorateClass([
  Autowired("dragAndDropService")
], VirtualListDragFeature.prototype, "dragAndDropService", 2);
__decorateClass([
  PostConstruct
], VirtualListDragFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridApi.ts
function unwrapUserComp(comp) {
  const compAsAny = comp;
  const isProxy = compAsAny != null && compAsAny.getFrameworkComponentInstance != null;
  return isProxy ? compAsAny.getFrameworkComponentInstance() : comp;
}
var GridApi = class {
  constructor() {
    this.detailGridInfoMap = {};
    this.destroyCalled = false;
  }
  init() {
    switch (this.rowModel.getType()) {
      case "clientSide":
        this.clientSideRowModel = this.rowModel;
        break;
      case "infinite":
        this.infiniteRowModel = this.rowModel;
        break;
      case "serverSide":
        this.serverSideRowModel = this.rowModel;
        break;
    }
    this.ctrlsService.whenReady((p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
    });
  }
  /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */
  __getAlignedGridService() {
    return this.alignedGridsService;
  }
  /** Returns the `gridId` for the current grid as specified via the gridOptions property `gridId` or the auto assigned grid id if none was provided. */
  getGridId() {
    return this.context.getGridId();
  }
  /** Register a detail grid with the master grid when it is created. */
  addDetailGridInfo(id, gridInfo) {
    this.detailGridInfoMap[id] = gridInfo;
  }
  /** Unregister a detail grid from the master grid when it is destroyed. */
  removeDetailGridInfo(id) {
    delete this.detailGridInfoMap[id];
  }
  /** Returns the `DetailGridInfo` corresponding to the supplied `detailGridId`. */
  getDetailGridInfo(id) {
    return this.detailGridInfoMap[id];
  }
  /** Iterates through each `DetailGridInfo` in the grid and calls the supplied callback on each. */
  forEachDetailGridInfo(callback) {
    let index = 0;
    iterateObject(this.detailGridInfoMap, (id, gridInfo) => {
      if (exists(gridInfo)) {
        callback(gridInfo, index);
        index++;
      }
    });
  }
  /** Similar to `exportDataAsCsv`, except returns the result as a string rather than download it. */
  getDataAsCsv(params) {
    if (ModuleRegistry.__assertRegistered("@ag-grid-community/csv-export" /* CsvExportModule */, "api.getDataAsCsv", this.context.getGridId())) {
      return this.csvCreator.getDataAsCsv(params);
    }
  }
  /** Downloads a CSV export of the grid's data. */
  exportDataAsCsv(params) {
    if (ModuleRegistry.__assertRegistered("@ag-grid-community/csv-export" /* CsvExportModule */, "api.exportDataAsCsv", this.context.getGridId())) {
      this.csvCreator.exportDataAsCsv(params);
    }
  }
  assertNotExcelMultiSheet(method, params) {
    if (!ModuleRegistry.__assertRegistered("@ag-grid-enterprise/excel-export" /* ExcelExportModule */, "api." + method, this.context.getGridId())) {
      return false;
    }
    if (this.excelCreator.getFactoryMode() === 1 /* MULTI_SHEET */) {
      console.warn("AG Grid: The Excel Exporter is currently on Multi Sheet mode. End that operation by calling 'api.getMultipleSheetAsExcel()' or 'api.exportMultipleSheetsAsExcel()'");
      return false;
    }
    return true;
  }
  /** Similar to `exportDataAsExcel`, except instead of downloading a file, it will return a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) to be processed by the user. */
  getDataAsExcel(params) {
    if (this.assertNotExcelMultiSheet("getDataAsExcel", params)) {
      return this.excelCreator.getDataAsExcel(params);
    }
  }
  /** Downloads an Excel export of the grid's data. */
  exportDataAsExcel(params) {
    if (this.assertNotExcelMultiSheet("exportDataAsExcel", params)) {
      this.excelCreator.exportDataAsExcel(params);
    }
  }
  /** This is method to be used to get the grid's data as a sheet, that will later be exported either by `getMultipleSheetsAsExcel()` or `exportMultipleSheetsAsExcel()`. */
  getSheetDataForExcel(params) {
    if (!ModuleRegistry.__assertRegistered("@ag-grid-enterprise/excel-export" /* ExcelExportModule */, "api.getSheetDataForExcel", this.context.getGridId())) {
      return;
    }
    this.excelCreator.setFactoryMode(1 /* MULTI_SHEET */);
    return this.excelCreator.getSheetDataForExcel(params);
  }
  /** Similar to `exportMultipleSheetsAsExcel`, except instead of downloading a file, it will return a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) to be processed by the user. */
  getMultipleSheetsAsExcel(params) {
    if (ModuleRegistry.__assertRegistered("@ag-grid-enterprise/excel-export" /* ExcelExportModule */, "api.getMultipleSheetsAsExcel", this.context.getGridId())) {
      return this.excelCreator.getMultipleSheetsAsExcel(params);
    }
  }
  /** Downloads an Excel export of multiple sheets in one file. */
  exportMultipleSheetsAsExcel(params) {
    if (ModuleRegistry.__assertRegistered("@ag-grid-enterprise/excel-export" /* ExcelExportModule */, "api.exportMultipleSheetsAsExcel", this.context.getGridId())) {
      this.excelCreator.exportMultipleSheetsAsExcel(params);
    }
  }
  /**
   * Sets an ARIA property in the grid panel (element with `role=\"grid\"`), and removes an ARIA property when the value is null.
   *
   * Example: `api.setGridAriaProperty('label', 'my grid')` will set `aria-label=\"my grid\"`.
   *
   * `api.setGridAriaProperty('label', null)` will remove the `aria-label` attribute from the grid element.
   */
  setGridAriaProperty(property, value) {
    if (!property) {
      return;
    }
    const eGrid = this.ctrlsService.getGridBodyCtrl().getGui();
    const ariaProperty = `aria-${property}`;
    if (value === null) {
      eGrid.removeAttribute(ariaProperty);
    } else {
      eGrid.setAttribute(ariaProperty, value);
    }
  }
  logMissingRowModel(apiMethod, ...requiredRowModels) {
    console.error(`AG Grid: api.${apiMethod} can only be called when gridOptions.rowModelType is ${requiredRowModels.join(" or ")}`);
  }
  logDeprecation(version, apiMethod, replacement, message) {
    warnOnce(`Since ${version} api.${apiMethod} is deprecated. Please use ${replacement} instead. ${message != null ? message : ""}`);
  }
  /** Gets the number of top pinned rows. */
  getPinnedTopRowCount() {
    return this.pinnedRowModel.getPinnedTopRowCount();
  }
  /** Gets the number of bottom pinned rows. */
  getPinnedBottomRowCount() {
    return this.pinnedRowModel.getPinnedBottomRowCount();
  }
  /** Gets the top pinned row with the specified index. */
  getPinnedTopRow(index) {
    return this.pinnedRowModel.getPinnedTopRow(index);
  }
  /** Gets the bottom pinned row with the specified index. */
  getPinnedBottomRow(index) {
    return this.pinnedRowModel.getPinnedBottomRow(index);
  }
  expireValueCache() {
    this.valueCache.expire();
  }
  /**
   * Returns an object with two properties:
   *  - `top`: The top pixel position of the current scroll in the grid
   *  - `bottom`: The bottom pixel position of the current scroll in the grid
   */
  getVerticalPixelRange() {
    return this.gridBodyCtrl.getScrollFeature().getVScrollPosition();
  }
  /**
   * Returns an object with two properties:
   * - `left`: The left pixel position of the current scroll in the grid
   * - `right`: The right pixel position of the current scroll in the grid
   */
  getHorizontalPixelRange() {
    return this.gridBodyCtrl.getScrollFeature().getHScrollPosition();
  }
  /** Performs change detection on all cells, refreshing cells where required. */
  refreshCells(params = {}) {
    this.frameworkOverrides.wrapIncoming(() => this.rowRenderer.refreshCells(params));
  }
  /** Flash rows, columns or individual cells. */
  flashCells(params = {}) {
    const warning = (prop) => warnOnce(`Since v31.1 api.flashCells parameter '${prop}Delay' is deprecated. Please use '${prop}Duration' instead.`);
    if (exists(params.fadeDelay)) {
      warning("fade");
    }
    if (exists(params.flashDelay)) {
      warning("flash");
    }
    this.frameworkOverrides.wrapIncoming(() => this.rowRenderer.flashCells(params));
  }
  /** Remove row(s) from the DOM and recreate them again from scratch. */
  redrawRows(params = {}) {
    const rowNodes = params ? params.rowNodes : void 0;
    this.frameworkOverrides.wrapIncoming(() => this.rowRenderer.redrawRows(rowNodes));
  }
  /** Redraws the header. Useful if a column name changes, or something else that changes how the column header is displayed. */
  refreshHeader() {
    this.frameworkOverrides.wrapIncoming(() => this.ctrlsService.getHeaderRowContainerCtrls().forEach((c) => c.refresh()));
  }
  /** Returns `true` if any filter is set. This includes quick filter, column filter, external filter or advanced filter. */
  isAnyFilterPresent() {
    return this.filterManager.isAnyFilterPresent();
  }
  /** Returns `true` if any column filter is set, otherwise `false`. */
  isColumnFilterPresent() {
    return this.filterManager.isColumnFilterPresent() || this.filterManager.isAggregateFilterPresent();
  }
  /** Returns `true` if the Quick Filter is set, otherwise `false`. */
  isQuickFilterPresent() {
    return this.filterManager.isQuickFilterPresent();
  }
  /**
   * Returns the row model inside the table.
   * From here you can see the original rows, rows after filter has been applied,
   * rows after aggregation has been applied, and the final set of 'to be displayed' rows.
   *
   * @deprecated As of v31.1, getModel() is deprecated and will not be available in future versions.
   * Please use the appropriate grid API methods instead
   */
  getModel() {
    warnOnce("Since v31.1 getModel() is deprecated. Please use the appropriate grid API methods instead.");
    return this.rowModel;
  }
  /** 
   * Expand or collapse a specific row node, optionally expanding/collapsing all of its parent nodes.
   * By default rows are expanded asynchronously for best performance. Set forceSync: `true` if you need to interact with the expanded row immediately after this function.
   */
  setRowNodeExpanded(rowNode, expanded, expandParents, forceSync) {
    this.expansionService.setRowNodeExpanded(rowNode, expanded, expandParents, forceSync);
  }
  /**
   * Informs the grid that row group expanded state has changed and it needs to rerender the group nodes.
   * Typically called after updating the row node expanded state explicitly, i.e `rowNode.expanded = false`,
   * across multiple groups and you want to update the grid view in a single rerender instead of on every group change.
   */
  onGroupExpandedOrCollapsed() {
    if (missing(this.clientSideRowModel)) {
      this.logMissingRowModel("onGroupExpandedOrCollapsed", "clientSide");
      return;
    }
    this.expansionService.onGroupExpandedOrCollapsed();
  }
  /**
   * Refresh the Client-Side Row Model, executing the grouping, filtering and sorting again.
   * Optionally provide the step you wish the refresh to apply from. Defaults to `everything`.
   */
  refreshClientSideRowModel(step) {
    if (missing(this.clientSideRowModel)) {
      this.logMissingRowModel("refreshClientSideRowModel", "clientSide");
      return;
    }
    this.clientSideRowModel.refreshModel(step);
  }
  /** Returns `true` when there are no more animation frames left to process. */
  isAnimationFrameQueueEmpty() {
    return this.animationFrameService.isQueueEmpty();
  }
  flushAllAnimationFrames() {
    this.animationFrameService.flushAllFrames();
  }
  /**
   * Returns the row node with the given ID.
   * The row node ID is the one you provide from the callback `getRowId(params)`,
   * otherwise the ID is a number (cast as string) auto-generated by the grid when
   * the row data is set.
   */
  getRowNode(id) {
    return this.rowModel.getRowNode(id);
  }
  /**
   * Gets the sizes that various UI elements will be rendered at with the current theme.
   * If you override the row or header height using `gridOptions`, the override value you provided will be returned.
   */
  getSizesForCurrentTheme() {
    return {
      rowHeight: this.gos.getRowHeightAsNumber(),
      headerHeight: this.columnModel.getHeaderHeight()
    };
  }
  /** Expand all groups. */
  expandAll() {
    if (this.clientSideRowModel || this.serverSideRowModel) {
      this.expansionService.expandAll(true);
    } else {
      this.logMissingRowModel("expandAll", "clientSide", "serverSide");
    }
  }
  /** Collapse all groups. */
  collapseAll() {
    if (this.clientSideRowModel || this.serverSideRowModel) {
      this.expansionService.expandAll(false);
    } else {
      this.logMissingRowModel("collapseAll", "clientSide", "serverSide");
    }
  }
  /**
   * Registers a callback to a virtual row.
   * A virtual row is a row that is visually rendered on the screen (rows that are not visible because of the scroll position are not rendered).
   * Unlike normal events, you do not need to unregister rendered row listeners.
   * When the rendered row is removed from the grid, all associated rendered row listeners will also be removed.
   * listen for this event if your `cellRenderer` needs to do cleanup when the row no longer exists.
   */
  addRenderedRowListener(eventName, rowIndex, callback) {
    this.rowRenderer.addRenderedRowListener(eventName, rowIndex, callback);
  }
  /** Get the current Quick Filter text from the grid, or `undefined` if none is set. */
  getQuickFilter() {
    return this.gos.get("quickFilterText");
  }
  /** Get the state of the Advanced Filter. Used for saving Advanced Filter state */
  getAdvancedFilterModel() {
    if (ModuleRegistry.__assertRegistered("@ag-grid-enterprise/advanced-filter" /* AdvancedFilterModule */, "api.getAdvancedFilterModel", this.context.getGridId())) {
      return this.filterManager.getAdvancedFilterModel();
    }
    return null;
  }
  /** Set the state of the Advanced Filter. Used for restoring Advanced Filter state */
  setAdvancedFilterModel(advancedFilterModel) {
    this.filterManager.setAdvancedFilterModel(advancedFilterModel);
  }
  /** Open the Advanced Filter Builder dialog (if enabled). */
  showAdvancedFilterBuilder() {
    if (ModuleRegistry.__assertRegistered("@ag-grid-enterprise/advanced-filter" /* AdvancedFilterModule */, "api.setAdvancedFilterModel", this.context.getGridId())) {
      this.filterManager.showAdvancedFilterBuilder("api");
    }
  }
  /**
   * Set all of the provided nodes selection state to the provided value.
   */
  setNodesSelected(params) {
    const allNodesValid = params.nodes.every((node) => {
      if (node.rowPinned) {
        console.warn("AG Grid: cannot select pinned rows");
        return false;
      }
      if (node.id === void 0) {
        console.warn("AG Grid: cannot select node until id for node is known");
        return false;
      }
      return true;
    });
    if (!allNodesValid) {
      return;
    }
    const { nodes, source, newValue } = params;
    const nodesAsRowNode = nodes;
    this.selectionService.setNodesSelected({ nodes: nodesAsRowNode, source: source != null ? source : "api", newValue });
  }
  /**
   * Select all rows, regardless of filtering and rows that are not visible due to grouping being enabled and their groups not expanded.
   * @param source Source property that will appear in the `selectionChanged` event, defaults to `'apiSelectAll'`
   */
  selectAll(source = "apiSelectAll") {
    this.selectionService.selectAllRowNodes({ source });
  }
  /**
   * Clear all row selections, regardless of filtering.
   * @param source Source property that will appear in the `selectionChanged` event, defaults to `'apiSelectAll'`
   */
  deselectAll(source = "apiSelectAll") {
    this.selectionService.deselectAllRowNodes({ source });
  }
  /**
   * Select all filtered rows.
   * @param source Source property that will appear in the `selectionChanged` event, defaults to `'apiSelectAllFiltered'`
   */
  selectAllFiltered(source = "apiSelectAllFiltered") {
    this.selectionService.selectAllRowNodes({ source, justFiltered: true });
  }
  /**
   * Clear all filtered selections.
   * @param source Source property that will appear in the `selectionChanged` event, defaults to `'apiSelectAllFiltered'`
   */
  deselectAllFiltered(source = "apiSelectAllFiltered") {
    this.selectionService.deselectAllRowNodes({ source, justFiltered: true });
  }
  /**
   * Returns an object containing rules matching the selected rows in the SSRM.
   * 
   * If `groupSelectsChildren=false` the returned object will be flat, and will conform to IServerSideSelectionState.
   * If `groupSelectsChildren=true` the returned object will be hierarchical, and will conform to IServerSideGroupSelectionState.
   */
  getServerSideSelectionState() {
    if (missing(this.serverSideRowModel)) {
      this.logMissingRowModel("getServerSideSelectionState", "serverSide");
      return null;
    }
    return this.selectionService.getSelectionState();
  }
  /**
   * Set the rules matching the selected rows in the SSRM.
   * 
   * If `groupSelectsChildren=false` the param will be flat, and should conform to IServerSideSelectionState.
   * If `groupSelectsChildren=true` the param will be hierarchical, and should conform to IServerSideGroupSelectionState.
   */
  setServerSideSelectionState(state) {
    if (missing(this.serverSideRowModel)) {
      this.logMissingRowModel("setServerSideSelectionState", "serverSide");
      return;
    }
    this.selectionService.setSelectionState(state, "api");
  }
  /**
   * Select all rows on the current page.
   * @param source Source property that will appear in the `selectionChanged` event, defaults to `'apiSelectAllCurrentPage'`
   */
  selectAllOnCurrentPage(source = "apiSelectAllCurrentPage") {
    this.selectionService.selectAllRowNodes({ source, justCurrentPage: true });
  }
  /**
   * Clear all filtered on the current page.
   * @param source Source property that will appear in the `selectionChanged` event, defaults to `'apiSelectAllCurrentPage'`
   */
  deselectAllOnCurrentPage(source = "apiSelectAllCurrentPage") {
    this.selectionService.deselectAllRowNodes({ source, justCurrentPage: true });
  }
  /** Show the 'loading' overlay. */
  showLoadingOverlay() {
    this.overlayService.showLoadingOverlay();
  }
  /** Show the 'no rows' overlay. */
  showNoRowsOverlay() {
    this.overlayService.showNoRowsOverlay();
  }
  /** Hides the overlay if showing. */
  hideOverlay() {
    this.overlayService.hideOverlay();
  }
  /**
   * Returns an unsorted list of selected nodes.
   * Getting the underlying node (rather than the data) is useful when working with tree / aggregated data,
   * as the node can be traversed.
   */
  getSelectedNodes() {
    return this.selectionService.getSelectedNodes();
  }
  /** Returns an unsorted list of selected rows (i.e. row data that you provided). */
  getSelectedRows() {
    return this.selectionService.getSelectedRows();
  }
  /**
   * Returns a list of all selected nodes at 'best cost', a feature to be used with groups / trees.
   * If a group has all its children selected, then the group appears in the result, but not the children.
   * Designed for use with `'children'` as the group selection type, where groups don't actually appear in the selection normally.
   */
  getBestCostNodeSelection() {
    if (missing(this.clientSideRowModel)) {
      this.logMissingRowModel("getBestCostNodeSelection", "clientSide");
      return;
    }
    return this.selectionService.getBestCostNodeSelection();
  }
  /** Retrieve rendered nodes. Due to virtualisation this will contain only the current visible rows and those in the buffer. */
  getRenderedNodes() {
    return this.rowRenderer.getRenderedNodes();
  }
  /**
   *  Ensures the column is visible by scrolling the table if needed.
   *
   * This will have no effect before the firstDataRendered event has fired.
   *
   * @param key - The column to ensure visible
   * @param position - Where the column will be positioned.
   * - `auto` - Scrolls the minimum amount to make sure the column is visible.
   * - `start` - Scrolls the column to the start of the viewport.
   * - `middle` - Scrolls the column to the middle of the viewport.
   * - `end` - Scrolls the column to the end of the viewport.
  */
  ensureColumnVisible(key, position = "auto") {
    this.frameworkOverrides.wrapIncoming(() => this.gridBodyCtrl.getScrollFeature().ensureColumnVisible(key, position), "ensureVisible");
  }
  /**
   * Vertically scrolls the grid until the provided row index is inside the visible viewport.
   * If a position is provided, the grid will attempt to scroll until the row is at the given position within the viewport.
   * This will have no effect before the firstDataRendered event has fired.
   */
  ensureIndexVisible(index, position) {
    this.frameworkOverrides.wrapIncoming(() => this.gridBodyCtrl.getScrollFeature().ensureIndexVisible(index, position), "ensureVisible");
  }
  /**
   * Vertically scrolls the grid until the provided row (or a row matching the provided comparator) is inside the visible viewport.
   * If a position is provided, the grid will attempt to scroll until the row is at the given position within the viewport.
   * This will have no effect before the firstDataRendered event has fired.
   */
  ensureNodeVisible(nodeSelector, position = null) {
    this.frameworkOverrides.wrapIncoming(() => this.gridBodyCtrl.getScrollFeature().ensureNodeVisible(nodeSelector, position), "ensureVisible");
  }
  /**
   * Similar to `forEachNode`, except lists all the leaf nodes.
   * This effectively goes through all the data that you provided to the grid before the grid performed any grouping.
   * If using tree data, goes through all the nodes for the data you provided, including nodes that have children,
   * but excluding groups the grid created where gaps were missing in the hierarchy.
   */
  forEachLeafNode(callback) {
    if (missing(this.clientSideRowModel)) {
      this.logMissingRowModel("forEachLeafNode", "clientSide");
      return;
    }
    this.clientSideRowModel.forEachLeafNode(callback);
  }
  /**
   * Iterates through each node (row) in the grid and calls the callback for each node.
   * This works similar to the `forEach` method on a JavaScript array.
   * This is called for every node, ignoring any filtering or sorting applied within the grid.
   * If using the Infinite Row Model, then this gets called for each page loaded in the page cache.
   */
  forEachNode(callback, includeFooterNodes) {
    this.rowModel.forEachNode(callback, includeFooterNodes);
  }
  /** Similar to `forEachNode`, except skips any filtered out data. */
  forEachNodeAfterFilter(callback) {
    if (missing(this.clientSideRowModel)) {
      this.logMissingRowModel("forEachNodeAfterFilter", "clientSide");
      return;
    }
    this.clientSideRowModel.forEachNodeAfterFilter(callback);
  }
  /** Similar to `forEachNodeAfterFilter`, except the callbacks are called in the order the rows are displayed in the grid. */
  forEachNodeAfterFilterAndSort(callback) {
    if (missing(this.clientSideRowModel)) {
      this.logMissingRowModel("forEachNodeAfterFilterAndSort", "clientSide");
      return;
    }
    this.clientSideRowModel.forEachNodeAfterFilterAndSort(callback);
  }
  /**
   * @deprecated v31.1 To get/set individual filter models, use `getColumnFilterModel` or `setColumnFilterModel` instead.
   * To get hold of the filter instance, use `getColumnFilterInstance` which returns the instance asynchronously.
   */
  getFilterInstance(key, callback) {
    warnOnce(`'getFilterInstance' is deprecated. To get/set individual filter models, use 'getColumnFilterModel' or 'setColumnFilterModel' instead. To get hold of the filter instance, use 'getColumnFilterInstance' which returns the instance asynchronously.`);
    return this.filterManager.getFilterInstance(key, callback);
  }
  /**
   * Returns the filter component instance for a column.
   * For getting/setting models for individual column filters, use `getColumnFilterModel` and `setColumnFilterModel` instead of this.
   * `key` can be a column ID or a `Column` object.
   */
  getColumnFilterInstance(key) {
    return this.filterManager.getColumnFilterInstance(key);
  }
  /** Destroys a filter. Useful to force a particular filter to be created from scratch again. */
  destroyFilter(key) {
    const column = this.columnModel.getPrimaryColumn(key);
    if (column) {
      return this.filterManager.destroyFilter(column, "api");
    }
  }
  /** Gets the status panel instance corresponding to the supplied `id`. */
  getStatusPanel(key) {
    if (!ModuleRegistry.__assertRegistered("@ag-grid-enterprise/status-bar" /* StatusBarModule */, "api.getStatusPanel", this.context.getGridId())) {
      return;
    }
    const comp = this.statusBarService.getStatusPanel(key);
    return unwrapUserComp(comp);
  }
  getColumnDef(key) {
    const column = this.columnModel.getPrimaryColumn(key);
    if (column) {
      return column.getColDef();
    }
    return null;
  }
  /**
   * Returns the current column definitions.
  */
  getColumnDefs() {
    return this.columnModel.getColumnDefs();
  }
  /**
   * Informs the grid that a filter has changed. This is typically called after a filter change through one of the filter APIs.
   * @param source The source of the filter change event. If not specified defaults to `'api'`.
   */
  onFilterChanged(source = "api") {
    this.filterManager.onFilterChanged({ source });
  }
  /**
   * Gets the grid to act as if the sort was changed.
   * Useful if you update some values and want to get the grid to reorder them according to the new values.
   */
  onSortChanged() {
    this.sortController.onSortChanged("api");
  }
  /**
   * Sets the state of all the column filters. Provide it with what you get from `getFilterModel()` to restore filter state.
   * If inferring cell data types, and row data is provided asynchronously and is yet to be set,
   * the filter model will be applied asynchronously after row data is added.
   * To always perform this synchronously, set `cellDataType = false` on the default column definition,
   * or provide cell data types for every column.
   */
  setFilterModel(model) {
    this.frameworkOverrides.wrapIncoming(() => this.filterManager.setFilterModel(model));
  }
  /** Gets the current state of all the column filters. Used for saving filter state. */
  getFilterModel() {
    return this.filterManager.getFilterModel();
  }
  /**
   * Gets the current filter model for the specified column.
   * Will return `null` if no active filter.
   */
  getColumnFilterModel(column) {
    return this.filterManager.getColumnFilterModel(column);
  }
  /**
   * Sets the filter model for the specified column.
   * Setting a `model` of `null` will reset the filter (make inactive).
   * Must wait on the response before calling `api.onFilterChanged()`.
   */
  setColumnFilterModel(column, model) {
    return this.filterManager.setColumnFilterModel(column, model);
  }
  /** Returns the focused cell (or the last focused cell if the grid lost focus). */
  getFocusedCell() {
    return this.focusService.getFocusedCell();
  }
  /** Clears the focused cell. */
  clearFocusedCell() {
    return this.focusService.clearFocusedCell();
  }
  /** Sets the focus to the specified cell. `rowPinned` can be either 'top', 'bottom' or null (for not pinned). */
  setFocusedCell(rowIndex, colKey, rowPinned) {
    this.focusService.setFocusedCell({ rowIndex, column: colKey, rowPinned, forceBrowserFocus: true });
  }
  /** Adds a drop zone outside of the grid where rows can be dropped. */
  addRowDropZone(params) {
    this.gridBodyCtrl.getRowDragFeature().addRowDropZone(params);
  }
  /** Removes an external drop zone added by `addRowDropZone`. */
  removeRowDropZone(params) {
    const activeDropTarget = this.dragAndDropService.findExternalZone(params);
    if (activeDropTarget) {
      this.dragAndDropService.removeDropTarget(activeDropTarget);
    }
  }
  /** Returns the `RowDropZoneParams` to be used by another grid's `addRowDropZone` method. */
  getRowDropZoneParams(events) {
    return this.gridBodyCtrl.getRowDragFeature().getRowDropZone(events);
  }
  assertSideBarLoaded(apiMethod) {
    return ModuleRegistry.__assertRegistered("@ag-grid-enterprise/side-bar" /* SideBarModule */, "api." + apiMethod, this.context.getGridId());
  }
  /** Returns `true` if the side bar is visible. */
  isSideBarVisible() {
    return this.assertSideBarLoaded("isSideBarVisible") && this.sideBarService.getSideBarComp().isDisplayed();
  }
  /** Show/hide the entire side bar, including any visible panel and the tab buttons. */
  setSideBarVisible(show) {
    if (this.assertSideBarLoaded("setSideBarVisible")) {
      this.sideBarService.getSideBarComp().setDisplayed(show);
    }
  }
  /** Sets the side bar position relative to the grid. Possible values are `'left'` or `'right'`. */
  setSideBarPosition(position) {
    if (this.assertSideBarLoaded("setSideBarPosition")) {
      this.sideBarService.getSideBarComp().setSideBarPosition(position);
    }
  }
  /** Opens a particular tool panel. Provide the ID of the tool panel to open. */
  openToolPanel(key) {
    if (this.assertSideBarLoaded("openToolPanel")) {
      this.sideBarService.getSideBarComp().openToolPanel(key, "api");
    }
  }
  /** Closes the currently open tool panel (if any). */
  closeToolPanel() {
    if (this.assertSideBarLoaded("closeToolPanel")) {
      this.sideBarService.getSideBarComp().close("api");
    }
  }
  /** Returns the ID of the currently shown tool panel if any, otherwise `null`. */
  getOpenedToolPanel() {
    if (this.assertSideBarLoaded("getOpenedToolPanel")) {
      return this.sideBarService.getSideBarComp().openedItem();
    }
    return null;
  }
  /** Force refresh all tool panels by calling their `refresh` method. */
  refreshToolPanel() {
    if (this.assertSideBarLoaded("refreshToolPanel")) {
      this.sideBarService.getSideBarComp().refresh();
    }
  }
  /** Returns `true` if the tool panel is showing, otherwise `false`. */
  isToolPanelShowing() {
    return this.assertSideBarLoaded("isToolPanelShowing") && this.sideBarService.getSideBarComp().isToolPanelShowing();
  }
  /** Gets the tool panel instance corresponding to the supplied `id`. */
  getToolPanelInstance(id) {
    if (this.assertSideBarLoaded("getToolPanelInstance")) {
      const comp = this.sideBarService.getSideBarComp().getToolPanelInstance(id);
      return unwrapUserComp(comp);
    }
  }
  /** Returns the current side bar configuration. If a shortcut was used, returns the detailed long form. */
  getSideBar() {
    if (this.assertSideBarLoaded("getSideBar")) {
      return this.sideBarService.getSideBarComp().getDef();
    }
    return void 0;
  }
  /** Tells the grid to recalculate the row heights. */
  resetRowHeights() {
    if (exists(this.clientSideRowModel)) {
      if (this.columnModel.isAutoRowHeightActive()) {
        console.warn("AG Grid: calling gridApi.resetRowHeights() makes no sense when using Auto Row Height.");
        return;
      }
      this.clientSideRowModel.resetRowHeights();
    }
  }
  /**
   * Sets the `rowCount` and `maxRowFound` properties.
   * The second parameter, `maxRowFound`, is optional and if left out, only `rowCount` is set.
   * Set `rowCount` to adjust the height of the vertical scroll.
   * Set `maxRowFound` to enable / disable searching for more rows.
   * Use this method if you add or remove rows into the dataset and need to reset the number of rows or instruct the grid that the entire row count is no longer known.
   */
  setRowCount(rowCount, maxRowFound) {
    if (this.serverSideRowModel) {
      if (this.columnModel.isRowGroupEmpty()) {
        this.serverSideRowModel.setRowCount(rowCount, maxRowFound);
        return;
      }
      console.error("AG Grid: setRowCount cannot be used while using row grouping.");
      return;
    }
    if (this.infiniteRowModel) {
      this.infiniteRowModel.setRowCount(rowCount, maxRowFound);
      return;
    }
    this.logMissingRowModel("setRowCount", "infinite", "serverSide");
  }
  /** Tells the grid a row height has changed. To be used after calling `rowNode.setRowHeight(newHeight)`. */
  onRowHeightChanged() {
    if (this.clientSideRowModel) {
      this.clientSideRowModel.onRowHeightChanged();
    } else if (this.serverSideRowModel) {
      this.serverSideRowModel.onRowHeightChanged();
    }
  }
  /**
   * @deprecated v31.3 Use `getCellValue` instead.
   */
  getValue(colKey, rowNode) {
    this.logDeprecation("31.3", "getValue", "getCellValue");
    return this.getCellValue({ colKey, rowNode });
  }
  getCellValue(params) {
    var _a;
    const { colKey, rowNode, useFormatter } = params;
    let column = (_a = this.columnModel.getPrimaryColumn(colKey)) != null ? _a : this.columnModel.getGridColumn(colKey);
    if (missing(column)) {
      return null;
    }
    const value = this.valueService.getValue(column, rowNode);
    if (useFormatter) {
      const formattedValue = this.valueService.formatValue(column, rowNode, value);
      return formattedValue != null ? formattedValue : escapeString(value, true);
    }
    return value;
  }
  /**
   * Add an event listener for the specified `eventType`.
   * Works similar to `addEventListener` for a browser DOM element.
   * Listeners will be automatically removed when the grid is destroyed.
   */
  addEventListener(eventType, listener) {
    this.apiEventService.addEventListener(eventType, listener);
  }
  /**
   * Add an event listener for all event types coming from the grid.
   * Listeners will be automatically removed when the grid is destroyed.
   */
  addGlobalListener(listener) {
    this.apiEventService.addGlobalListener(listener);
  }
  /** Remove an event listener. */
  removeEventListener(eventType, listener) {
    this.apiEventService.removeEventListener(eventType, listener);
  }
  /** Remove a global event listener. */
  removeGlobalListener(listener) {
    this.apiEventService.removeGlobalListener(listener);
  }
  dispatchEvent(event) {
    this.eventService.dispatchEvent(event);
  }
  /** Will destroy the grid and release resources. If you are using a framework you do not need to call this, as the grid links in with the framework lifecycle. However if you are using Web Components or native JavaScript, you do need to call this, to avoid a memory leak in your application. */
  destroy() {
    var _a;
    const preDestroyLink = `See ${this.frameworkOverrides.getDocLink("grid-lifecycle/#grid-pre-destroyed")}`;
    if (this.destroyCalled) {
      return;
    }
    const event = {
      type: Events.EVENT_GRID_PRE_DESTROYED,
      state: this.getState()
    };
    this.dispatchEvent(event);
    this.destroyCalled = true;
    (_a = this.ctrlsService.get("gridCtrl")) == null ? void 0 : _a.destroyGridUi();
    this.context.destroy();
    this.detailGridInfoMap = {};
    removeAllReferences(this, ["isDestroyed"], preDestroyLink);
  }
  /** Returns `true` if the grid has been destroyed. */
  isDestroyed() {
    return this.destroyCalled;
  }
  /** Reset the Quick Filter cache text on every rowNode. */
  resetQuickFilter() {
    this.filterManager.resetQuickFilterCache();
  }
  /** Returns the list of selected cell ranges. */
  getCellRanges() {
    if (this.rangeService) {
      return this.rangeService.getCellRanges();
    }
    ModuleRegistry.__assertRegistered("@ag-grid-enterprise/range-selection" /* RangeSelectionModule */, "api.getCellRanges", this.context.getGridId());
    return null;
  }
  /** Adds the provided cell range to the selected ranges. */
  addCellRange(params) {
    if (this.rangeService) {
      this.rangeService.addCellRange(params);
      return;
    }
    ModuleRegistry.__assertRegistered("@ag-grid-enterprise/range-selection" /* RangeSelectionModule */, "api.addCellRange", this.context.getGridId());
  }
  /** Clears the selected ranges. */
  clearRangeSelection() {
    if (this.rangeService) {
      this.rangeService.removeAllCellRanges();
    }
    ModuleRegistry.__assertRegistered("@ag-grid-enterprise/range-selection" /* RangeSelectionModule */, "gridApi.clearRangeSelection", this.context.getGridId());
  }
  /** Reverts the last cell edit. */
  undoCellEditing() {
    this.undoRedoService.undo("api");
  }
  /** Re-applies the most recently undone cell edit. */
  redoCellEditing() {
    this.undoRedoService.redo("api");
  }
  /** Returns current number of available cell edit undo operations. */
  getCurrentUndoSize() {
    return this.undoRedoService.getCurrentUndoStackSize();
  }
  /** Returns current number of available cell edit redo operations. */
  getCurrentRedoSize() {
    return this.undoRedoService.getCurrentRedoStackSize();
  }
  assertChart(methodName, func) {
    if (ModuleRegistry.__assertRegistered("@ag-grid-enterprise/charts" /* GridChartsModule */, "api." + methodName, this.context.getGridId())) {
      return this.frameworkOverrides.wrapIncoming(() => func());
    }
  }
  /** Returns a list of models with information about the charts that are currently rendered from the grid. */
  getChartModels() {
    return this.assertChart("getChartModels", () => this.chartService.getChartModels());
  }
  /** Returns the `ChartRef` using the supplied `chartId`. */
  getChartRef(chartId) {
    return this.assertChart("getChartRef", () => this.chartService.getChartRef(chartId));
  }
  /** Returns a base64-encoded image data URL for the referenced chartId. */
  getChartImageDataURL(params) {
    return this.assertChart("getChartImageDataURL", () => this.chartService.getChartImageDataURL(params));
  }
  /** Starts a browser-based image download for the referenced chartId. */
  downloadChart(params) {
    return this.assertChart("downloadChart", () => this.chartService.downloadChart(params));
  }
  /** Open the Chart Tool Panel. */
  openChartToolPanel(params) {
    return this.assertChart("openChartToolPanel", () => this.chartService.openChartToolPanel(params));
  }
  /** Close the Chart Tool Panel. */
  closeChartToolPanel(params) {
    return this.assertChart("closeChartToolPanel", () => this.chartService.closeChartToolPanel(params.chartId));
  }
  /** Used to programmatically create charts from a range. */
  createRangeChart(params) {
    return this.assertChart("createRangeChart", () => this.chartService.createRangeChart(params));
  }
  /** Used to programmatically create pivot charts from a grid. */
  createPivotChart(params) {
    return this.assertChart("createPivotChart", () => this.chartService.createPivotChart(params));
  }
  /** Used to programmatically create cross filter charts from a range. */
  createCrossFilterChart(params) {
    return this.assertChart("createCrossFilterChart", () => this.chartService.createCrossFilterChart(params));
  }
  /** Used to programmatically update a chart. */
  updateChart(params) {
    return this.assertChart("updateChart", () => this.chartService.updateChart(params));
  }
  /** Restores a chart using the `ChartModel` that was previously obtained from `getChartModels()`. */
  restoreChart(chartModel, chartContainer) {
    return this.assertChart("restoreChart", () => this.chartService.restoreChart(chartModel, chartContainer));
  }
  assertClipboard(methodName, func) {
    if (ModuleRegistry.__assertRegistered("@ag-grid-enterprise/clipboard" /* ClipboardModule */, "api" + methodName, this.context.getGridId())) {
      func();
    }
  }
  /** Copies data to clipboard by following the same rules as pressing Ctrl+C. */
  copyToClipboard(params) {
    this.assertClipboard("copyToClipboard", () => this.clipboardService.copyToClipboard(params));
  }
  /** Cuts data to clipboard by following the same rules as pressing Ctrl+X. */
  cutToClipboard(params) {
    this.assertClipboard("cutToClipboard", () => this.clipboardService.cutToClipboard(params));
  }
  /** Copies the selected rows to the clipboard. */
  copySelectedRowsToClipboard(params) {
    this.assertClipboard("copySelectedRowsToClipboard", () => this.clipboardService.copySelectedRowsToClipboard(params));
  }
  /** Copies the selected ranges to the clipboard. */
  copySelectedRangeToClipboard(params) {
    this.assertClipboard("copySelectedRangeToClipboard", () => this.clipboardService.copySelectedRangeToClipboard(params));
  }
  /** Copies the selected range down, similar to `Ctrl + D` in Excel. */
  copySelectedRangeDown() {
    this.assertClipboard("copySelectedRangeDown", () => this.clipboardService.copyRangeDown());
  }
  /** Pastes the data from the Clipboard into the focused cell of the grid. If no grid cell is focused, calling this method has no effect. */
  pasteFromClipboard() {
    this.assertClipboard("pasteFromClipboard", () => this.clipboardService.pasteFromClipboard());
  }
  /** @deprecated v31.1 Use `IHeaderParams.showColumnMenu` within a header component, or `api.showColumnMenu` elsewhere. */
  showColumnMenuAfterButtonClick(colKey, buttonElement) {
    warnOnce(`'showColumnMenuAfterButtonClick' is deprecated. Use 'IHeaderParams.showColumnMenu' within a header component, or 'api.showColumnMenu' elsewhere.`);
    const column = this.columnModel.getGridColumn(colKey);
    this.menuService.showColumnMenu({
      column,
      buttonElement,
      positionBy: "button"
    });
  }
  /** @deprecated v31.1 Use `IHeaderParams.showColumnMenuAfterMouseClick` within a header component, or `api.showColumnMenu` elsewhere. */
  showColumnMenuAfterMouseClick(colKey, mouseEvent) {
    warnOnce(`'showColumnMenuAfterMouseClick' is deprecated. Use 'IHeaderParams.showColumnMenuAfterMouseClick' within a header component, or 'api.showColumnMenu' elsewhere.`);
    let column = this.columnModel.getGridColumn(colKey);
    if (!column) {
      column = this.columnModel.getPrimaryColumn(colKey);
    }
    if (!column) {
      console.error(`AG Grid: column '${colKey}' not found`);
      return;
    }
    this.menuService.showColumnMenu({
      column,
      mouseEvent,
      positionBy: "mouse"
    });
  }
  /**
   * Displays the AG Grid context menu
   */
  showContextMenu(params) {
    const { rowNode, column, value, x, y } = params || {};
    let { x: clientX, y: clientY } = this.menuService.getContextMenuPosition(rowNode, column);
    if (x != null) {
      clientX = x;
    }
    if (y != null) {
      clientY = y;
    }
    this.menuService.showContextMenu({
      mouseEvent: new MouseEvent("mousedown", { clientX, clientY }),
      rowNode,
      column,
      value
    });
  }
  /** Show the column chooser. */
  showColumnChooser(params) {
    this.menuService.showColumnChooser({ chooserParams: params });
  }
  /** Show the filter for the provided column. */
  showColumnFilter(colKey) {
    const column = this.columnModel.getGridColumn(colKey);
    if (!column) {
      console.error(`AG Grid: column '${colKey}' not found`);
      return;
    }
    this.menuService.showFilterMenu({
      column,
      containerType: "columnFilter",
      positionBy: "auto"
    });
  }
  /** Show the column menu for the provided column. */
  showColumnMenu(colKey) {
    const column = this.columnModel.getGridColumn(colKey);
    if (!column) {
      console.error(`AG Grid: column '${colKey}' not found`);
      return;
    }
    this.menuService.showColumnMenu({
      column,
      positionBy: "auto"
    });
  }
  /** Hides any visible context menu or column menu. */
  hidePopupMenu() {
    this.menuService.hidePopupMenu();
  }
  /** Hide the column chooser if visible. */
  hideColumnChooser() {
    this.menuService.hideColumnChooser();
  }
  /** Navigates the grid focus to the next cell, as if tabbing. */
  tabToNextCell(event) {
    return this.navigationService.tabToNextCell(false, event);
  }
  /** Navigates the grid focus to the previous cell, as if shift-tabbing. */
  tabToPreviousCell(event) {
    return this.navigationService.tabToNextCell(true, event);
  }
  /** Returns the list of active cell renderer instances. */
  getCellRendererInstances(params = {}) {
    const res = this.rowRenderer.getCellRendererInstances(params);
    const unwrapped = res.map(unwrapUserComp);
    return unwrapped;
  }
  /** Returns the list of active cell editor instances. Optionally provide parameters to restrict to certain columns / row nodes. */
  getCellEditorInstances(params = {}) {
    const res = this.rowRenderer.getCellEditorInstances(params);
    const unwrapped = res.map(unwrapUserComp);
    return unwrapped;
  }
  /** If the grid is editing, returns back details of the editing cell(s). */
  getEditingCells() {
    return this.rowRenderer.getEditingCells();
  }
  /** If a cell is editing, it stops the editing. Pass `true` if you want to cancel the editing (i.e. don't accept changes). */
  stopEditing(cancel = false) {
    this.rowRenderer.stopEditing(cancel);
  }
  /** Start editing the provided cell. If another cell is editing, the editing will be stopped in that other cell. */
  startEditingCell(params) {
    const column = this.columnModel.getGridColumn(params.colKey);
    if (!column) {
      console.warn(`AG Grid: no column found for ${params.colKey}`);
      return;
    }
    const cellPosition = {
      rowIndex: params.rowIndex,
      rowPinned: params.rowPinned || null,
      column
    };
    const notPinned = params.rowPinned == null;
    if (notPinned) {
      this.ensureIndexVisible(params.rowIndex);
    }
    this.ensureColumnVisible(params.colKey);
    const cell = this.navigationService.getCellByPosition(cellPosition);
    if (!cell) {
      return;
    }
    if (!this.focusService.isCellFocused(cellPosition)) {
      this.focusService.setFocusedCell(cellPosition);
    }
    cell.startRowOrCellEdit(params.key);
  }
  /** @deprecated v31.1 addAggFunc(key, func) is  deprecated, please use addAggFuncs({ key: func }) instead. */
  addAggFunc(key, aggFunc) {
    this.logDeprecation("v31.1", "addAggFunc(key, func)", "addAggFuncs({ key: func })");
    if (this.aggFuncService) {
      this.aggFuncService.addAggFuncs({ key: aggFunc });
    }
  }
  /** Add aggregations function with the specified keys. */
  addAggFuncs(aggFuncs) {
    if (this.aggFuncService) {
      this.aggFuncService.addAggFuncs(aggFuncs);
    }
  }
  /** Clears all aggregation functions (including those provided by the grid). */
  clearAggFuncs() {
    if (this.aggFuncService) {
      this.aggFuncService.clear();
    }
  }
  /** Apply transactions to the server side row model. */
  applyServerSideTransaction(transaction) {
    if (!this.serverSideTransactionManager) {
      this.logMissingRowModel("applyServerSideTransaction", "serverSide");
      return;
    }
    return this.serverSideTransactionManager.applyTransaction(transaction);
  }
  /** Batch apply transactions to the server side row model. */
  applyServerSideTransactionAsync(transaction, callback) {
    if (!this.serverSideTransactionManager) {
      this.logMissingRowModel("applyServerSideTransactionAsync", "serverSide");
      return;
    }
    return this.serverSideTransactionManager.applyTransactionAsync(transaction, callback);
  }
  /**
   * Applies row data to a server side store.
   * New rows will overwrite rows at the same index in the same way as if provided by a datasource success callback.
  */
  applyServerSideRowData(params) {
    var _a, _b;
    const startRow = (_a = params.startRow) != null ? _a : 0;
    const route = (_b = params.route) != null ? _b : [];
    if (startRow < 0) {
      console.warn(`AG Grid: invalid value ${params.startRow} for startRow, the value should be >= 0`);
      return;
    }
    if (this.serverSideRowModel) {
      this.serverSideRowModel.applyRowData(params.successParams, startRow, route);
    } else {
      this.logMissingRowModel("setServerSideDatasource", "serverSide");
    }
  }
  /** Gets all failed server side loads to retry. */
  retryServerSideLoads() {
    if (!this.serverSideRowModel) {
      this.logMissingRowModel("retryServerSideLoads", "serverSide");
      return;
    }
    this.serverSideRowModel.retryLoads();
  }
  flushServerSideAsyncTransactions() {
    if (!this.serverSideTransactionManager) {
      this.logMissingRowModel("flushServerSideAsyncTransactions", "serverSide");
      return;
    }
    return this.serverSideTransactionManager.flushAsyncTransactions();
  }
  /** Update row data. Pass a transaction object with lists for `add`, `remove` and `update`. */
  applyTransaction(rowDataTransaction) {
    if (!this.clientSideRowModel) {
      this.logMissingRowModel("applyTransaction", "clientSide");
      return;
    }
    return this.frameworkOverrides.wrapIncoming(() => this.clientSideRowModel.updateRowData(rowDataTransaction));
  }
  /** Same as `applyTransaction` except executes asynchronously for efficiency. */
  applyTransactionAsync(rowDataTransaction, callback) {
    if (!this.clientSideRowModel) {
      this.logMissingRowModel("applyTransactionAsync", "clientSide");
      return;
    }
    this.frameworkOverrides.wrapIncoming(() => this.clientSideRowModel.batchUpdateRowData(rowDataTransaction, callback));
  }
  /** Executes any remaining asynchronous grid transactions, if any are waiting to be executed. */
  flushAsyncTransactions() {
    if (!this.clientSideRowModel) {
      this.logMissingRowModel("flushAsyncTransactions", "clientSide");
      return;
    }
    this.frameworkOverrides.wrapIncoming(() => this.clientSideRowModel.flushAsyncTransactions());
  }
  /**
   * Marks all the currently loaded blocks in the cache for reload.
   * If you have 10 blocks in the cache, all 10 will be marked for reload.
   * The old data will continue to be displayed until the new data is loaded.
   */
  refreshInfiniteCache() {
    if (this.infiniteRowModel) {
      this.infiniteRowModel.refreshCache();
    } else {
      this.logMissingRowModel("refreshInfiniteCache", "infinite");
    }
  }
  /**
   * Purges the cache.
   * The grid is then told to refresh. Only the blocks required to display the current data on screen are fetched (typically no more than 2).
   * The grid will display nothing while the new blocks are loaded.
   * Use this to immediately remove the old data from the user.
   */
  purgeInfiniteCache() {
    if (this.infiniteRowModel) {
      this.infiniteRowModel.purgeCache();
    } else {
      this.logMissingRowModel("purgeInfiniteCache", "infinite");
    }
  }
  /**
   * Refresh a server-side store level.
   * If you pass no parameters, then the top level store is refreshed.
   * To refresh a child level, pass in the string of keys to get to the desired level.
   * Once the store refresh is complete, the storeRefreshed event is fired.
   */
  refreshServerSide(params) {
    if (!this.serverSideRowModel) {
      this.logMissingRowModel("refreshServerSide", "serverSide");
      return;
    }
    this.serverSideRowModel.refreshStore(params);
  }
  /** Returns info on all server side group levels. */
  getServerSideGroupLevelState() {
    if (!this.serverSideRowModel) {
      this.logMissingRowModel("getServerSideGroupLevelState", "serverSide");
      return [];
    }
    return this.serverSideRowModel.getStoreState();
  }
  /** The row count defines how many rows the grid allows scrolling to. */
  getInfiniteRowCount() {
    if (this.infiniteRowModel) {
      return this.infiniteRowModel.getRowCount();
    } else {
      this.logMissingRowModel("getInfiniteRowCount", "infinite");
    }
  }
  /** Returns `true` if grid allows for scrolling past the last row to load more rows, thus providing infinite scroll. */
  isLastRowIndexKnown() {
    if (this.infiniteRowModel) {
      return this.infiniteRowModel.isLastRowIndexKnown();
    } else {
      this.logMissingRowModel("isLastRowIndexKnown", "infinite");
    }
  }
  /**
   * Returns an object representing the state of the cache. This is useful for debugging and understanding how the cache is working.
   */
  getCacheBlockState() {
    return this.rowNodeBlockLoader.getBlockState();
  }
  /** @deprecated v31.1 `getFirstDisplayedRow` is deprecated. Please use `getFirstDisplayedRowIndex` instead. */
  getFirstDisplayedRow() {
    this.logDeprecation("v31.1", "getFirstDisplayedRow", "getFirstDisplayedRowIndex");
    return this.getFirstDisplayedRowIndex();
  }
  /** Get the index of the first displayed row due to scrolling (includes invisible rendered rows in the buffer). */
  getFirstDisplayedRowIndex() {
    return this.rowRenderer.getFirstVirtualRenderedRow();
  }
  /** @deprecated v31.1 `getLastDisplayedRow` is deprecated. Please use `getLastDisplayedRowIndex` instead. */
  getLastDisplayedRow() {
    this.logDeprecation("v31.1", "getLastDisplayedRow", "getLastDisplayedRowIndex");
    return this.getLastDisplayedRowIndex();
  }
  /** Get the index of the last displayed row due to scrolling (includes invisible rendered rows in the buffer). */
  getLastDisplayedRowIndex() {
    return this.rowRenderer.getLastVirtualRenderedRow();
  }
  /** Returns the displayed `RowNode` at the given `index`. */
  getDisplayedRowAtIndex(index) {
    return this.rowModel.getRow(index);
  }
  /** Returns the total number of displayed rows. */
  getDisplayedRowCount() {
    return this.rowModel.getRowCount();
  }
  /**
   * Returns `true` when the last page is known.
   * This will always be `true` if you are using the Client-Side Row Model for pagination.
   * Returns `false` when the last page is not known; this only happens when using Infinite Row Model.
   */
  paginationIsLastPageFound() {
    return this.paginationProxy.isLastPageFound();
  }
  /** Returns how many rows are being shown per page. */
  paginationGetPageSize() {
    return this.paginationProxy.getPageSize();
  }
  /** Returns the 0-based index of the page which is showing. */
  paginationGetCurrentPage() {
    return this.paginationProxy.getCurrentPage();
  }
  /** Returns the total number of pages. Returns `null` if `paginationIsLastPageFound() === false`. */
  paginationGetTotalPages() {
    return this.paginationProxy.getTotalPages();
  }
  /** The total number of rows. Returns `null` if `paginationIsLastPageFound() === false`. */
  paginationGetRowCount() {
    return this.paginationProxy.getMasterRowCount();
  }
  /** Navigates to the next page. */
  paginationGoToNextPage() {
    this.paginationProxy.goToNextPage();
  }
  /** Navigates to the previous page. */
  paginationGoToPreviousPage() {
    this.paginationProxy.goToPreviousPage();
  }
  /** Navigates to the first page. */
  paginationGoToFirstPage() {
    this.paginationProxy.goToFirstPage();
  }
  /** Navigates to the last page. */
  paginationGoToLastPage() {
    this.paginationProxy.goToLastPage();
  }
  /** Goes to the specified page. If the page requested doesn't exist, it will go to the last page. */
  paginationGoToPage(page) {
    this.paginationProxy.goToPage(page);
  }
  // Methods migrated from old ColumnApi
  /**
   * Adjusts the size of columns to fit the available horizontal space.
   *
   * Note: it is not recommended to call this method rapidly e.g. in response
   * to window resize events or as the container size is animated. This can
   * cause the scrollbar to flicker. Use column flex for smoother results.
   * 
   * If inferring cell data types with custom column types
   * and row data is provided asynchronously, the column sizing will happen asynchronously when row data is added.
   * To always perform this synchronously, set `cellDataType = false` on the default column definition.
   **/
  sizeColumnsToFit(paramsOrGridWidth) {
    if (typeof paramsOrGridWidth === "number") {
      this.columnModel.sizeColumnsToFit(paramsOrGridWidth, "api");
    } else {
      this.gridBodyCtrl.sizeColumnsToFit(paramsOrGridWidth);
    }
  }
  /** Call this if you want to open or close a column group. */
  setColumnGroupOpened(group, newValue) {
    this.columnModel.setColumnGroupOpened(group, newValue, "api");
  }
  /** Returns the column group with the given name. */
  getColumnGroup(name, instanceId) {
    return this.columnModel.getColumnGroup(name, instanceId);
  }
  /** Returns the provided column group with the given name. */
  getProvidedColumnGroup(name) {
    return this.columnModel.getProvidedColumnGroup(name);
  }
  /** Returns the display name for a column. Useful if you are doing your own header rendering and want the grid to work out if `headerValueGetter` is used, or if you are doing your own column management GUI, to know what to show as the column name. */
  getDisplayNameForColumn(column, location) {
    return this.columnModel.getDisplayNameForColumn(column, location) || "";
  }
  /** Returns the display name for a column group (when grouping columns). */
  getDisplayNameForColumnGroup(columnGroup, location) {
    return this.columnModel.getDisplayNameForColumnGroup(columnGroup, location) || "";
  }
  /** Returns the column with the given `colKey`, which can either be the `colId` (a string) or the `colDef` (an object). */
  getColumn(key) {
    return this.columnModel.getPrimaryColumn(key);
  }
  /** Returns all the columns, regardless of visible or not. */
  getColumns() {
    return this.columnModel.getAllPrimaryColumns();
  }
  /** Applies the state of the columns from a previous state. Returns `false` if one or more columns could not be found. */
  applyColumnState(params) {
    return this.columnModel.applyColumnState(params, "api");
  }
  /** Gets the state of the columns. Typically used when saving column state. */
  getColumnState() {
    return this.columnModel.getColumnState();
  }
  /** Sets the state back to match the originally provided column definitions. */
  resetColumnState() {
    this.columnModel.resetColumnState("api");
  }
  /** Gets the state of the column groups. Typically used when saving column group state. */
  getColumnGroupState() {
    return this.columnModel.getColumnGroupState();
  }
  /** Sets the state of the column group state from a previous state. */
  setColumnGroupState(stateItems) {
    this.columnModel.setColumnGroupState(stateItems, "api");
  }
  /** Sets the state back to match the originally provided column definitions. */
  resetColumnGroupState() {
    this.columnModel.resetColumnGroupState("api");
  }
  /** Returns `true` if pinning left or right, otherwise `false`. */
  isPinning() {
    return this.columnModel.isPinningLeft() || this.columnModel.isPinningRight();
  }
  /** Returns `true` if pinning left, otherwise `false`. */
  isPinningLeft() {
    return this.columnModel.isPinningLeft();
  }
  /** Returns `true` if pinning right, otherwise `false`. */
  isPinningRight() {
    return this.columnModel.isPinningRight();
  }
  /** Returns the column to the right of the provided column, taking into consideration open / closed column groups and visible columns. This is useful if you need to know what column is beside yours e.g. if implementing your own cell navigation. */
  getDisplayedColAfter(col) {
    return this.columnModel.getDisplayedColAfter(col);
  }
  /** Same as `getVisibleColAfter` except gives column to the left. */
  getDisplayedColBefore(col) {
    return this.columnModel.getDisplayedColBefore(col);
  }
  /** @deprecated v31.1 setColumnVisible(key, visible) deprecated, please use setColumnsVisible([key], visible) instead. */
  setColumnVisible(key, visible) {
    this.logDeprecation("v31.1", "setColumnVisible(key,visible)", "setColumnsVisible([key],visible)");
    this.columnModel.setColumnsVisible([key], visible, "api");
  }
  /** Sets the visibility of columns. Key can be the column ID or `Column` object. */
  setColumnsVisible(keys2, visible) {
    this.columnModel.setColumnsVisible(keys2, visible, "api");
  }
  /** @deprecated v31.1 setColumnPinned(key, pinned) deprecated, please use setColumnsPinned([key], pinned) instead. */
  setColumnPinned(key, pinned) {
    this.logDeprecation("v31.1", "setColumnPinned(key,pinned)", "setColumnsPinned([key],pinned)");
    this.columnModel.setColumnsPinned([key], pinned, "api");
  }
  /** Set a column's pinned / unpinned state. Key can be the column ID, field, `ColDef` object or `Column` object. */
  setColumnsPinned(keys2, pinned) {
    this.columnModel.setColumnsPinned(keys2, pinned, "api");
  }
  /**
   * Returns all the grid columns, same as `getColumns()`, except
   *
   *  a) it has the order of the columns that are presented in the grid
   *
   *  b) it's after the 'pivot' step, so if pivoting, has the value columns for the pivot.
   */
  getAllGridColumns() {
    return this.columnModel.getAllGridColumns();
  }
  /** Same as `getAllDisplayedColumns` but just for the pinned left portion of the grid. */
  getDisplayedLeftColumns() {
    return this.columnModel.getDisplayedLeftColumns();
  }
  /** Same as `getAllDisplayedColumns` but just for the center portion of the grid. */
  getDisplayedCenterColumns() {
    return this.columnModel.getDisplayedCenterColumns();
  }
  /** Same as `getAllDisplayedColumns` but just for the pinned right portion of the grid. */
  getDisplayedRightColumns() {
    return this.columnModel.getDisplayedRightColumns();
  }
  /** Returns all columns currently displayed (e.g. are visible and if in a group, the group is showing the columns) for the pinned left, centre and pinned right portions of the grid. */
  getAllDisplayedColumns() {
    return this.columnModel.getAllDisplayedColumns();
  }
  /** Same as `getAllGridColumns()`, except only returns rendered columns, i.e. columns that are not within the viewport and therefore not rendered, due to column virtualisation, are not displayed. */
  getAllDisplayedVirtualColumns() {
    return this.columnModel.getViewportColumns();
  }
  /** @deprecated v31.1 moveColumn(key, toIndex) deprecated, please use moveColumns([key], toIndex) instead. */
  moveColumn(key, toIndex) {
    this.logDeprecation("v31.1", "moveColumn(key, toIndex)", "moveColumns([key], toIndex)");
    this.columnModel.moveColumns([key], toIndex, "api");
  }
  /** Moves the column at `fromIdex` to `toIndex`. The column is first removed, then added at the `toIndex` location, thus index locations will change to the right of the column after the removal. */
  moveColumnByIndex(fromIndex, toIndex) {
    this.columnModel.moveColumnByIndex(fromIndex, toIndex, "api");
  }
  /** Moves columns to `toIndex`. The columns are first removed, then added at the `toIndex` location, thus index locations will change to the right of the column after the removal. */
  moveColumns(columnsToMoveKeys, toIndex) {
    this.columnModel.moveColumns(columnsToMoveKeys, toIndex, "api");
  }
  /** Move the column to a new position in the row grouping order. */
  moveRowGroupColumn(fromIndex, toIndex) {
    this.columnModel.moveRowGroupColumn(fromIndex, toIndex, "api");
  }
  /** Sets the agg function for a column. `aggFunc` can be one of the built-in aggregations or a custom aggregation by name or direct function. */
  setColumnAggFunc(key, aggFunc) {
    this.columnModel.setColumnAggFunc(key, aggFunc, "api");
  }
  /** @deprecated v31.1 setColumnWidths(key, newWidth) deprecated, please use setColumnWidths( [{key: newWidth}] ) instead. */
  setColumnWidth(key, newWidth, finished = true, source = "api") {
    this.logDeprecation("v31.1", "setColumnWidth(col, width)", "setColumnWidths([{key: col, newWidth: width}])");
    this.columnModel.setColumnWidths([{ key, newWidth }], false, finished, source);
  }
  /** Sets the column widths of the columns provided. The finished flag gets included in the resulting event and not used internally by the grid. The finished flag is intended for dragging, where a dragging action will produce many `columnWidth` events, so the consumer of events knows when it receives the last event in a stream. The finished parameter is optional, and defaults to `true`. */
  setColumnWidths(columnWidths, finished = true, source = "api") {
    this.columnModel.setColumnWidths(columnWidths, false, finished, source);
  }
  /** Get the pivot mode. */
  isPivotMode() {
    return this.columnModel.isPivotMode();
  }
  /** Returns the pivot result column for the given `pivotKeys` and `valueColId`. Useful to then call operations on the pivot column. */
  getPivotResultColumn(pivotKeys, valueColKey) {
    return this.columnModel.getSecondaryPivotColumn(pivotKeys, valueColKey);
  }
  /** Set the value columns to the provided list of columns. */
  setValueColumns(colKeys) {
    this.columnModel.setValueColumns(colKeys, "api");
  }
  /** Get a list of the existing value columns. */
  getValueColumns() {
    return this.columnModel.getValueColumns();
  }
  /** @deprecated v31.1 removeValueColumn(colKey) deprecated, please use removeValueColumns([colKey]) instead. */
  removeValueColumn(colKey) {
    this.logDeprecation("v31.1", "removeValueColumn(colKey)", "removeValueColumns([colKey])");
    this.columnModel.removeValueColumns([colKey], "api");
  }
  /** Remove the given list of columns from the existing set of value columns. */
  removeValueColumns(colKeys) {
    this.columnModel.removeValueColumns(colKeys, "api");
  }
  /** @deprecated v31.1 addValueColumn(colKey) deprecated, please use addValueColumns([colKey]) instead. */
  addValueColumn(colKey) {
    this.logDeprecation("v31.1", "addValueColumn(colKey)", "addValueColumns([colKey])");
    this.columnModel.addValueColumns([colKey], "api");
  }
  /** Add the given list of columns to the existing set of value columns. */
  addValueColumns(colKeys) {
    this.columnModel.addValueColumns(colKeys, "api");
  }
  /** Set the row group columns. */
  setRowGroupColumns(colKeys) {
    this.columnModel.setRowGroupColumns(colKeys, "api");
  }
  /** @deprecated v31.1 removeRowGroupColumn(colKey) deprecated, please use removeRowGroupColumns([colKey]) instead. */
  removeRowGroupColumn(colKey) {
    this.logDeprecation("v31.1", "removeRowGroupColumn(colKey)", "removeRowGroupColumns([colKey])");
    this.columnModel.removeRowGroupColumns([colKey], "api");
  }
  /** Remove columns from the row groups. */
  removeRowGroupColumns(colKeys) {
    this.columnModel.removeRowGroupColumns(colKeys, "api");
  }
  /** @deprecated v31.1 addRowGroupColumn(colKey) deprecated, please use addRowGroupColumns([colKey]) instead. */
  addRowGroupColumn(colKey) {
    this.logDeprecation("v31.1", "addRowGroupColumn(colKey)", "addRowGroupColumns([colKey])");
    this.columnModel.addRowGroupColumns([colKey], "api");
  }
  /** Add columns to the row groups. */
  addRowGroupColumns(colKeys) {
    this.columnModel.addRowGroupColumns(colKeys, "api");
  }
  /** Get row group columns. */
  getRowGroupColumns() {
    return this.columnModel.getRowGroupColumns();
  }
  /** Set the pivot columns. */
  setPivotColumns(colKeys) {
    this.columnModel.setPivotColumns(colKeys, "api");
  }
  /** @deprecated v31.1 removePivotColumn(colKey) deprecated, please use removePivotColumns([colKey]) instead. */
  removePivotColumn(colKey) {
    this.logDeprecation("v31.1", "removePivotColumn(colKey)", "removePivotColumns([colKey])");
    this.columnModel.removePivotColumns([colKey], "api");
  }
  /** Remove pivot columns. */
  removePivotColumns(colKeys) {
    this.columnModel.removePivotColumns(colKeys, "api");
  }
  /** @deprecated v31.1 addPivotColumn(colKey) deprecated, please use addPivotColumns([colKey]) instead. */
  addPivotColumn(colKey) {
    this.logDeprecation("v31.1", "addPivotColumn(colKey)", "addPivotColumns([colKey])");
    this.columnModel.addPivotColumns([colKey], "api");
  }
  /** Add pivot columns. */
  addPivotColumns(colKeys) {
    this.columnModel.addPivotColumns(colKeys, "api");
  }
  /** Get the pivot columns. */
  getPivotColumns() {
    return this.columnModel.getPivotColumns();
  }
  /** Same as `getAllDisplayedColumnGroups` but just for the pinned left portion of the grid. */
  getLeftDisplayedColumnGroups() {
    return this.columnModel.getDisplayedTreeLeft();
  }
  /** Same as `getAllDisplayedColumnGroups` but just for the center portion of the grid. */
  getCenterDisplayedColumnGroups() {
    return this.columnModel.getDisplayedTreeCentre();
  }
  /** Same as `getAllDisplayedColumnGroups` but just for the pinned right portion of the grid. */
  getRightDisplayedColumnGroups() {
    return this.columnModel.getDisplayedTreeRight();
  }
  /** Returns all 'root' column headers. If you are not grouping columns, these return the columns. If you are grouping, these return the top level groups - you can navigate down through each one to get the other lower level headers and finally the columns at the bottom. */
  getAllDisplayedColumnGroups() {
    return this.columnModel.getAllDisplayedTrees();
  }
  /** @deprecated v31.1 autoSizeColumn(key) deprecated, please use autoSizeColumns([colKey]) instead. */
  autoSizeColumn(key, skipHeader) {
    this.logDeprecation("v31.1", "autoSizeColumn(key, skipHeader)", "autoSizeColumns([key], skipHeader)");
    return this.columnModel.autoSizeColumns({ columns: [key], skipHeader, source: "api" });
  }
  /**
   * Auto-sizes columns based on their contents. If inferring cell data types with custom column types
   * and row data is provided asynchronously, the column sizing will happen asynchronously when row data is added.
   * To always perform this synchronously, set `cellDataType = false` on the default column definition.
   */
  autoSizeColumns(keys2, skipHeader) {
    this.columnModel.autoSizeColumns({ columns: keys2, skipHeader, source: "api" });
  }
  /**
   * Calls `autoSizeColumns` on all displayed columns. If inferring cell data types with custom column types
   * and row data is provided asynchronously, the column sizing will happen asynchronously when row data is added.
   * To always perform this synchronously, set `cellDataType = false` on the default column definition.
   */
  autoSizeAllColumns(skipHeader) {
    this.columnModel.autoSizeAllColumns("api", skipHeader);
  }
  /** Set the pivot result columns. */
  setPivotResultColumns(colDefs) {
    this.columnModel.setSecondaryColumns(colDefs, "api");
  }
  /** Returns the grid's pivot result columns. */
  getPivotResultColumns() {
    return this.columnModel.getSecondaryColumns();
  }
  /** Get the current state of the grid. Can be used in conjunction with the `initialState` grid option to save and restore grid state. */
  getState() {
    return this.stateService.getState();
  }
  /**
   * Returns the grid option value for a provided key.
   */
  getGridOption(key) {
    return this.gos.get(key);
  }
  /**
   * Updates a single gridOption to the new value provided. (Cannot be used on `Initial` properties.)
   * If updating multiple options, it is recommended to instead use `api.updateGridOptions()` which batches update logic.
   */
  setGridOption(key, value) {
    this.updateGridOptions({ [key]: value });
  }
  /**
   * Updates the provided subset of gridOptions with the provided values. (Cannot be used on `Initial` properties.)
   */
  updateGridOptions(options) {
    this.gos.updateGridOptions({ options });
  }
  /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */
  __internalUpdateGridOptions(options, force) {
    this.gos.updateGridOptions({ options, force, source: "gridOptionsUpdated" });
  }
  deprecatedUpdateGridOption(key, value) {
    warnOnce(`set${key.charAt(0).toUpperCase()}${key.slice(1, key.length)} is deprecated. Please use 'api.setGridOption('${key}', newValue)' or 'api.updateGridOptions({ ${key}: newValue })' instead.`);
    this.setGridOption(key, value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set the top pinned rows. Call with no rows / undefined to clear top pinned rows. 
   **/
  setPivotMode(pivotMode) {
    this.deprecatedUpdateGridOption("pivotMode", pivotMode);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set the top pinned rows. Call with no rows / undefined to clear top pinned rows. 
   **/
  setPinnedTopRowData(rows) {
    this.deprecatedUpdateGridOption("pinnedTopRowData", rows);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set the bottom pinned rows. Call with no rows / undefined to clear bottom pinned rows.
   * */
  setPinnedBottomRowData(rows) {
    this.deprecatedUpdateGridOption("pinnedBottomRowData", rows);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * DOM element to use as the popup parent for grid popups (context menu, column menu etc).
   * */
  setPopupParent(ePopupParent) {
    this.deprecatedUpdateGridOption("popupParent", ePopupParent);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   */
  setSuppressModelUpdateAfterUpdateTransaction(value) {
    this.deprecatedUpdateGridOption("suppressModelUpdateAfterUpdateTransaction", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Resets the data type definitions. This will update the columns in the grid.
   * */
  setDataTypeDefinitions(dataTypeDefinitions) {
    this.deprecatedUpdateGridOption("dataTypeDefinitions", dataTypeDefinitions);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set whether the grid paginates the data or not.
   *  - `true` to enable pagination
   *  - `false` to disable pagination
   */
  setPagination(value) {
    this.deprecatedUpdateGridOption("pagination", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `paginationPageSize`, then re-paginates the grid so the changes are applied immediately.
   * */
  paginationSetPageSize(size) {
    this.deprecatedUpdateGridOption("paginationPageSize", size);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Resets the side bar to the provided configuration. The parameter is the same as the sideBar grid property. The side bar is re-created from scratch with the new config.
   * */
  setSideBar(def) {
    this.deprecatedUpdateGridOption("sideBar", def);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   */
  setSuppressClipboardPaste(value) {
    this.deprecatedUpdateGridOption("suppressClipboardPaste", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   */
  setGroupRemoveSingleChildren(value) {
    this.deprecatedUpdateGridOption("groupRemoveSingleChildren", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   */
  setGroupRemoveLowestSingleChildren(value) {
    this.deprecatedUpdateGridOption("groupRemoveLowestSingleChildren", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   */
  setGroupDisplayType(value) {
    this.deprecatedUpdateGridOption("groupDisplayType", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `groupIncludeFooter` property
   */
  setGroupIncludeFooter(value) {
    this.deprecatedUpdateGridOption("groupIncludeFooter", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `groupIncludeTotalFooter` property
   */
  setGroupIncludeTotalFooter(value) {
    this.deprecatedUpdateGridOption("groupIncludeTotalFooter", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   */
  setRowClass(className) {
    this.deprecatedUpdateGridOption("rowClass", className);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `deltaSort` property
   * */
  setDeltaSort(enable) {
    this.deprecatedUpdateGridOption("deltaSort", enable);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `suppressRowDrag` property.
   * */
  setSuppressRowDrag(value) {
    this.deprecatedUpdateGridOption("suppressRowDrag", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `suppressMoveWhenRowDragging` property.
   * */
  setSuppressMoveWhenRowDragging(value) {
    this.deprecatedUpdateGridOption("suppressMoveWhenRowDragging", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `suppressRowClickSelection` property.
   * */
  setSuppressRowClickSelection(value) {
    this.deprecatedUpdateGridOption("suppressRowClickSelection", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Enable/disable the Advanced Filter
   * */
  setEnableAdvancedFilter(enabled) {
    this.deprecatedUpdateGridOption("enableAdvancedFilter", enabled);
  }
  /** 
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Updates the `includeHiddenColumnsInAdvancedFilter` grid option.
   * By default hidden columns are excluded from the Advanced Filter.
   * Set to `true` to include them.
   */
  setIncludeHiddenColumnsInAdvancedFilter(value) {
    this.deprecatedUpdateGridOption("includeHiddenColumnsInAdvancedFilter", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * DOM element to use as the parent for the Advanced Filter, to allow it to appear outside of the grid.
   * Set to `null` to appear inside the grid.
   */
  setAdvancedFilterParent(advancedFilterParent) {
    this.deprecatedUpdateGridOption("advancedFilterParent", advancedFilterParent);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Updates the Advanced Filter Builder parameters.
   * */
  setAdvancedFilterBuilderParams(params) {
    this.deprecatedUpdateGridOption("advancedFilterBuilderParams", params);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Pass a Quick Filter text into the grid for filtering.
   * */
  setQuickFilter(newFilter) {
    warnOnce(`setQuickFilter is deprecated. Please use 'api.setGridOption('quickFilterText', newValue)' or 'api.updateGridOptions({ quickFilterText: newValue })' instead.`);
    this.gos.updateGridOptions({ options: { quickFilterText: newFilter } });
  }
  /** 
   * @deprecated As of v30, hidden columns are excluded from the Quick Filter by default. To include hidden columns, use `setIncludeHiddenColumnsInQuickFilter` instead.
   */
  setExcludeHiddenColumnsFromQuickFilter(value) {
    this.deprecatedUpdateGridOption("includeHiddenColumnsInQuickFilter", !value);
  }
  /** 
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Updates the `includeHiddenColumnsInQuickFilter` grid option.
   * By default hidden columns are excluded from the Quick Filter.
   * Set to `true` to include them.
   */
  setIncludeHiddenColumnsInQuickFilter(value) {
    this.deprecatedUpdateGridOption("includeHiddenColumnsInQuickFilter", value);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Updates the `quickFilterParser` grid option,
   * which changes how the Quick Filter splits the Quick Filter text into search terms.
   */
  setQuickFilterParser(quickFilterParser) {
    this.deprecatedUpdateGridOption("quickFilterParser", quickFilterParser);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Updates the `quickFilterMatcher` grid option,
   * which changes the matching logic for whether a row passes the Quick Filter.
   */
  setQuickFilterMatcher(quickFilterMatcher) {
    this.deprecatedUpdateGridOption("quickFilterMatcher", quickFilterMatcher);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * If `true`, the horizontal scrollbar will always be present, even if not required. Otherwise, it will only be displayed when necessary.
   * */
  setAlwaysShowHorizontalScroll(show) {
    this.deprecatedUpdateGridOption("alwaysShowHorizontalScroll", show);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * If `true`, the vertical scrollbar will always be present, even if not required. Otherwise it will only be displayed when necessary.
   * */
  setAlwaysShowVerticalScroll(show) {
    this.deprecatedUpdateGridOption("alwaysShowVerticalScroll", show);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   */
  setFunctionsReadOnly(readOnly) {
    this.deprecatedUpdateGridOption("functionsReadOnly", readOnly);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Call to set new column definitions. The grid will redraw all the column headers, and then redraw all of the rows.
   */
  setColumnDefs(colDefs, source = "api") {
    warnOnce(`setColumnDefs is deprecated. Please use 'api.setGridOption('columnDefs', newValue)' or 'api.updateGridOptions({ columnDefs: newValue })' instead.`);
    this.gos.updateGridOptions({
      options: { columnDefs: colDefs },
      source
    });
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Call to set new auto group column definition. The grid will recreate any auto-group columns if present.
   * */
  setAutoGroupColumnDef(colDef, source = "api") {
    warnOnce(`setAutoGroupColumnDef is deprecated. Please use 'api.setGridOption('autoGroupColumnDef', newValue)' or 'api.updateGridOptions({ autoGroupColumnDef: newValue })' instead.`);
    this.gos.updateGridOptions({
      options: { autoGroupColumnDef: colDef },
      source
    });
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Call to set new Default Column Definition.
   * */
  setDefaultColDef(colDef, source = "api") {
    warnOnce(`setDefaultColDef is deprecated. Please use 'api.setGridOption('defaultColDef', newValue)' or 'api.updateGridOptions({ defaultColDef: newValue })' instead.`);
    this.gos.updateGridOptions({
      options: { defaultColDef: colDef },
      source
    });
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Call to set new Column Types.
   * */
  setColumnTypes(columnTypes, source = "api") {
    warnOnce(`setColumnTypes is deprecated. Please use 'api.setGridOption('columnTypes', newValue)' or 'api.updateGridOptions({ columnTypes: newValue })' instead.`);
    this.gos.updateGridOptions({
      options: { columnTypes },
      source
    });
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `treeData` property.
   * */
  setTreeData(newTreeData) {
    this.deprecatedUpdateGridOption("treeData", newTreeData);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set new datasource for Server-Side Row Model.
   * */
  setServerSideDatasource(datasource) {
    this.deprecatedUpdateGridOption("serverSideDatasource", datasource);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * 
   * Note this purges all the cached data and reloads all the rows of the grid.
   * */
  setCacheBlockSize(blockSize) {
    this.deprecatedUpdateGridOption("cacheBlockSize", blockSize);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set new datasource for Infinite Row Model.
   * */
  setDatasource(datasource) {
    this.deprecatedUpdateGridOption("datasource", datasource);
  }
  /** 
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set new datasource for Viewport Row Model.
   * */
  setViewportDatasource(viewportDatasource) {
    this.deprecatedUpdateGridOption("viewportDatasource", viewportDatasource);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Set the row data.
   * */
  setRowData(rowData) {
    this.deprecatedUpdateGridOption("rowData", rowData);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the `enableCellTextSelection` property.
   * */
  setEnableCellTextSelection(selectable) {
    this.deprecatedUpdateGridOption("enableCellTextSelection", selectable);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the height in pixels for the row containing the column label header.
   * */
  setHeaderHeight(headerHeight) {
    this.deprecatedUpdateGridOption("headerHeight", headerHeight);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Switch between layout options: `normal`, `autoHeight`, `print`.
   * Defaults to `normal` if no domLayout provided.
   */
  setDomLayout(domLayout) {
    this.deprecatedUpdateGridOption("domLayout", domLayout);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the preferred direction for the selection fill handle.
   * */
  setFillHandleDirection(direction) {
    this.deprecatedUpdateGridOption("fillHandleDirection", direction);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the height in pixels for the rows containing header column groups.
   * */
  setGroupHeaderHeight(headerHeight) {
    this.deprecatedUpdateGridOption("groupHeaderHeight", headerHeight);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the height in pixels for the row containing the floating filters.
   * */
  setFloatingFiltersHeight(headerHeight) {
    this.deprecatedUpdateGridOption("floatingFiltersHeight", headerHeight);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the height in pixels for the row containing the columns when in pivot mode.
   * */
  setPivotHeaderHeight(headerHeight) {
    this.deprecatedUpdateGridOption("pivotHeaderHeight", headerHeight);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   * Sets the height in pixels for the row containing header column groups when in pivot mode.
   * */
  setPivotGroupHeaderHeight(headerHeight) {
    this.deprecatedUpdateGridOption("pivotGroupHeaderHeight", headerHeight);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setAnimateRows(animateRows) {
    this.deprecatedUpdateGridOption("animateRows", animateRows);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setIsExternalFilterPresent(isExternalFilterPresentFunc) {
    this.deprecatedUpdateGridOption("isExternalFilterPresent", isExternalFilterPresentFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setDoesExternalFilterPass(doesExternalFilterPassFunc) {
    this.deprecatedUpdateGridOption("doesExternalFilterPass", doesExternalFilterPassFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setNavigateToNextCell(navigateToNextCellFunc) {
    this.deprecatedUpdateGridOption("navigateToNextCell", navigateToNextCellFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setTabToNextCell(tabToNextCellFunc) {
    this.deprecatedUpdateGridOption("tabToNextCell", tabToNextCellFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setTabToNextHeader(tabToNextHeaderFunc) {
    this.deprecatedUpdateGridOption("tabToNextHeader", tabToNextHeaderFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setNavigateToNextHeader(navigateToNextHeaderFunc) {
    this.deprecatedUpdateGridOption("navigateToNextHeader", navigateToNextHeaderFunc);
  }
  setRowGroupPanelShow(rowGroupPanelShow) {
    this.deprecatedUpdateGridOption("rowGroupPanelShow", rowGroupPanelShow);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetGroupRowAgg(getGroupRowAggFunc) {
    this.deprecatedUpdateGridOption("getGroupRowAgg", getGroupRowAggFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetBusinessKeyForNode(getBusinessKeyForNodeFunc) {
    this.deprecatedUpdateGridOption("getBusinessKeyForNode", getBusinessKeyForNodeFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetChildCount(getChildCountFunc) {
    this.deprecatedUpdateGridOption("getChildCount", getChildCountFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setProcessRowPostCreate(processRowPostCreateFunc) {
    this.deprecatedUpdateGridOption("processRowPostCreate", processRowPostCreateFunc);
  }
  /**
   * @deprecated v31 `getRowId` is a static property and cannot be updated.
   *  */
  setGetRowId(getRowIdFunc) {
    warnOnce(`getRowId is a static property and can no longer be updated.`);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetRowClass(rowClassFunc) {
    this.deprecatedUpdateGridOption("getRowClass", rowClassFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setIsFullWidthRow(isFullWidthRowFunc) {
    this.deprecatedUpdateGridOption("isFullWidthRow", isFullWidthRowFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setIsRowSelectable(isRowSelectableFunc) {
    this.deprecatedUpdateGridOption("isRowSelectable", isRowSelectableFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setIsRowMaster(isRowMasterFunc) {
    this.deprecatedUpdateGridOption("isRowMaster", isRowMasterFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setPostSortRows(postSortRowsFunc) {
    this.deprecatedUpdateGridOption("postSortRows", postSortRowsFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetDocument(getDocumentFunc) {
    this.deprecatedUpdateGridOption("getDocument", getDocumentFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetContextMenuItems(getContextMenuItemsFunc) {
    this.deprecatedUpdateGridOption("getContextMenuItems", getContextMenuItemsFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetMainMenuItems(getMainMenuItemsFunc) {
    this.deprecatedUpdateGridOption("getMainMenuItems", getMainMenuItemsFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setProcessCellForClipboard(processCellForClipboardFunc) {
    this.deprecatedUpdateGridOption("processCellForClipboard", processCellForClipboardFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setSendToClipboard(sendToClipboardFunc) {
    this.deprecatedUpdateGridOption("sendToClipboard", sendToClipboardFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setProcessCellFromClipboard(processCellFromClipboardFunc) {
    this.deprecatedUpdateGridOption("processCellFromClipboard", processCellFromClipboardFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setProcessPivotResultColDef(processPivotResultColDefFunc) {
    this.deprecatedUpdateGridOption("processPivotResultColDef", processPivotResultColDefFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setProcessPivotResultColGroupDef(processPivotResultColGroupDefFunc) {
    this.deprecatedUpdateGridOption("processPivotResultColGroupDef", processPivotResultColGroupDefFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setPostProcessPopup(postProcessPopupFunc) {
    this.deprecatedUpdateGridOption("postProcessPopup", postProcessPopupFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setInitialGroupOrderComparator(initialGroupOrderComparatorFunc) {
    this.deprecatedUpdateGridOption("initialGroupOrderComparator", initialGroupOrderComparatorFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetChartToolbarItems(getChartToolbarItemsFunc) {
    this.deprecatedUpdateGridOption("getChartToolbarItems", getChartToolbarItemsFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setPaginationNumberFormatter(paginationNumberFormatterFunc) {
    this.deprecatedUpdateGridOption("paginationNumberFormatter", paginationNumberFormatterFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetServerSideGroupLevelParams(getServerSideGroupLevelParamsFunc) {
    this.deprecatedUpdateGridOption("getServerSideGroupLevelParams", getServerSideGroupLevelParamsFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setIsServerSideGroupOpenByDefault(isServerSideGroupOpenByDefaultFunc) {
    this.deprecatedUpdateGridOption("isServerSideGroupOpenByDefault", isServerSideGroupOpenByDefaultFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setIsApplyServerSideTransaction(isApplyServerSideTransactionFunc) {
    this.deprecatedUpdateGridOption("isApplyServerSideTransaction", isApplyServerSideTransactionFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setIsServerSideGroup(isServerSideGroupFunc) {
    this.deprecatedUpdateGridOption("isServerSideGroup", isServerSideGroupFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetServerSideGroupKey(getServerSideGroupKeyFunc) {
    this.deprecatedUpdateGridOption("getServerSideGroupKey", getServerSideGroupKeyFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetRowStyle(rowStyleFunc) {
    this.deprecatedUpdateGridOption("getRowStyle", rowStyleFunc);
  }
  /**
   * @deprecated v31 Use `api.setGridOption` or `api.updateGridOptions` instead.
   *  */
  setGetRowHeight(rowHeightFunc) {
    this.deprecatedUpdateGridOption("getRowHeight", rowHeightFunc);
  }
};
__decorateClass([
  Autowired("rowRenderer")
], GridApi.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("navigationService")
], GridApi.prototype, "navigationService", 2);
__decorateClass([
  Autowired("filterManager")
], GridApi.prototype, "filterManager", 2);
__decorateClass([
  Autowired("columnModel")
], GridApi.prototype, "columnModel", 2);
__decorateClass([
  Autowired("selectionService")
], GridApi.prototype, "selectionService", 2);
__decorateClass([
  Autowired("gridOptionsService")
], GridApi.prototype, "gos", 2);
__decorateClass([
  Autowired("valueService")
], GridApi.prototype, "valueService", 2);
__decorateClass([
  Autowired("alignedGridsService")
], GridApi.prototype, "alignedGridsService", 2);
__decorateClass([
  Autowired("eventService")
], GridApi.prototype, "eventService", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], GridApi.prototype, "pinnedRowModel", 2);
__decorateClass([
  Autowired("context")
], GridApi.prototype, "context", 2);
__decorateClass([
  Autowired("rowModel")
], GridApi.prototype, "rowModel", 2);
__decorateClass([
  Autowired("sortController")
], GridApi.prototype, "sortController", 2);
__decorateClass([
  Autowired("paginationProxy")
], GridApi.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("focusService")
], GridApi.prototype, "focusService", 2);
__decorateClass([
  Autowired("dragAndDropService")
], GridApi.prototype, "dragAndDropService", 2);
__decorateClass([
  Autowired("menuService")
], GridApi.prototype, "menuService", 2);
__decorateClass([
  Autowired("valueCache")
], GridApi.prototype, "valueCache", 2);
__decorateClass([
  Autowired("animationFrameService")
], GridApi.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("ctrlsService")
], GridApi.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("overlayService")
], GridApi.prototype, "overlayService", 2);
__decorateClass([
  Autowired("stateService")
], GridApi.prototype, "stateService", 2);
__decorateClass([
  Autowired("expansionService")
], GridApi.prototype, "expansionService", 2);
__decorateClass([
  Autowired("apiEventService")
], GridApi.prototype, "apiEventService", 2);
__decorateClass([
  Autowired("frameworkOverrides")
], GridApi.prototype, "frameworkOverrides", 2);
__decorateClass([
  Autowired("undoRedoService")
], GridApi.prototype, "undoRedoService", 2);
__decorateClass([
  Autowired("rowNodeBlockLoader")
], GridApi.prototype, "rowNodeBlockLoader", 2);
__decorateClass([
  Optional("csvCreator")
], GridApi.prototype, "csvCreator", 2);
__decorateClass([
  Optional("excelCreator")
], GridApi.prototype, "excelCreator", 2);
__decorateClass([
  Optional("rangeService")
], GridApi.prototype, "rangeService", 2);
__decorateClass([
  Optional("clipboardService")
], GridApi.prototype, "clipboardService", 2);
__decorateClass([
  Optional("aggFuncService")
], GridApi.prototype, "aggFuncService", 2);
__decorateClass([
  Optional("statusBarService")
], GridApi.prototype, "statusBarService", 2);
__decorateClass([
  Optional("chartService")
], GridApi.prototype, "chartService", 2);
__decorateClass([
  Optional("ssrmTransactionManager")
], GridApi.prototype, "serverSideTransactionManager", 2);
__decorateClass([
  Optional("sideBarService")
], GridApi.prototype, "sideBarService", 2);
__decorateClass([
  PostConstruct
], GridApi.prototype, "init", 1);
GridApi = __decorateClass([
  Bean("gridApi")
], GridApi);

// community-modules/core/src/filter/quickFilterService.ts
var QuickFilterService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.quickFilter = null;
    this.quickFilterParts = null;
  }
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, () => this.resetQuickFilterCache());
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, () => this.resetQuickFilterCache());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, () => this.resetQuickFilterCache());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VISIBLE, () => {
      if (!this.gos.get("includeHiddenColumnsInQuickFilter")) {
        this.resetQuickFilterCache();
      }
    });
    this.addManagedPropertyListener("quickFilterText", (e) => this.setQuickFilter(e.currentValue));
    this.addManagedPropertyListeners([
      "includeHiddenColumnsInQuickFilter",
      "applyQuickFilterBeforePivotOrAgg"
    ], () => this.onQuickFilterColumnConfigChanged());
    this.quickFilter = this.parseQuickFilter(this.gos.get("quickFilterText"));
    this.parser = this.gos.get("quickFilterParser");
    this.matcher = this.gos.get("quickFilterMatcher");
    this.setQuickFilterParts();
    this.addManagedPropertyListeners(["quickFilterMatcher", "quickFilterParser"], () => this.setQuickFilterParserAndMatcher());
  }
  isQuickFilterPresent() {
    return this.quickFilter !== null;
  }
  doesRowPassQuickFilter(node) {
    const usingCache = this.gos.get("cacheQuickFilter");
    if (this.matcher) {
      return this.doesRowPassQuickFilterMatcher(usingCache, node);
    }
    return this.quickFilterParts.every(
      (part) => usingCache ? this.doesRowPassQuickFilterCache(node, part) : this.doesRowPassQuickFilterNoCache(node, part)
    );
  }
  resetQuickFilterCache() {
    this.rowModel.forEachNode((node) => node.quickFilterAggregateText = null);
  }
  setQuickFilterParts() {
    const { quickFilter, parser } = this;
    if (quickFilter) {
      this.quickFilterParts = parser ? parser(quickFilter) : quickFilter.split(" ");
    } else {
      this.quickFilterParts = null;
    }
  }
  parseQuickFilter(newFilter) {
    if (!exists(newFilter)) {
      return null;
    }
    if (!this.gos.isRowModelType("clientSide")) {
      console.warn("AG Grid - Quick filtering only works with the Client-Side Row Model");
      return null;
    }
    return newFilter.toUpperCase();
  }
  setQuickFilter(newFilter) {
    if (newFilter != null && typeof newFilter !== "string") {
      console.warn(`AG Grid - Grid option quickFilterText only supports string inputs, received: ${typeof newFilter}`);
      return;
    }
    const parsedFilter = this.parseQuickFilter(newFilter);
    if (this.quickFilter !== parsedFilter) {
      this.quickFilter = parsedFilter;
      this.setQuickFilterParts();
      this.dispatchEvent({ type: QuickFilterService.EVENT_QUICK_FILTER_CHANGED });
    }
  }
  setQuickFilterParserAndMatcher() {
    const parser = this.gos.get("quickFilterParser");
    const matcher = this.gos.get("quickFilterMatcher");
    const hasChanged = parser !== this.parser || matcher !== this.matcher;
    this.parser = parser;
    this.matcher = matcher;
    if (hasChanged) {
      this.setQuickFilterParts();
      this.dispatchEvent({ type: QuickFilterService.EVENT_QUICK_FILTER_CHANGED });
    }
  }
  onQuickFilterColumnConfigChanged() {
    this.columnModel.refreshQuickFilterColumns();
    this.resetQuickFilterCache();
    if (this.isQuickFilterPresent()) {
      this.dispatchEvent({ type: QuickFilterService.EVENT_QUICK_FILTER_CHANGED });
    }
  }
  doesRowPassQuickFilterNoCache(node, filterPart) {
    const columns = this.columnModel.getAllColumnsForQuickFilter();
    return columns.some((column) => {
      const part = this.getQuickFilterTextForColumn(column, node);
      return exists(part) && part.indexOf(filterPart) >= 0;
    });
  }
  doesRowPassQuickFilterCache(node, filterPart) {
    this.checkGenerateQuickFilterAggregateText(node);
    return node.quickFilterAggregateText.indexOf(filterPart) >= 0;
  }
  doesRowPassQuickFilterMatcher(usingCache, node) {
    let quickFilterAggregateText;
    if (usingCache) {
      this.checkGenerateQuickFilterAggregateText(node);
      quickFilterAggregateText = node.quickFilterAggregateText;
    } else {
      quickFilterAggregateText = this.getQuickFilterAggregateText(node);
    }
    const { quickFilterParts, matcher } = this;
    return matcher(quickFilterParts, quickFilterAggregateText);
  }
  checkGenerateQuickFilterAggregateText(node) {
    if (!node.quickFilterAggregateText) {
      node.quickFilterAggregateText = this.getQuickFilterAggregateText(node);
    }
  }
  getQuickFilterTextForColumn(column, node) {
    let value = this.valueService.getValue(column, node, true);
    const colDef = column.getColDef();
    if (colDef.getQuickFilterText) {
      const params = this.gos.addGridCommonParams({
        value,
        node,
        data: node.data,
        column,
        colDef
      });
      value = colDef.getQuickFilterText(params);
    }
    return exists(value) ? value.toString().toUpperCase() : null;
  }
  getQuickFilterAggregateText(node) {
    const stringParts = [];
    const columns = this.columnModel.getAllColumnsForQuickFilter();
    columns.forEach((column) => {
      const part = this.getQuickFilterTextForColumn(column, node);
      if (exists(part)) {
        stringParts.push(part);
      }
    });
    return stringParts.join(QuickFilterService.QUICK_FILTER_SEPARATOR);
  }
};
QuickFilterService.EVENT_QUICK_FILTER_CHANGED = "quickFilterChanged";
QuickFilterService.QUICK_FILTER_SEPARATOR = "\n";
__decorateClass([
  Autowired("valueService")
], QuickFilterService.prototype, "valueService", 2);
__decorateClass([
  Autowired("columnModel")
], QuickFilterService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("rowModel")
], QuickFilterService.prototype, "rowModel", 2);
__decorateClass([
  PostConstruct
], QuickFilterService.prototype, "postConstruct", 1);
QuickFilterService = __decorateClass([
  Bean("quickFilterService")
], QuickFilterService);

// community-modules/core/src/filter/filterManager.ts
var FilterManager = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.allColumnFilters = /* @__PURE__ */ new Map();
    this.allColumnListeners = /* @__PURE__ */ new Map();
    this.activeAggregateFilters = [];
    this.activeColumnFilters = [];
    // this is true when the grid is processing the filter change. this is used by the cell comps, so that they
    // don't flash when data changes due to filter changes. there is no need to flash when filter changes as the
    // user is in control, so doesn't make sense to show flashing changes. for example, go to main demo where
    // this feature is turned off (hack code to always return false for isSuppressFlashingCellsBecauseFiltering(), put in)
    // 100,000 rows and group by country. then do some filtering. all the cells flash, which is silly.
    this.processingFilterChange = false;
    // when we're waiting for cell data types to be inferred, we need to defer filter model updates
    this.filterModelUpdateQueue = [];
    this.columnFilterModelUpdateQueue = [];
    this.advancedFilterModelUpdateQueue = [];
  }
  init() {
    var _a, _b, _c;
    this.addManagedListener(this.eventService, Events.EVENT_GRID_COLUMNS_CHANGED, () => this.onColumnsChanged());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VALUE_CHANGED, () => this.refreshFiltersForAggregations());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_CHANGED, () => this.refreshFiltersForAggregations());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, () => this.refreshFiltersForAggregations());
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, () => this.updateAdvancedFilterColumns());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VISIBLE, () => this.updateAdvancedFilterColumns());
    this.addManagedListener(this.eventService, Events.EVENT_ROW_DATA_UPDATED, () => this.onNewRowsLoaded("rowDataUpdated"));
    this.externalFilterPresent = this.isExternalFilterPresentCallback();
    this.addManagedPropertyListeners(["isExternalFilterPresent", "doesExternalFilterPass"], () => {
      this.onFilterChanged({ source: "api" });
    });
    this.updateAggFiltering();
    this.addManagedPropertyListener("groupAggFiltering", () => {
      this.updateAggFiltering();
      this.onFilterChanged();
    });
    this.addManagedPropertyListener("advancedFilterModel", (event) => this.setAdvancedFilterModel(event.currentValue));
    this.addManagedListener(
      this.eventService,
      Events.EVENT_ADVANCED_FILTER_ENABLED_CHANGED,
      ({ enabled }) => this.onAdvancedFilterEnabledChanged(enabled)
    );
    this.addManagedListener(this.eventService, Events.EVENT_DATA_TYPES_INFERRED, () => this.processFilterModelUpdateQueue());
    this.addManagedListener(this.quickFilterService, QuickFilterService.EVENT_QUICK_FILTER_CHANGED, () => this.onFilterChanged({ source: "quickFilter" }));
    this.initialFilterModel = __spreadValues({}, (_c = (_b = (_a = this.gos.get("initialState")) == null ? void 0 : _a.filter) == null ? void 0 : _b.filterModel) != null ? _c : {});
  }
  isExternalFilterPresentCallback() {
    const isFilterPresent = this.gos.getCallback("isExternalFilterPresent");
    if (typeof isFilterPresent === "function") {
      return isFilterPresent({});
    }
    return false;
  }
  doesExternalFilterPass(node) {
    const doesFilterPass = this.gos.get("doesExternalFilterPass");
    if (typeof doesFilterPass === "function") {
      return doesFilterPass(node);
    }
    return false;
  }
  setFilterModel(model, source = "api") {
    if (this.isAdvancedFilterEnabled()) {
      this.warnAdvancedFilters();
      return;
    }
    if (this.dataTypeService.isPendingInference()) {
      this.filterModelUpdateQueue.push({ model, source });
      return;
    }
    const allPromises = [];
    const previousModel = this.getFilterModel();
    if (model) {
      const modelKeys = convertToSet(Object.keys(model));
      this.allColumnFilters.forEach((filterWrapper, colId) => {
        const newModel = model[colId];
        allPromises.push(this.setModelOnFilterWrapper(filterWrapper.filterPromise, newModel));
        modelKeys.delete(colId);
      });
      modelKeys.forEach((colId) => {
        const column = this.columnModel.getPrimaryColumn(colId) || this.columnModel.getGridColumn(colId);
        if (!column) {
          console.warn("AG Grid: setFilterModel() - no column found for colId: " + colId);
          return;
        }
        if (!column.isFilterAllowed()) {
          console.warn("AG Grid: setFilterModel() - unable to fully apply model, filtering disabled for colId: " + colId);
          return;
        }
        const filterWrapper = this.getOrCreateFilterWrapper(column, "NO_UI");
        if (!filterWrapper) {
          console.warn("AG-Grid: setFilterModel() - unable to fully apply model, unable to create filter for colId: " + colId);
          return;
        }
        allPromises.push(this.setModelOnFilterWrapper(filterWrapper.filterPromise, model[colId]));
      });
    } else {
      this.allColumnFilters.forEach((filterWrapper) => {
        allPromises.push(this.setModelOnFilterWrapper(filterWrapper.filterPromise, null));
      });
    }
    AgPromise.all(allPromises).then(() => {
      const currentModel = this.getFilterModel();
      const columns = [];
      this.allColumnFilters.forEach((filterWrapper, colId) => {
        const before = previousModel ? previousModel[colId] : null;
        const after = currentModel ? currentModel[colId] : null;
        if (!_.jsonEquals(before, after)) {
          columns.push(filterWrapper.column);
        }
      });
      if (columns.length > 0) {
        this.onFilterChanged({ columns, source });
      }
    });
  }
  setModelOnFilterWrapper(filterPromise, newModel) {
    return new AgPromise((resolve) => {
      filterPromise.then((filter) => {
        if (typeof filter.setModel !== "function") {
          console.warn("AG Grid: filter missing setModel method, which is needed for setFilterModel");
          resolve();
        }
        (filter.setModel(newModel) || AgPromise.resolve()).then(() => resolve());
      });
    });
  }
  getFilterModel() {
    const result = {};
    this.allColumnFilters.forEach((filterWrapper, key) => {
      const model = this.getModelFromFilterWrapper(filterWrapper);
      if (exists(model)) {
        result[key] = model;
      }
    });
    return result;
  }
  getModelFromFilterWrapper(filterWrapper) {
    var _a;
    const filterPromise = filterWrapper.filterPromise;
    const filter = filterPromise.resolveNow(null, (promiseFilter) => promiseFilter);
    if (filter == null) {
      return (_a = this.initialFilterModel[filterWrapper.column.getColId()]) != null ? _a : null;
    }
    if (typeof filter.getModel !== "function") {
      console.warn("AG Grid: filter API missing getModel method, which is needed for getFilterModel");
      return null;
    }
    return filter.getModel();
  }
  isColumnFilterPresent() {
    return this.activeColumnFilters.length > 0;
  }
  isAggregateFilterPresent() {
    return !!this.activeAggregateFilters.length;
  }
  isExternalFilterPresent() {
    return this.externalFilterPresent;
  }
  isChildFilterPresent() {
    return this.isColumnFilterPresent() || this.isQuickFilterPresent() || this.isExternalFilterPresent() || this.isAdvancedFilterPresent();
  }
  isAdvancedFilterPresent() {
    return this.isAdvancedFilterEnabled() && this.advancedFilterService.isFilterPresent();
  }
  onAdvancedFilterEnabledChanged(enabled) {
    var _a;
    if (enabled) {
      if (this.allColumnFilters.size) {
        this.allColumnFilters.forEach((filterWrapper) => this.disposeFilterWrapper(filterWrapper, "advancedFilterEnabled"));
        this.onFilterChanged({ source: "advancedFilter" });
      }
    } else {
      if ((_a = this.advancedFilterService) == null ? void 0 : _a.isFilterPresent()) {
        this.advancedFilterService.setModel(null);
        this.onFilterChanged({ source: "advancedFilter" });
      }
    }
  }
  isAdvancedFilterEnabled() {
    var _a;
    return !!((_a = this.advancedFilterService) == null ? void 0 : _a.isEnabled());
  }
  isAdvancedFilterHeaderActive() {
    return this.isAdvancedFilterEnabled() && this.advancedFilterService.isHeaderActive();
  }
  doAggregateFiltersPass(node, filterToSkip) {
    return this.doColumnFiltersPass(node, filterToSkip, true);
  }
  // called by:
  // 1) onFilterChanged()
  // 2) onNewRowsLoaded()
  updateActiveFilters() {
    this.activeColumnFilters.length = 0;
    this.activeAggregateFilters.length = 0;
    const isFilterActive = (filter) => {
      if (!filter) {
        return false;
      }
      if (!filter.isFilterActive) {
        console.warn("AG Grid: Filter is missing isFilterActive() method");
        return false;
      }
      return filter.isFilterActive();
    };
    const groupFilterEnabled = !!this.gos.getGroupAggFiltering();
    const isAggFilter = (column) => {
      const isSecondary = !column.isPrimary();
      if (isSecondary) {
        return true;
      }
      const isShowingPrimaryColumns = !this.columnModel.isPivotActive();
      const isValueActive = column.isValueActive();
      if (!isValueActive || !isShowingPrimaryColumns) {
        return false;
      }
      if (this.columnModel.isPivotMode()) {
        return true;
      }
      return groupFilterEnabled;
    };
    this.allColumnFilters.forEach((filterWrapper) => {
      if (filterWrapper.filterPromise.resolveNow(false, isFilterActive)) {
        const filterComp = filterWrapper.filterPromise.resolveNow(null, (filter) => filter);
        if (isAggFilter(filterWrapper.column)) {
          this.activeAggregateFilters.push(filterComp);
        } else {
          this.activeColumnFilters.push(filterComp);
        }
      }
    });
  }
  updateFilterFlagInColumns(source, additionalEventAttributes) {
    this.allColumnFilters.forEach((filterWrapper) => {
      const isFilterActive = filterWrapper.filterPromise.resolveNow(false, (filter) => filter.isFilterActive());
      filterWrapper.column.setFilterActive(isFilterActive, source, additionalEventAttributes);
    });
  }
  isAnyFilterPresent() {
    return this.isQuickFilterPresent() || this.isColumnFilterPresent() || this.isAggregateFilterPresent() || this.isExternalFilterPresent() || this.isAdvancedFilterPresent();
  }
  doColumnFiltersPass(node, filterToSkip, targetAggregates) {
    const { data, aggData } = node;
    const targetedFilters = targetAggregates ? this.activeAggregateFilters : this.activeColumnFilters;
    const targetedData = targetAggregates ? aggData : data;
    for (let i = 0; i < targetedFilters.length; i++) {
      const filter = targetedFilters[i];
      if (filter == null || filter === filterToSkip) {
        continue;
      }
      if (typeof filter.doesFilterPass !== "function") {
        throw new Error("Filter is missing method doesFilterPass");
      }
      if (!filter.doesFilterPass({ node, data: targetedData })) {
        return false;
      }
    }
    return true;
  }
  resetQuickFilterCache() {
    this.quickFilterService.resetQuickFilterCache();
  }
  refreshFiltersForAggregations() {
    const isAggFiltering = this.gos.getGroupAggFiltering();
    if (isAggFiltering) {
      this.onFilterChanged();
    }
  }
  // sometimes (especially in React) the filter can call onFilterChanged when we are in the middle
  // of a render cycle. this would be bad, so we wait for render cycle to complete when this happens.
  // this happens in react when we change React State in the grid (eg setting RowCtrl's in RowContainer)
  // which results in React State getting applied in the main application, triggering a useEffect() to
  // be kicked off adn then the application calling the grid's API. in AG-6554, the custom filter was
  // getting it's useEffect() triggered in this way.
  callOnFilterChangedOutsideRenderCycle(params) {
    const action = () => this.onFilterChanged(params);
    if (this.rowRenderer.isRefreshInProgress()) {
      setTimeout(action, 0);
    } else {
      action();
    }
  }
  onFilterChanged(params = {}) {
    const { source, filterInstance, additionalEventAttributes, columns } = params;
    this.updateDependantFilters();
    this.updateActiveFilters();
    this.updateFilterFlagInColumns("filterChanged", additionalEventAttributes);
    this.externalFilterPresent = this.isExternalFilterPresentCallback();
    this.allColumnFilters.forEach((filterWrapper) => {
      if (!filterWrapper.filterPromise) {
        return;
      }
      filterWrapper.filterPromise.then((filter) => {
        if (filter && filter !== filterInstance && filter.onAnyFilterChanged) {
          filter.onAnyFilterChanged();
        }
      });
    });
    const filterChangedEvent = {
      source,
      type: Events.EVENT_FILTER_CHANGED,
      columns: columns || []
    };
    if (additionalEventAttributes) {
      mergeDeep(filterChangedEvent, additionalEventAttributes);
    }
    this.processingFilterChange = true;
    this.eventService.dispatchEvent(filterChangedEvent);
    this.processingFilterChange = false;
  }
  isSuppressFlashingCellsBecauseFiltering() {
    var _a;
    const allowShowChangeAfterFilter = (_a = this.gos.get("allowShowChangeAfterFilter")) != null ? _a : false;
    return !allowShowChangeAfterFilter && this.processingFilterChange;
  }
  isQuickFilterPresent() {
    return this.quickFilterService.isQuickFilterPresent();
  }
  updateAggFiltering() {
    this.aggFiltering = !!this.gos.getGroupAggFiltering();
  }
  isAggregateQuickFilterPresent() {
    return this.isQuickFilterPresent() && this.shouldApplyQuickFilterAfterAgg();
  }
  isNonAggregateQuickFilterPresent() {
    return this.isQuickFilterPresent() && !this.shouldApplyQuickFilterAfterAgg();
  }
  shouldApplyQuickFilterAfterAgg() {
    return (this.aggFiltering || this.columnModel.isPivotMode()) && !this.gos.get("applyQuickFilterBeforePivotOrAgg");
  }
  doesRowPassOtherFilters(filterToSkip, node) {
    return this.doesRowPassFilter({ rowNode: node, filterInstanceToSkip: filterToSkip });
  }
  doesRowPassAggregateFilters(params) {
    if (this.isAggregateQuickFilterPresent() && !this.quickFilterService.doesRowPassQuickFilter(params.rowNode)) {
      return false;
    }
    if (this.isAggregateFilterPresent() && !this.doAggregateFiltersPass(params.rowNode, params.filterInstanceToSkip)) {
      return false;
    }
    return true;
  }
  doesRowPassFilter(params) {
    if (this.isNonAggregateQuickFilterPresent() && !this.quickFilterService.doesRowPassQuickFilter(params.rowNode)) {
      return false;
    }
    if (this.isExternalFilterPresent() && !this.doesExternalFilterPass(params.rowNode)) {
      return false;
    }
    if (this.isColumnFilterPresent() && !this.doColumnFiltersPass(params.rowNode, params.filterInstanceToSkip)) {
      return false;
    }
    if (this.isAdvancedFilterPresent() && !this.advancedFilterService.doesFilterPass(params.rowNode)) {
      return false;
    }
    return true;
  }
  onNewRowsLoaded(source) {
    this.allColumnFilters.forEach((filterWrapper) => {
      filterWrapper.filterPromise.then((filter) => {
        if (filter.onNewRowsLoaded) {
          filter.onNewRowsLoaded();
        }
      });
    });
    this.updateFilterFlagInColumns(source, { afterDataChange: true });
    this.updateActiveFilters();
  }
  createValueGetter(column) {
    return ({ node }) => this.valueService.getValue(column, node, true);
  }
  createGetValue(filterColumn) {
    return (rowNode, column) => {
      const columnToUse = column ? this.columnModel.getGridColumn(column) : filterColumn;
      return columnToUse ? this.valueService.getValue(columnToUse, rowNode, true) : void 0;
    };
  }
  getFilterComponent(column, source, createIfDoesNotExist = true) {
    var _a;
    if (createIfDoesNotExist) {
      return ((_a = this.getOrCreateFilterWrapper(column, source)) == null ? void 0 : _a.filterPromise) || null;
    }
    const filterWrapper = this.cachedFilter(column);
    return filterWrapper ? filterWrapper.filterPromise : null;
  }
  isFilterActive(column) {
    const filterWrapper = this.cachedFilter(column);
    return !!filterWrapper && filterWrapper.filterPromise.resolveNow(false, (filter) => filter.isFilterActive());
  }
  getOrCreateFilterWrapper(column, source) {
    if (!column.isFilterAllowed()) {
      return null;
    }
    let filterWrapper = this.cachedFilter(column);
    if (!filterWrapper) {
      filterWrapper = this.createFilterWrapper(column, source);
      this.setColumnFilterWrapper(column, filterWrapper);
    }
    return filterWrapper;
  }
  cachedFilter(column) {
    return this.allColumnFilters.get(column.getColId());
  }
  getDefaultFilter(column) {
    let defaultFilter;
    if (ModuleRegistry.__isRegistered("@ag-grid-enterprise/set-filter" /* SetFilterModule */, this.context.getGridId())) {
      defaultFilter = "agSetColumnFilter";
    } else {
      const cellDataType = this.dataTypeService.getBaseDataType(column);
      if (cellDataType === "number") {
        defaultFilter = "agNumberColumnFilter";
      } else if (cellDataType === "date" || cellDataType === "dateString") {
        defaultFilter = "agDateColumnFilter";
      } else {
        defaultFilter = "agTextColumnFilter";
      }
    }
    return defaultFilter;
  }
  getDefaultFloatingFilter(column) {
    let defaultFloatingFilterType;
    if (ModuleRegistry.__isRegistered("@ag-grid-enterprise/set-filter" /* SetFilterModule */, this.context.getGridId())) {
      defaultFloatingFilterType = "agSetColumnFloatingFilter";
    } else {
      const cellDataType = this.dataTypeService.getBaseDataType(column);
      if (cellDataType === "number") {
        defaultFloatingFilterType = "agNumberColumnFloatingFilter";
      } else if (cellDataType === "date" || cellDataType === "dateString") {
        defaultFloatingFilterType = "agDateColumnFloatingFilter";
      } else {
        defaultFloatingFilterType = "agTextColumnFloatingFilter";
      }
    }
    return defaultFloatingFilterType;
  }
  createFilterInstance(column) {
    const defaultFilter = this.getDefaultFilter(column);
    const colDef = column.getColDef();
    let filterInstance;
    const params = __spreadProps(__spreadValues({}, this.createFilterParams(column, colDef)), {
      filterModifiedCallback: () => this.filterModifiedCallbackFactory(filterInstance, column)(),
      filterChangedCallback: (additionalEventAttributes) => this.filterChangedCallbackFactory(filterInstance, column)(additionalEventAttributes),
      doesRowPassOtherFilter: (node) => this.doesRowPassOtherFilters(filterInstance, node)
    });
    const compDetails = this.userComponentFactory.getFilterDetails(colDef, params, defaultFilter);
    if (!compDetails) {
      return { filterPromise: null, compDetails: null };
    }
    return {
      filterPromise: () => {
        const filterPromise = compDetails.newAgStackInstance();
        if (filterPromise) {
          filterPromise.then((r) => filterInstance = r);
        }
        return filterPromise;
      },
      compDetails
    };
  }
  createFilterParams(column, colDef) {
    const params = this.gos.addGridCommonParams({
      column,
      colDef: cloneObject(colDef),
      rowModel: this.rowModel,
      filterChangedCallback: () => {
      },
      filterModifiedCallback: () => {
      },
      valueGetter: this.createValueGetter(column),
      getValue: this.createGetValue(column),
      doesRowPassOtherFilter: () => true
    });
    return params;
  }
  createFilterWrapper(column, source) {
    var _a;
    const filterWrapper = {
      column,
      filterPromise: null,
      compiledElement: null,
      compDetails: null
    };
    const { filterPromise, compDetails } = this.createFilterInstance(column);
    filterWrapper.filterPromise = (_a = filterPromise == null ? void 0 : filterPromise()) != null ? _a : null;
    filterWrapper.compDetails = compDetails;
    return filterWrapper;
  }
  onColumnsChanged() {
    const columns = [];
    this.allColumnFilters.forEach((wrapper, colId) => {
      let currentColumn;
      if (wrapper.column.isPrimary()) {
        currentColumn = this.columnModel.getPrimaryColumn(colId);
      } else {
        currentColumn = this.columnModel.getGridColumn(colId);
      }
      if (currentColumn && currentColumn === wrapper.column) {
        return;
      }
      columns.push(wrapper.column);
      this.disposeFilterWrapper(wrapper, "columnChanged");
      this.disposeColumnListener(colId);
    });
    if (columns.length > 0) {
      this.onFilterChanged({ columns, source: "api" });
    } else {
      this.updateDependantFilters();
    }
  }
  updateDependantFilters() {
    const groupColumns = this.columnModel.getGroupAutoColumns();
    groupColumns == null ? void 0 : groupColumns.forEach((groupColumn) => {
      if (groupColumn.getColDef().filter === "agGroupColumnFilter") {
        this.getOrCreateFilterWrapper(groupColumn, "NO_UI");
      }
    });
  }
  // for group filters, can change dynamically whether they are allowed or not
  isFilterAllowed(column) {
    var _a, _b;
    if (this.isAdvancedFilterEnabled()) {
      return false;
    }
    const isFilterAllowed = column.isFilterAllowed();
    if (!isFilterAllowed) {
      return false;
    }
    const filterWrapper = this.allColumnFilters.get(column.getColId());
    return (_b = (_a = filterWrapper == null ? void 0 : filterWrapper.filterPromise) == null ? void 0 : _a.resolveNow(
      true,
      // defer to filter component isFilterAllowed if it exists
      (filter) => typeof (filter == null ? void 0 : filter.isFilterAllowed) === "function" ? filter == null ? void 0 : filter.isFilterAllowed() : true
    )) != null ? _b : true;
  }
  getFloatingFilterCompDetails(column, showParentFilter) {
    const parentFilterInstance = (callback) => {
      const filterComponent = this.getFilterComponent(column, "NO_UI");
      if (filterComponent == null) {
        return;
      }
      filterComponent.then((instance) => {
        callback(unwrapUserComp(instance));
      });
    };
    const colDef = column.getColDef();
    const filterParams = __spreadProps(__spreadValues({}, this.createFilterParams(column, colDef)), {
      filterChangedCallback: () => parentFilterInstance((filterInstance) => this.filterChangedCallbackFactory(filterInstance, column)())
    });
    const finalFilterParams = this.userComponentFactory.mergeParamsWithApplicationProvidedParams(colDef, FilterComponent, filterParams);
    let defaultFloatingFilterType = this.userComponentFactory.getDefaultFloatingFilterType(colDef, () => this.getDefaultFloatingFilter(column));
    if (defaultFloatingFilterType == null) {
      defaultFloatingFilterType = "agReadOnlyFloatingFilter";
    }
    const params = {
      column,
      filterParams: finalFilterParams,
      currentParentModel: () => this.getCurrentFloatingFilterParentModel(column),
      parentFilterInstance,
      showParentFilter,
      suppressFilterButton: false
      // This one might be overridden from the colDef
    };
    return this.userComponentFactory.getFloatingFilterCompDetails(colDef, params, defaultFloatingFilterType);
  }
  getCurrentFloatingFilterParentModel(column) {
    const filterComponent = this.getFilterComponent(column, "NO_UI", false);
    return filterComponent ? filterComponent.resolveNow(null, (filter) => filter && filter.getModel()) : null;
  }
  // destroys the filter, so it no longer takes part
  destroyFilter(column, source = "api") {
    const colId = column.getColId();
    const filterWrapper = this.allColumnFilters.get(colId);
    this.disposeColumnListener(colId);
    delete this.initialFilterModel[colId];
    if (filterWrapper) {
      this.disposeFilterWrapper(filterWrapper, source);
      this.onFilterChanged({
        columns: [column],
        source: "api"
      });
    }
  }
  disposeColumnListener(colId) {
    const columnListener = this.allColumnListeners.get(colId);
    if (columnListener) {
      this.allColumnListeners.delete(colId);
      columnListener();
    }
  }
  disposeFilterWrapper(filterWrapper, source) {
    filterWrapper.filterPromise.then((filter) => {
      this.getContext().destroyBean(filter);
      filterWrapper.column.setFilterActive(false, "filterDestroyed");
      this.allColumnFilters.delete(filterWrapper.column.getColId());
      const event = {
        type: Events.EVENT_FILTER_DESTROYED,
        source,
        column: filterWrapper.column
      };
      this.eventService.dispatchEvent(event);
    });
  }
  filterModifiedCallbackFactory(filter, column) {
    return () => {
      const event = {
        type: Events.EVENT_FILTER_MODIFIED,
        column,
        filterInstance: filter
      };
      this.eventService.dispatchEvent(event);
    };
  }
  filterChangedCallbackFactory(filter, column) {
    return (additionalEventAttributes) => {
      var _a;
      const source = (_a = additionalEventAttributes == null ? void 0 : additionalEventAttributes.source) != null ? _a : "api";
      const params = {
        filter,
        additionalEventAttributes,
        columns: [column],
        source
      };
      this.callOnFilterChangedOutsideRenderCycle(params);
    };
  }
  checkDestroyFilter(colId) {
    const filterWrapper = this.allColumnFilters.get(colId);
    if (!filterWrapper) {
      return;
    }
    const column = filterWrapper.column;
    const { compDetails } = column.isFilterAllowed() ? this.createFilterInstance(column) : { compDetails: null };
    if (this.areFilterCompsDifferent(filterWrapper.compDetails, compDetails)) {
      this.destroyFilter(column, "paramsUpdated");
      return;
    }
    const newFilterParams = column.getColDef().filterParams;
    if (!filterWrapper.filterPromise) {
      this.destroyFilter(column, "paramsUpdated");
      return;
    }
    filterWrapper.filterPromise.then((filter) => {
      const shouldRefreshFilter = (filter == null ? void 0 : filter.refresh) ? filter.refresh(__spreadValues(__spreadProps(__spreadValues({}, this.createFilterParams(column, column.getColDef())), {
        filterModifiedCallback: this.filterModifiedCallbackFactory(filter, column),
        filterChangedCallback: this.filterChangedCallbackFactory(filter, column),
        doesRowPassOtherFilter: (node) => this.doesRowPassOtherFilters(filter, node)
      }), newFilterParams)) : true;
      if (shouldRefreshFilter === false) {
        this.destroyFilter(column, "paramsUpdated");
      }
    });
  }
  setColumnFilterWrapper(column, filterWrapper) {
    const colId = column.getColId();
    this.allColumnFilters.set(colId, filterWrapper);
    this.allColumnListeners.set(
      colId,
      this.addManagedListener(
        column,
        Column.EVENT_COL_DEF_CHANGED,
        () => this.checkDestroyFilter(colId)
      )
    );
  }
  areFilterCompsDifferent(oldCompDetails, newCompDetails) {
    if (!newCompDetails || !oldCompDetails) {
      return true;
    }
    const { componentClass: oldComponentClass } = oldCompDetails;
    const { componentClass: newComponentClass } = newCompDetails;
    const isSameComponentClass = oldComponentClass === newComponentClass || // react hooks returns new wrappers, so check nested render method
    (oldComponentClass == null ? void 0 : oldComponentClass.render) && (newComponentClass == null ? void 0 : newComponentClass.render) && oldComponentClass.render === newComponentClass.render;
    return !isSameComponentClass;
  }
  getAdvancedFilterModel() {
    return this.isAdvancedFilterEnabled() ? this.advancedFilterService.getModel() : null;
  }
  setAdvancedFilterModel(expression) {
    if (!this.isAdvancedFilterEnabled()) {
      return;
    }
    if (this.dataTypeService.isPendingInference()) {
      this.advancedFilterModelUpdateQueue.push(expression);
      return;
    }
    this.advancedFilterService.setModel(expression != null ? expression : null);
    this.onFilterChanged({ source: "advancedFilter" });
  }
  showAdvancedFilterBuilder(source) {
    if (!this.isAdvancedFilterEnabled()) {
      return;
    }
    this.advancedFilterService.getCtrl().toggleFilterBuilder(source, true);
  }
  updateAdvancedFilterColumns() {
    if (!this.isAdvancedFilterEnabled()) {
      return;
    }
    if (this.advancedFilterService.updateValidity()) {
      this.onFilterChanged({ source: "advancedFilter" });
    }
  }
  hasFloatingFilters() {
    if (this.isAdvancedFilterEnabled()) {
      return false;
    }
    const gridColumns = this.columnModel.getAllGridColumns();
    return gridColumns.some((col) => col.getColDef().floatingFilter);
  }
  getFilterInstance(key, callback) {
    if (this.isAdvancedFilterEnabled()) {
      this.warnAdvancedFilters();
      return void 0;
    }
    const res = this.getFilterInstanceImpl(key, (instance) => {
      if (!callback) {
        return;
      }
      const unwrapped2 = unwrapUserComp(instance);
      callback(unwrapped2);
    });
    const unwrapped = unwrapUserComp(res);
    return unwrapped;
  }
  getColumnFilterInstance(key) {
    return new Promise((resolve) => {
      this.getFilterInstance(key, (filter) => {
        resolve(filter);
      });
    });
  }
  getFilterInstanceImpl(key, callback) {
    const column = this.columnModel.getPrimaryColumn(key);
    if (!column) {
      return void 0;
    }
    const filterPromise = this.getFilterComponent(column, "NO_UI");
    const currentValue = filterPromise && filterPromise.resolveNow(null, (filterComp) => filterComp);
    if (currentValue) {
      setTimeout(callback, 0, currentValue);
    } else if (filterPromise) {
      filterPromise.then((comp) => {
        callback(comp);
      });
    }
    return currentValue;
  }
  warnAdvancedFilters() {
    warnOnce("Column Filter API methods have been disabled as Advanced Filters are enabled.");
  }
  setupAdvancedFilterHeaderComp(eCompToInsertBefore) {
    var _a;
    (_a = this.advancedFilterService) == null ? void 0 : _a.getCtrl().setupHeaderComp(eCompToInsertBefore);
  }
  getHeaderRowCount() {
    return this.isAdvancedFilterHeaderActive() ? 1 : 0;
  }
  getHeaderHeight() {
    return this.isAdvancedFilterHeaderActive() ? this.advancedFilterService.getCtrl().getHeaderHeight() : 0;
  }
  processFilterModelUpdateQueue() {
    this.filterModelUpdateQueue.forEach(({ model, source }) => this.setFilterModel(model, source));
    this.filterModelUpdateQueue = [];
    this.columnFilterModelUpdateQueue.forEach(({ key, model, resolve }) => {
      this.setColumnFilterModel(key, model).then(() => resolve());
    });
    this.columnFilterModelUpdateQueue = [];
    this.advancedFilterModelUpdateQueue.forEach((model) => this.setAdvancedFilterModel(model));
    this.advancedFilterModelUpdateQueue = [];
  }
  getColumnFilterModel(key) {
    const filterWrapper = this.getFilterWrapper(key);
    return filterWrapper ? this.getModelFromFilterWrapper(filterWrapper) : null;
  }
  setColumnFilterModel(key, model) {
    if (this.isAdvancedFilterEnabled()) {
      this.warnAdvancedFilters();
      return Promise.resolve();
    }
    if (this.dataTypeService.isPendingInference()) {
      let resolve = () => {
      };
      const promise = new Promise((res) => {
        resolve = res;
      });
      this.columnFilterModelUpdateQueue.push({ key, model, resolve });
      return promise;
    }
    const column = this.columnModel.getPrimaryColumn(key);
    const filterWrapper = column ? this.getOrCreateFilterWrapper(column, "NO_UI") : null;
    const convertPromise = (promise) => {
      return new Promise((resolve) => {
        promise.then((result) => resolve(result));
      });
    };
    return filterWrapper ? convertPromise(this.setModelOnFilterWrapper(filterWrapper.filterPromise, model)) : Promise.resolve();
  }
  getFilterWrapper(key) {
    var _a;
    const column = this.columnModel.getPrimaryColumn(key);
    return column ? (_a = this.cachedFilter(column)) != null ? _a : null : null;
  }
  destroy() {
    super.destroy();
    this.allColumnFilters.forEach((filterWrapper) => this.disposeFilterWrapper(filterWrapper, "gridDestroyed"));
    this.allColumnListeners.clear();
  }
};
__decorateClass([
  Autowired("valueService")
], FilterManager.prototype, "valueService", 2);
__decorateClass([
  Autowired("columnModel")
], FilterManager.prototype, "columnModel", 2);
__decorateClass([
  Autowired("rowModel")
], FilterManager.prototype, "rowModel", 2);
__decorateClass([
  Autowired("userComponentFactory")
], FilterManager.prototype, "userComponentFactory", 2);
__decorateClass([
  Autowired("rowRenderer")
], FilterManager.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("dataTypeService")
], FilterManager.prototype, "dataTypeService", 2);
__decorateClass([
  Autowired("quickFilterService")
], FilterManager.prototype, "quickFilterService", 2);
__decorateClass([
  Optional("advancedFilterService")
], FilterManager.prototype, "advancedFilterService", 2);
__decorateClass([
  PostConstruct
], FilterManager.prototype, "init", 1);
FilterManager = __decorateClass([
  Bean("filterManager")
], FilterManager);

// community-modules/core/src/filter/filterWrapperComp.ts
var FilterWrapperComp = class extends Component {
  constructor(column, source) {
    super(
      /* html */
      `<div class="ag-filter"></div>`
    );
    this.column = column;
    this.source = source;
    this.filterWrapper = null;
  }
  postConstruct() {
    this.createFilter(true);
    this.addManagedListener(this.eventService, Events.EVENT_FILTER_DESTROYED, this.onFilterDestroyed.bind(this));
  }
  hasFilter() {
    return !!this.filterWrapper;
  }
  getFilter() {
    var _a, _b;
    return (_b = (_a = this.filterWrapper) == null ? void 0 : _a.filterPromise) != null ? _b : null;
  }
  afterInit() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this.filterWrapper) == null ? void 0 : _a.filterPromise) == null ? void 0 : _b.then(() => {
    })) != null ? _c : AgPromise.resolve();
  }
  afterGuiAttached(params) {
    var _a, _b;
    (_b = (_a = this.filterWrapper) == null ? void 0 : _a.filterPromise) == null ? void 0 : _b.then((filter) => {
      var _a2;
      (_a2 = filter == null ? void 0 : filter.afterGuiAttached) == null ? void 0 : _a2.call(filter, params);
    });
  }
  afterGuiDetached() {
    var _a, _b;
    (_b = (_a = this.filterWrapper) == null ? void 0 : _a.filterPromise) == null ? void 0 : _b.then((filter) => {
      var _a2;
      (_a2 = filter == null ? void 0 : filter.afterGuiDetached) == null ? void 0 : _a2.call(filter);
    });
  }
  createFilter(init) {
    var _a;
    const { column, source } = this;
    this.filterWrapper = this.filterManager.getOrCreateFilterWrapper(column, source);
    if (!((_a = this.filterWrapper) == null ? void 0 : _a.filterPromise)) {
      return;
    }
    this.filterWrapper.filterPromise.then((filter) => {
      let guiFromFilter = filter.getGui();
      if (!exists(guiFromFilter)) {
        console.warn(`AG Grid: getGui method from filter returned ${guiFromFilter}, it should be a DOM element or an HTML template string.`);
      }
      if (typeof guiFromFilter === "string") {
        guiFromFilter = loadTemplate(guiFromFilter);
      }
      this.appendChild(guiFromFilter);
      if (init) {
        const event = {
          type: Events.EVENT_FILTER_OPENED,
          column,
          source,
          eGui: this.getGui()
        };
        this.eventService.dispatchEvent(event);
      }
    });
  }
  onFilterDestroyed(event) {
    if ((event.source === "api" || event.source === "paramsUpdated") && event.column.getId() === this.column.getId() && this.columnModel.getPrimaryColumn(this.column)) {
      clearElement(this.getGui());
      this.createFilter();
    }
  }
  destroy() {
    this.filterWrapper = null;
    super.destroy();
  }
};
__decorateClass([
  Autowired("filterManager")
], FilterWrapperComp.prototype, "filterManager", 2);
__decorateClass([
  Autowired("columnModel")
], FilterWrapperComp.prototype, "columnModel", 2);
__decorateClass([
  PostConstruct
], FilterWrapperComp.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/cells/abstractCell/abstractHeaderCellComp.ts
var AbstractHeaderCellComp = class extends Component {
  constructor(template, ctrl) {
    super(template);
    this.ctrl = ctrl;
  }
  getCtrl() {
    return this.ctrl;
  }
};

// community-modules/core/src/headerRendering/cells/floatingFilter/headerFilterCellComp.ts
var _HeaderFilterCellComp = class _HeaderFilterCellComp extends AbstractHeaderCellComp {
  constructor(ctrl) {
    super(_HeaderFilterCellComp.TEMPLATE, ctrl);
  }
  postConstruct() {
    const eGui = this.getGui();
    const compProxy = {
      addOrRemoveCssClass: (cssClassName, on) => this.addOrRemoveCssClass(cssClassName, on),
      addOrRemoveBodyCssClass: (cssClassName, on) => this.eFloatingFilterBody.classList.toggle(cssClassName, on),
      setButtonWrapperDisplayed: (displayed) => setDisplayed(this.eButtonWrapper, displayed),
      setCompDetails: (compDetails) => this.setCompDetails(compDetails),
      getFloatingFilterComp: () => this.compPromise,
      setWidth: (width) => eGui.style.width = width,
      setMenuIcon: (eIcon) => this.eButtonShowMainFilter.appendChild(eIcon)
    };
    this.ctrl.setComp(compProxy, eGui, this.eButtonShowMainFilter, this.eFloatingFilterBody);
  }
  setCompDetails(compDetails) {
    if (!compDetails) {
      this.destroyFloatingFilterComp();
      this.compPromise = null;
      return;
    }
    this.compPromise = compDetails.newAgStackInstance();
    this.compPromise.then((comp) => this.afterCompCreated(comp));
  }
  destroyFloatingFilterComp() {
    if (this.floatingFilterComp) {
      this.eFloatingFilterBody.removeChild(this.floatingFilterComp.getGui());
      this.floatingFilterComp = this.destroyBean(this.floatingFilterComp);
    }
  }
  afterCompCreated(comp) {
    if (!comp) {
      return;
    }
    if (!this.isAlive()) {
      this.destroyBean(comp);
      return;
    }
    this.destroyFloatingFilterComp();
    this.floatingFilterComp = comp;
    this.eFloatingFilterBody.appendChild(comp.getGui());
    if (comp.afterGuiAttached) {
      comp.afterGuiAttached();
    }
  }
};
_HeaderFilterCellComp.TEMPLATE = /* html */
`<div class="ag-header-cell ag-floating-filter" role="gridcell">
            <div ref="eFloatingFilterBody" role="presentation"></div>
            <div class="ag-floating-filter-button ag-hidden" ref="eButtonWrapper" role="presentation">
                <button type="button" class="ag-button ag-floating-filter-button-button" ref="eButtonShowMainFilter" tabindex="-1"></button>
            </div>
        </div>`;
__decorateClass([
  RefSelector("eFloatingFilterBody")
], _HeaderFilterCellComp.prototype, "eFloatingFilterBody", 2);
__decorateClass([
  RefSelector("eButtonWrapper")
], _HeaderFilterCellComp.prototype, "eButtonWrapper", 2);
__decorateClass([
  RefSelector("eButtonShowMainFilter")
], _HeaderFilterCellComp.prototype, "eButtonShowMainFilter", 2);
__decorateClass([
  PostConstruct
], _HeaderFilterCellComp.prototype, "postConstruct", 1);
__decorateClass([
  PreDestroy
], _HeaderFilterCellComp.prototype, "destroyFloatingFilterComp", 1);
var HeaderFilterCellComp = _HeaderFilterCellComp;

// community-modules/core/src/styling/layoutFeature.ts
var LayoutCssClasses = /* @__PURE__ */ ((LayoutCssClasses2) => {
  LayoutCssClasses2["AUTO_HEIGHT"] = "ag-layout-auto-height";
  LayoutCssClasses2["NORMAL"] = "ag-layout-normal";
  LayoutCssClasses2["PRINT"] = "ag-layout-print";
  return LayoutCssClasses2;
})(LayoutCssClasses || {});
var LayoutFeature = class extends BeanStub {
  constructor(view) {
    super();
    this.view = view;
  }
  postConstruct() {
    this.addManagedPropertyListener("domLayout", this.updateLayoutClasses.bind(this));
    this.updateLayoutClasses();
  }
  updateLayoutClasses() {
    const domLayout = this.getDomLayout();
    const params = {
      autoHeight: domLayout === "autoHeight",
      normal: domLayout === "normal",
      print: domLayout === "print"
    };
    const cssClass = params.autoHeight ? "ag-layout-auto-height" /* AUTO_HEIGHT */ : params.print ? "ag-layout-print" /* PRINT */ : "ag-layout-normal" /* NORMAL */;
    this.view.updateLayoutClasses(cssClass, params);
  }
  // returns either 'print', 'autoHeight' or 'normal' (normal is the default)
  getDomLayout() {
    var _a;
    const domLayout = (_a = this.gos.get("domLayout")) != null ? _a : "normal";
    const validLayouts = ["normal", "print", "autoHeight"];
    if (validLayouts.indexOf(domLayout) === -1) {
      warnOnce(`${domLayout} is not valid for DOM Layout, valid values are 'normal', 'autoHeight', 'print'.`);
      return "normal";
    }
    return domLayout;
  }
};
__decorateClass([
  PostConstruct
], LayoutFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/gridBodyScrollFeature.ts
var GridBodyScrollFeature = class extends BeanStub {
  constructor(eBodyViewport) {
    super();
    this.lastScrollSource = [null, null];
    this.scrollLeft = -1;
    this.nextScrollTop = -1;
    this.scrollTop = -1;
    // Used to provide approximate values of scrollTop and offsetHeight
    // without forcing the browser to recalculate styles.
    this.lastOffsetHeight = -1;
    this.lastScrollTop = -1;
    this.eBodyViewport = eBodyViewport;
    this.resetLastHScrollDebounced = debounce(() => this.lastScrollSource[1 /* Horizontal */] = null, 500);
    this.resetLastVScrollDebounced = debounce(() => this.lastScrollSource[0 /* Vertical */] = null, 500);
  }
  postConstruct() {
    this.enableRtl = this.gos.get("enableRtl");
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, this.onDisplayedColumnsWidthChanged.bind(this));
    this.ctrlsService.whenReady((p) => {
      this.centerRowsCtrl = p.center;
      this.onDisplayedColumnsWidthChanged();
      this.addScrollListener();
    });
  }
  addScrollListener() {
    const { fakeHScrollComp, fakeVScrollComp } = this.ctrlsService.getParams();
    this.addManagedListener(this.centerRowsCtrl.getViewportElement(), "scroll", this.onHScroll.bind(this));
    fakeHScrollComp.onScrollCallback(this.onFakeHScroll.bind(this));
    const isDebounce = this.gos.get("debounceVerticalScrollbar");
    const onVScroll = isDebounce ? debounce(this.onVScroll.bind(this), 100) : this.onVScroll.bind(this);
    const onFakeVScroll = isDebounce ? debounce(this.onFakeVScroll.bind(this), 100) : this.onFakeVScroll.bind(this);
    this.addManagedListener(this.eBodyViewport, "scroll", onVScroll);
    fakeVScrollComp.onScrollCallback(onFakeVScroll);
  }
  onDisplayedColumnsWidthChanged() {
    if (this.enableRtl) {
      this.horizontallyScrollHeaderCenterAndFloatingCenter();
    }
  }
  horizontallyScrollHeaderCenterAndFloatingCenter(scrollLeft) {
    const notYetInitialised = this.centerRowsCtrl == null;
    if (notYetInitialised) {
      return;
    }
    if (scrollLeft === void 0) {
      scrollLeft = this.centerRowsCtrl.getCenterViewportScrollLeft();
    }
    const offset = this.enableRtl ? scrollLeft : -scrollLeft;
    const {
      topCenter,
      stickyTopCenter,
      stickyBottomCenter,
      centerHeader,
      bottomCenter,
      fakeHScrollComp
    } = this.ctrlsService.getParams();
    centerHeader.setHorizontalScroll(-offset);
    bottomCenter.setContainerTranslateX(offset);
    topCenter.setContainerTranslateX(offset);
    stickyTopCenter.setContainerTranslateX(offset);
    stickyBottomCenter.setContainerTranslateX(offset);
    const centerViewport = this.centerRowsCtrl.getViewportElement();
    const isCenterViewportLastHorizontal = this.lastScrollSource[1 /* Horizontal */] === 0 /* Container */;
    scrollLeft = Math.abs(scrollLeft);
    if (isCenterViewportLastHorizontal) {
      fakeHScrollComp.setScrollPosition(scrollLeft);
    } else {
      setScrollLeft(centerViewport, scrollLeft, this.enableRtl);
    }
  }
  isControllingScroll(source, direction) {
    if (this.lastScrollSource[direction] == null) {
      this.lastScrollSource[direction] = source;
      return true;
    }
    return this.lastScrollSource[direction] === source;
  }
  onFakeHScroll() {
    if (!this.isControllingScroll(1 /* FakeContainer */, 1 /* Horizontal */)) {
      return;
    }
    this.onHScrollCommon(1 /* FakeContainer */);
  }
  onHScroll() {
    if (!this.isControllingScroll(0 /* Container */, 1 /* Horizontal */)) {
      return;
    }
    this.onHScrollCommon(0 /* Container */);
  }
  onHScrollCommon(source) {
    const centerContainerViewport = this.centerRowsCtrl.getViewportElement();
    const { scrollLeft } = centerContainerViewport;
    if (this.shouldBlockScrollUpdate(1 /* Horizontal */, scrollLeft, true)) {
      return;
    }
    let newScrollLeft;
    if (source === 0 /* Container */) {
      newScrollLeft = getScrollLeft(centerContainerViewport, this.enableRtl);
    } else {
      newScrollLeft = this.ctrlsService.get("fakeHScrollComp").getScrollPosition();
    }
    this.doHorizontalScroll(Math.round(newScrollLeft));
    this.resetLastHScrollDebounced();
  }
  onFakeVScroll() {
    if (!this.isControllingScroll(1 /* FakeContainer */, 0 /* Vertical */)) {
      return;
    }
    this.onVScrollCommon(1 /* FakeContainer */);
  }
  onVScroll() {
    if (!this.isControllingScroll(0 /* Container */, 0 /* Vertical */)) {
      return;
    }
    this.onVScrollCommon(0 /* Container */);
  }
  onVScrollCommon(source) {
    let scrollTop;
    if (source === 0 /* Container */) {
      scrollTop = this.eBodyViewport.scrollTop;
    } else {
      scrollTop = this.ctrlsService.get("fakeVScrollComp").getScrollPosition();
    }
    if (this.shouldBlockScrollUpdate(0 /* Vertical */, scrollTop, true)) {
      return;
    }
    this.animationFrameService.setScrollTop(scrollTop);
    this.nextScrollTop = scrollTop;
    if (source === 0 /* Container */) {
      this.ctrlsService.get("fakeVScrollComp").setScrollPosition(scrollTop);
    } else {
      this.eBodyViewport.scrollTop = scrollTop;
    }
    if (this.gos.get("suppressAnimationFrame")) {
      this.scrollGridIfNeeded();
    } else {
      this.animationFrameService.schedule();
    }
    this.resetLastVScrollDebounced();
  }
  doHorizontalScroll(scrollLeft) {
    const fakeScrollLeft = this.ctrlsService.get("fakeHScrollComp").getScrollPosition();
    if (this.scrollLeft === scrollLeft && scrollLeft === fakeScrollLeft) {
      return;
    }
    this.scrollLeft = scrollLeft;
    this.fireScrollEvent(1 /* Horizontal */);
    this.horizontallyScrollHeaderCenterAndFloatingCenter(scrollLeft);
    this.centerRowsCtrl.onHorizontalViewportChanged(true);
  }
  fireScrollEvent(direction) {
    const bodyScrollEvent = {
      type: Events.EVENT_BODY_SCROLL,
      direction: direction === 1 /* Horizontal */ ? "horizontal" : "vertical",
      left: this.scrollLeft,
      top: this.scrollTop
    };
    this.eventService.dispatchEvent(bodyScrollEvent);
    window.clearTimeout(this.scrollTimer);
    this.scrollTimer = void 0;
    this.scrollTimer = window.setTimeout(() => {
      const bodyScrollEndEvent = __spreadProps(__spreadValues({}, bodyScrollEvent), {
        type: Events.EVENT_BODY_SCROLL_END
      });
      this.eventService.dispatchEvent(bodyScrollEndEvent);
    }, 100);
  }
  shouldBlockScrollUpdate(direction, scrollTo, touchOnly = false) {
    if (touchOnly && !isIOSUserAgent()) {
      return false;
    }
    if (direction === 0 /* Vertical */) {
      return this.shouldBlockVerticalScroll(scrollTo);
    }
    return this.shouldBlockHorizontalScroll(scrollTo);
  }
  shouldBlockVerticalScroll(scrollTo) {
    const clientHeight = getInnerHeight(this.eBodyViewport);
    const { scrollHeight } = this.eBodyViewport;
    if (scrollTo < 0 || scrollTo + clientHeight > scrollHeight) {
      return true;
    }
    return false;
  }
  shouldBlockHorizontalScroll(scrollTo) {
    const clientWidth = this.centerRowsCtrl.getCenterWidth();
    const { scrollWidth } = this.centerRowsCtrl.getViewportElement();
    if (this.enableRtl && isRtlNegativeScroll()) {
      if (scrollTo > 0) {
        return true;
      }
    } else if (scrollTo < 0) {
      return true;
    }
    if (Math.abs(scrollTo) + clientWidth > scrollWidth) {
      return true;
    }
    return false;
  }
  redrawRowsAfterScroll() {
    this.fireScrollEvent(0 /* Vertical */);
  }
  // this is to cater for AG-3274, where grid is removed from the dom and then inserted back in again.
  // (which happens with some implementations of tabbing). this can result in horizontal scroll getting
  // reset back to the left, however no scroll event is fired. so we need to get header to also scroll
  // back to the left to be kept in sync.
  // adding and removing the grid from the DOM both resets the scroll position and
  // triggers a resize event, so notify listeners if the scroll position has changed
  checkScrollLeft() {
    if (this.scrollLeft !== this.centerRowsCtrl.getCenterViewportScrollLeft()) {
      this.onHScrollCommon(0 /* Container */);
    }
  }
  scrollGridIfNeeded() {
    const frameNeeded = this.scrollTop != this.nextScrollTop;
    if (frameNeeded) {
      this.scrollTop = this.nextScrollTop;
      this.redrawRowsAfterScroll();
    }
    return frameNeeded;
  }
  // called by scrollHorizontally method and alignedGridsService
  setHorizontalScrollPosition(hScrollPosition, fromAlignedGridsService = false) {
    const minScrollLeft = 0;
    const maxScrollLeft = this.centerRowsCtrl.getViewportElement().scrollWidth - this.centerRowsCtrl.getCenterWidth();
    if (!fromAlignedGridsService && this.shouldBlockScrollUpdate(1 /* Horizontal */, hScrollPosition)) {
      if (this.enableRtl && isRtlNegativeScroll()) {
        hScrollPosition = hScrollPosition > 0 ? 0 : maxScrollLeft;
      } else {
        hScrollPosition = Math.min(Math.max(hScrollPosition, minScrollLeft), maxScrollLeft);
      }
    }
    setScrollLeft(this.centerRowsCtrl.getViewportElement(), Math.abs(hScrollPosition), this.enableRtl);
    this.doHorizontalScroll(hScrollPosition);
  }
  setVerticalScrollPosition(vScrollPosition) {
    this.eBodyViewport.scrollTop = vScrollPosition;
  }
  getVScrollPosition() {
    this.lastScrollTop = this.eBodyViewport.scrollTop;
    this.lastOffsetHeight = this.eBodyViewport.offsetHeight;
    const result = {
      top: this.lastScrollTop,
      bottom: this.lastScrollTop + this.lastOffsetHeight
    };
    return result;
  }
  /** Get an approximate scroll position that returns the last real value read.
   * This is useful for avoiding repeated DOM reads that force the browser to recalculate styles.
   * This can have big performance improvements but may not be 100% accurate so only use if this is acceptable.
   */
  getApproximateVScollPosition() {
    if (this.lastScrollTop >= 0 && this.lastOffsetHeight >= 0) {
      return {
        top: this.scrollTop,
        bottom: this.scrollTop + this.lastOffsetHeight
      };
    }
    return this.getVScrollPosition();
  }
  getHScrollPosition() {
    return this.centerRowsCtrl.getHScrollPosition();
  }
  isHorizontalScrollShowing() {
    return this.centerRowsCtrl.isHorizontalScrollShowing();
  }
  // called by the headerRootComp and moveColumnController
  scrollHorizontally(pixels) {
    const oldScrollPosition = this.centerRowsCtrl.getViewportElement().scrollLeft;
    this.setHorizontalScrollPosition(oldScrollPosition + pixels);
    return this.centerRowsCtrl.getViewportElement().scrollLeft - oldScrollPosition;
  }
  // gets called by rowRenderer when new data loaded, as it will want to scroll to the top
  scrollToTop() {
    this.eBodyViewport.scrollTop = 0;
  }
  // Valid values for position are bottom, middle and top
  ensureNodeVisible(comparator, position = null) {
    const rowCount = this.rowModel.getRowCount();
    let indexToSelect = -1;
    for (let i = 0; i < rowCount; i++) {
      const node = this.rowModel.getRow(i);
      if (typeof comparator === "function") {
        const predicate = comparator;
        if (node && predicate(node)) {
          indexToSelect = i;
          break;
        }
      } else {
        if (comparator === node || comparator === node.data) {
          indexToSelect = i;
          break;
        }
      }
    }
    if (indexToSelect >= 0) {
      this.ensureIndexVisible(indexToSelect, position);
    }
  }
  // Valid values for position are bottom, middle and top
  // position should be {'top','middle','bottom', or undefined/null}.
  // if undefined/null, then the grid will to the minimal amount of scrolling,
  // eg if grid needs to scroll up, it scrolls until row is on top,
  //    if grid needs to scroll down, it scrolls until row is on bottom,
  //    if row is already in view, grid does not scroll
  ensureIndexVisible(index, position) {
    if (this.gos.isDomLayout("print")) {
      return;
    }
    const rowCount = this.paginationProxy.getRowCount();
    if (typeof index !== "number" || index < 0 || index >= rowCount) {
      console.warn("AG Grid: Invalid row index for ensureIndexVisible: " + index);
      return;
    }
    const isPaging = this.gos.get("pagination");
    const paginationPanelEnabled = isPaging && !this.gos.get("suppressPaginationPanel");
    this.getFrameworkOverrides().wrapIncoming(() => {
      if (!paginationPanelEnabled) {
        this.paginationProxy.goToPageWithIndex(index);
      }
      const gridBodyCtrl = this.ctrlsService.getGridBodyCtrl();
      const stickyTopHeight = gridBodyCtrl.getStickyTopHeight();
      const stickyBottomHeight = gridBodyCtrl.getStickyBottomHeight();
      const rowNode = this.paginationProxy.getRow(index);
      let rowGotShiftedDuringOperation;
      do {
        const startingRowTop = rowNode.rowTop;
        const startingRowHeight = rowNode.rowHeight;
        const paginationOffset = this.paginationProxy.getPixelOffset();
        const rowTopPixel = rowNode.rowTop - paginationOffset;
        const rowBottomPixel = rowTopPixel + rowNode.rowHeight;
        const scrollPosition = this.getVScrollPosition();
        const heightOffset = this.heightScaler.getDivStretchOffset();
        const vScrollTop = scrollPosition.top + heightOffset;
        const vScrollBottom = scrollPosition.bottom + heightOffset;
        const viewportHeight = vScrollBottom - vScrollTop;
        const pxTop = this.heightScaler.getScrollPositionForPixel(rowTopPixel);
        const pxBottom = this.heightScaler.getScrollPositionForPixel(rowBottomPixel - viewportHeight);
        const pxMiddle = Math.min((pxTop + pxBottom) / 2, rowTopPixel);
        const rowAboveViewport = vScrollTop + stickyTopHeight > rowTopPixel;
        const rowBelowViewport = vScrollBottom - stickyBottomHeight < rowBottomPixel;
        let newScrollPosition = null;
        if (position === "top") {
          newScrollPosition = pxTop;
        } else if (position === "bottom") {
          newScrollPosition = pxBottom;
        } else if (position === "middle") {
          newScrollPosition = pxMiddle;
        } else if (rowAboveViewport) {
          newScrollPosition = pxTop - stickyTopHeight;
        } else if (rowBelowViewport) {
          newScrollPosition = pxBottom + stickyBottomHeight;
        }
        if (newScrollPosition !== null) {
          this.setVerticalScrollPosition(newScrollPosition);
          this.rowRenderer.redraw({ afterScroll: true });
        }
        rowGotShiftedDuringOperation = startingRowTop !== rowNode.rowTop || startingRowHeight !== rowNode.rowHeight;
      } while (rowGotShiftedDuringOperation);
      this.animationFrameService.flushAllFrames();
    });
  }
  ensureColumnVisible(key, position = "auto") {
    const column = this.columnModel.getGridColumn(key);
    if (!column) {
      return;
    }
    if (column.isPinned()) {
      return;
    }
    if (!this.columnModel.isColumnDisplayed(column)) {
      return;
    }
    const newHorizontalScroll = this.getPositionedHorizontalScroll(column, position);
    this.getFrameworkOverrides().wrapIncoming(() => {
      if (newHorizontalScroll !== null) {
        this.centerRowsCtrl.setCenterViewportScrollLeft(newHorizontalScroll);
      }
      this.centerRowsCtrl.onHorizontalViewportChanged();
      this.animationFrameService.flushAllFrames();
    });
  }
  setScrollPosition(top, left) {
    this.getFrameworkOverrides().wrapIncoming(() => {
      this.centerRowsCtrl.setCenterViewportScrollLeft(left);
      this.setVerticalScrollPosition(top);
      this.rowRenderer.redraw({ afterScroll: true });
      this.animationFrameService.flushAllFrames();
    });
  }
  getPositionedHorizontalScroll(column, position) {
    const { columnBeforeStart, columnAfterEnd } = this.isColumnOutsideViewport(column);
    const viewportTooSmallForColumn = this.centerRowsCtrl.getCenterWidth() < column.getActualWidth();
    const viewportWidth = this.centerRowsCtrl.getCenterWidth();
    const isRtl = this.enableRtl;
    let alignColToStart = (isRtl ? columnBeforeStart : columnAfterEnd) || viewportTooSmallForColumn;
    let alignColToEnd = isRtl ? columnAfterEnd : columnBeforeStart;
    if (position !== "auto") {
      alignColToStart = position === "start";
      alignColToEnd = position === "end";
    }
    const isMiddle = position === "middle";
    if (alignColToStart || alignColToEnd || isMiddle) {
      const { colLeft, colMiddle, colRight } = this.getColumnBounds(column);
      if (isMiddle) {
        return colMiddle - viewportWidth / 2;
      }
      if (alignColToStart) {
        return isRtl ? colRight : colLeft;
      }
      return isRtl ? colLeft - viewportWidth : colRight - viewportWidth;
    }
    return null;
  }
  isColumnOutsideViewport(column) {
    const { start: viewportStart, end: viewportEnd } = this.getViewportBounds();
    const { colLeft, colRight } = this.getColumnBounds(column);
    const isRtl = this.enableRtl;
    const columnBeforeStart = isRtl ? viewportStart > colRight : viewportEnd < colRight;
    const columnAfterEnd = isRtl ? viewportEnd < colLeft : viewportStart > colLeft;
    return { columnBeforeStart, columnAfterEnd };
  }
  getColumnBounds(column) {
    const isRtl = this.enableRtl;
    const bodyWidth = this.columnModel.getBodyContainerWidth();
    const colWidth = column.getActualWidth();
    const colLeft = column.getLeft();
    const multiplier = isRtl ? -1 : 1;
    const colLeftPixel = isRtl ? bodyWidth - colLeft : colLeft;
    const colRightPixel = colLeftPixel + colWidth * multiplier;
    const colMidPixel = colLeftPixel + colWidth / 2 * multiplier;
    return { colLeft: colLeftPixel, colMiddle: colMidPixel, colRight: colRightPixel };
  }
  getViewportBounds() {
    const viewportWidth = this.centerRowsCtrl.getCenterWidth();
    const scrollPosition = this.centerRowsCtrl.getCenterViewportScrollLeft();
    const viewportStartPixel = scrollPosition;
    const viewportEndPixel = viewportWidth + scrollPosition;
    return { start: viewportStartPixel, end: viewportEndPixel, width: viewportWidth };
  }
};
__decorateClass([
  Autowired("ctrlsService")
], GridBodyScrollFeature.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("animationFrameService")
], GridBodyScrollFeature.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("paginationProxy")
], GridBodyScrollFeature.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("rowModel")
], GridBodyScrollFeature.prototype, "rowModel", 2);
__decorateClass([
  Autowired("rowContainerHeightService")
], GridBodyScrollFeature.prototype, "heightScaler", 2);
__decorateClass([
  Autowired("rowRenderer")
], GridBodyScrollFeature.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("columnModel")
], GridBodyScrollFeature.prototype, "columnModel", 2);
__decorateClass([
  PostConstruct
], GridBodyScrollFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/gridBodyCtrl.ts
var RowAnimationCssClasses = /* @__PURE__ */ ((RowAnimationCssClasses2) => {
  RowAnimationCssClasses2["ANIMATION_ON"] = "ag-row-animation";
  RowAnimationCssClasses2["ANIMATION_OFF"] = "ag-row-no-animation";
  return RowAnimationCssClasses2;
})(RowAnimationCssClasses || {});
var CSS_CLASS_FORCE_VERTICAL_SCROLL = "ag-force-vertical-scroll";
var CSS_CLASS_CELL_SELECTABLE = "ag-selectable";
var CSS_CLASS_COLUMN_MOVING = "ag-column-moving";
var GridBodyCtrl = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.stickyTopHeight = 0;
    this.stickyBottomHeight = 0;
  }
  getScrollFeature() {
    return this.bodyScrollFeature;
  }
  getBodyViewportElement() {
    return this.eBodyViewport;
  }
  setComp(comp, eGridBody, eBodyViewport, eTop, eBottom, eStickyTop, eStickyBottom) {
    this.comp = comp;
    this.eGridBody = eGridBody;
    this.eBodyViewport = eBodyViewport;
    this.eTop = eTop;
    this.eBottom = eBottom;
    this.eStickyTop = eStickyTop;
    this.eStickyBottom = eStickyBottom;
    this.setCellTextSelection(this.gos.get("enableCellTextSelection"));
    this.addManagedPropertyListener("enableCellTextSelection", (props) => this.setCellTextSelection(props.currentValue));
    this.createManagedBean(new LayoutFeature(this.comp));
    this.bodyScrollFeature = this.createManagedBean(new GridBodyScrollFeature(this.eBodyViewport));
    this.addRowDragListener();
    this.setupRowAnimationCssClass();
    this.addEventListeners();
    this.addFocusListeners([eTop, eBodyViewport, eBottom, eStickyTop, eStickyBottom]);
    this.onGridColumnsChanged();
    this.addBodyViewportListener();
    this.setFloatingHeights();
    this.disableBrowserDragging();
    this.addStopEditingWhenGridLosesFocus();
    this.filterManager.setupAdvancedFilterHeaderComp(eTop);
    this.ctrlsService.register("gridBodyCtrl", this);
  }
  getComp() {
    return this.comp;
  }
  addEventListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_PINNED_ROW_DATA_CHANGED, this.onPinnedRowDataChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_HEADER_HEIGHT_CHANGED, this.onHeaderHeightChanged.bind(this));
  }
  addFocusListeners(elements) {
    elements.forEach((element) => {
      this.addManagedListener(element, "focusin", (e) => {
        const { target } = e;
        const isFocusedElementNested = isElementChildOfClass(target, "ag-root", element);
        element.classList.toggle("ag-has-focus", !isFocusedElementNested);
      });
      this.addManagedListener(element, "focusout", (e) => {
        const { target, relatedTarget } = e;
        const gridContainRelatedTarget = element.contains(relatedTarget);
        const isNestedRelatedTarget = isElementChildOfClass(relatedTarget, "ag-root", element);
        const isNestedTarget = isElementChildOfClass(target, "ag-root", element);
        if (isNestedTarget) {
          return;
        }
        if (!gridContainRelatedTarget || isNestedRelatedTarget) {
          element.classList.remove("ag-has-focus");
        }
      });
    });
  }
  // used by ColumnAnimationService
  setColumnMovingCss(moving) {
    this.comp.setColumnMovingCss(CSS_CLASS_COLUMN_MOVING, moving);
  }
  setCellTextSelection(selectable = false) {
    this.comp.setCellSelectableCss(CSS_CLASS_CELL_SELECTABLE, selectable);
  }
  onScrollVisibilityChanged() {
    const visible = this.scrollVisibleService.isVerticalScrollShowing();
    this.setVerticalScrollPaddingVisible(visible);
    this.setStickyWidth(visible);
    this.setStickyBottomOffsetBottom();
    const scrollbarWidth = visible ? this.gos.getScrollbarWidth() || 0 : 0;
    const pad = isInvisibleScrollbar() ? 16 : 0;
    const width = `calc(100% + ${scrollbarWidth + pad}px)`;
    this.animationFrameService.requestAnimationFrame(() => this.comp.setBodyViewportWidth(width));
  }
  onGridColumnsChanged() {
    const columns = this.columnModel.getAllGridColumns();
    this.comp.setColumnCount(columns.length);
  }
  // if we do not do this, then the user can select a pic in the grid (eg an image in a custom cell renderer)
  // and then that will start the browser native drag n' drop, which messes up with our own drag and drop.
  disableBrowserDragging() {
    this.addManagedListener(this.eGridBody, "dragstart", (event) => {
      if (event.target instanceof HTMLImageElement) {
        event.preventDefault();
        return false;
      }
    });
  }
  addStopEditingWhenGridLosesFocus() {
    if (!this.gos.get("stopEditingWhenCellsLoseFocus")) {
      return;
    }
    const focusOutListener = (event) => {
      const elementWithFocus = event.relatedTarget;
      if (getTabIndex(elementWithFocus) === null) {
        this.rowRenderer.stopEditing();
        return;
      }
      let clickInsideGrid = (
        // see if click came from inside the viewports
        viewports.some((viewport) => viewport.contains(elementWithFocus)) && this.mouseEventService.isElementInThisGrid(elementWithFocus)
      );
      if (!clickInsideGrid) {
        const popupService = this.popupService;
        clickInsideGrid = popupService.getActivePopups().some((popup) => popup.contains(elementWithFocus)) || popupService.isElementWithinCustomPopup(elementWithFocus);
      }
      if (!clickInsideGrid) {
        this.rowRenderer.stopEditing();
      }
    };
    const viewports = [this.eBodyViewport, this.eBottom, this.eTop, this.eStickyTop, this.eStickyBottom];
    viewports.forEach((viewport) => this.addManagedListener(viewport, "focusout", focusOutListener));
  }
  updateRowCount() {
    const headerCount = this.headerNavigationService.getHeaderRowCount() + this.filterManager.getHeaderRowCount();
    const rowCount = this.rowModel.isLastRowIndexKnown() ? this.rowModel.getRowCount() : -1;
    const total = rowCount === -1 ? -1 : headerCount + rowCount;
    this.comp.setRowCount(total);
  }
  registerBodyViewportResizeListener(listener) {
    this.comp.registerBodyViewportResizeListener(listener);
  }
  setVerticalScrollPaddingVisible(visible) {
    const overflowY = visible ? "scroll" : "hidden";
    this.comp.setPinnedTopBottomOverflowY(overflowY);
  }
  isVerticalScrollShowing() {
    const show = this.gos.get("alwaysShowVerticalScroll");
    const cssClass = show ? CSS_CLASS_FORCE_VERTICAL_SCROLL : null;
    const allowVerticalScroll = this.gos.isDomLayout("normal");
    this.comp.setAlwaysVerticalScrollClass(cssClass, show);
    return show || allowVerticalScroll && isVerticalScrollShowing(this.eBodyViewport);
  }
  setupRowAnimationCssClass() {
    const listener = () => {
      const animateRows = this.gos.isAnimateRows() && !this.rowContainerHeightService.isStretching();
      const animateRowsCssClass = animateRows ? "ag-row-animation" /* ANIMATION_ON */ : "ag-row-no-animation" /* ANIMATION_OFF */;
      this.comp.setRowAnimationCssOnBodyViewport(animateRowsCssClass, animateRows);
    };
    listener();
    this.addManagedListener(this.eventService, Events.EVENT_HEIGHT_SCALE_CHANGED, listener);
    this.addManagedPropertyListener("animateRows", listener);
  }
  getGridBodyElement() {
    return this.eGridBody;
  }
  addBodyViewportListener() {
    const listener = this.onBodyViewportContextMenu.bind(this);
    this.addManagedListener(this.eBodyViewport, "contextmenu", listener);
    this.mockContextMenuForIPad(listener);
    this.addManagedListener(this.eBodyViewport, "wheel", this.onBodyViewportWheel.bind(this));
    this.addManagedListener(this.eStickyTop, "wheel", this.onStickyWheel.bind(this));
    this.addManagedListener(this.eStickyBottom, "wheel", this.onStickyWheel.bind(this));
    this.addFullWidthContainerWheelListener();
  }
  addFullWidthContainerWheelListener() {
    const fullWidthContainer = this.eBodyViewport.querySelector(".ag-full-width-container");
    const eCenterColsViewport = this.eBodyViewport.querySelector(".ag-center-cols-viewport");
    if (fullWidthContainer && eCenterColsViewport) {
      this.addManagedListener(fullWidthContainer, "wheel", (e) => this.onFullWidthContainerWheel(e, eCenterColsViewport));
    }
  }
  onFullWidthContainerWheel(e, eCenterColsViewport) {
    if (!e.deltaX || Math.abs(e.deltaY) > Math.abs(e.deltaX) || !this.mouseEventService.isEventFromThisGrid(e)) {
      return;
    }
    e.preventDefault();
    eCenterColsViewport.scrollBy({ left: e.deltaX });
  }
  onBodyViewportContextMenu(mouseEvent, touch, touchEvent) {
    if (!mouseEvent && !touchEvent) {
      return;
    }
    if (this.gos.get("preventDefaultOnContextMenu")) {
      const event = mouseEvent || touchEvent;
      event.preventDefault();
    }
    const { target } = mouseEvent || touch;
    if (target === this.eBodyViewport || target === this.ctrlsService.get("center").getViewportElement()) {
      this.menuService.showContextMenu({ mouseEvent, touchEvent, value: null, anchorToElement: this.eGridBody });
    }
  }
  mockContextMenuForIPad(listener) {
    if (!isIOSUserAgent()) {
      return;
    }
    const touchListener = new TouchListener(this.eBodyViewport);
    const longTapListener = (event) => {
      listener(void 0, event.touchStart, event.touchEvent);
    };
    this.addManagedListener(touchListener, TouchListener.EVENT_LONG_TAP, longTapListener);
    this.addDestroyFunc(() => touchListener.destroy());
  }
  onBodyViewportWheel(e) {
    if (!this.gos.get("suppressScrollWhenPopupsAreOpen")) {
      return;
    }
    if (this.popupService.hasAnchoredPopup()) {
      e.preventDefault();
    }
  }
  onStickyWheel(e) {
    e.preventDefault();
    if (e.offsetY) {
      this.scrollVertically(e.deltaY);
    }
  }
  getGui() {
    return this.eGridBody;
  }
  // called by rowDragFeature
  scrollVertically(pixels) {
    const oldScrollPosition = this.eBodyViewport.scrollTop;
    this.bodyScrollFeature.setVerticalScrollPosition(oldScrollPosition + pixels);
    return this.eBodyViewport.scrollTop - oldScrollPosition;
  }
  addRowDragListener() {
    this.rowDragFeature = this.createManagedBean(new RowDragFeature(this.eBodyViewport));
    this.dragAndDropService.addDropTarget(this.rowDragFeature);
  }
  getRowDragFeature() {
    return this.rowDragFeature;
  }
  onPinnedRowDataChanged() {
    this.setFloatingHeights();
  }
  setFloatingHeights() {
    const { pinnedRowModel } = this;
    let floatingTopHeight = pinnedRowModel.getPinnedTopTotalHeight();
    let floatingBottomHeight = pinnedRowModel.getPinnedBottomTotalHeight();
    this.comp.setTopHeight(floatingTopHeight);
    this.comp.setBottomHeight(floatingBottomHeight);
    this.comp.setTopDisplay(floatingTopHeight ? "inherit" : "none");
    this.comp.setBottomDisplay(floatingBottomHeight ? "inherit" : "none");
    this.setStickyTopOffsetTop();
    this.setStickyBottomOffsetBottom();
  }
  setStickyTopHeight(height = 0) {
    this.comp.setStickyTopHeight(`${height}px`);
    this.stickyTopHeight = height;
  }
  getStickyTopHeight() {
    return this.stickyTopHeight;
  }
  setStickyBottomHeight(height = 0) {
    this.comp.setStickyBottomHeight(`${height}px`);
    this.stickyBottomHeight = height;
  }
  getStickyBottomHeight() {
    return this.stickyBottomHeight;
  }
  setStickyWidth(vScrollVisible) {
    if (!vScrollVisible) {
      this.comp.setStickyTopWidth("100%");
      this.comp.setStickyBottomWidth("100%");
    } else {
      const scrollbarWidth = this.gos.getScrollbarWidth();
      this.comp.setStickyTopWidth(`calc(100% - ${scrollbarWidth}px)`);
      this.comp.setStickyBottomWidth(`calc(100% - ${scrollbarWidth}px)`);
    }
  }
  onHeaderHeightChanged() {
    this.setStickyTopOffsetTop();
  }
  setStickyTopOffsetTop() {
    const headerCtrl = this.ctrlsService.get("gridHeaderCtrl");
    const headerHeight = headerCtrl.getHeaderHeight() + this.filterManager.getHeaderHeight();
    const pinnedTopHeight = this.pinnedRowModel.getPinnedTopTotalHeight();
    let height = 0;
    if (headerHeight > 0) {
      height += headerHeight;
    }
    if (pinnedTopHeight > 0) {
      height += pinnedTopHeight;
    }
    if (height > 0) {
      height += 1;
    }
    this.comp.setStickyTopTop(`${height}px`);
  }
  setStickyBottomOffsetBottom() {
    const pinnedBottomHeight = this.pinnedRowModel.getPinnedBottomTotalHeight();
    const hScrollShowing = this.scrollVisibleService.isHorizontalScrollShowing();
    const scrollbarWidth = hScrollShowing ? this.gos.getScrollbarWidth() || 0 : 0;
    const height = pinnedBottomHeight + scrollbarWidth;
    this.comp.setStickyBottomBottom(`${height}px`);
  }
  // method will call itself if no available width. this covers if the grid
  // isn't visible, but is just about to be visible.
  sizeColumnsToFit(params, nextTimeout) {
    const removeScrollWidth = this.isVerticalScrollShowing();
    const scrollWidthToRemove = removeScrollWidth ? this.gos.getScrollbarWidth() : 0;
    const bodyViewportWidth = getInnerWidth(this.eGridBody);
    const availableWidth = bodyViewportWidth - scrollWidthToRemove;
    if (availableWidth > 0) {
      this.columnModel.sizeColumnsToFit(availableWidth, "sizeColumnsToFit", false, params);
      return;
    }
    if (nextTimeout === void 0) {
      window.setTimeout(() => {
        this.sizeColumnsToFit(params, 100);
      }, 0);
    } else if (nextTimeout === 100) {
      window.setTimeout(() => {
        this.sizeColumnsToFit(params, 500);
      }, 100);
    } else if (nextTimeout === 500) {
      window.setTimeout(() => {
        this.sizeColumnsToFit(params, -1);
      }, 500);
    } else {
      console.warn("AG Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen?");
    }
  }
  // + rangeService
  addScrollEventListener(listener) {
    this.eBodyViewport.addEventListener("scroll", listener, { passive: true });
  }
  // + focusService
  removeScrollEventListener(listener) {
    this.eBodyViewport.removeEventListener("scroll", listener);
  }
};
__decorateClass([
  Autowired("animationFrameService")
], GridBodyCtrl.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("rowContainerHeightService")
], GridBodyCtrl.prototype, "rowContainerHeightService", 2);
__decorateClass([
  Autowired("ctrlsService")
], GridBodyCtrl.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("columnModel")
], GridBodyCtrl.prototype, "columnModel", 2);
__decorateClass([
  Autowired("scrollVisibleService")
], GridBodyCtrl.prototype, "scrollVisibleService", 2);
__decorateClass([
  Autowired("menuService")
], GridBodyCtrl.prototype, "menuService", 2);
__decorateClass([
  Autowired("headerNavigationService")
], GridBodyCtrl.prototype, "headerNavigationService", 2);
__decorateClass([
  Autowired("dragAndDropService")
], GridBodyCtrl.prototype, "dragAndDropService", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], GridBodyCtrl.prototype, "pinnedRowModel", 2);
__decorateClass([
  Autowired("rowRenderer")
], GridBodyCtrl.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("popupService")
], GridBodyCtrl.prototype, "popupService", 2);
__decorateClass([
  Autowired("mouseEventService")
], GridBodyCtrl.prototype, "mouseEventService", 2);
__decorateClass([
  Autowired("rowModel")
], GridBodyCtrl.prototype, "rowModel", 2);
__decorateClass([
  Autowired("filterManager")
], GridBodyCtrl.prototype, "filterManager", 2);

// community-modules/core/src/interfaces/IRangeService.ts
var SelectionHandleType = /* @__PURE__ */ ((SelectionHandleType2) => {
  SelectionHandleType2[SelectionHandleType2["FILL"] = 0] = "FILL";
  SelectionHandleType2[SelectionHandleType2["RANGE"] = 1] = "RANGE";
  return SelectionHandleType2;
})(SelectionHandleType || {});
var CellRangeType = /* @__PURE__ */ ((CellRangeType2) => {
  CellRangeType2[CellRangeType2["VALUE"] = 0] = "VALUE";
  CellRangeType2[CellRangeType2["DIMENSION"] = 1] = "DIMENSION";
  return CellRangeType2;
})(CellRangeType || {});

// community-modules/core/src/rendering/cell/cellRangeFeature.ts
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";
var CellRangeFeature = class {
  constructor(beans, ctrl) {
    this.beans = beans;
    this.rangeService = beans.rangeService;
    this.selectionHandleFactory = beans.selectionHandleFactory;
    this.cellCtrl = ctrl;
  }
  setComp(cellComp, eGui) {
    this.cellComp = cellComp;
    this.eGui = eGui;
    this.onRangeSelectionChanged();
  }
  onRangeSelectionChanged() {
    if (!this.cellComp) {
      return;
    }
    this.rangeCount = this.rangeService.getCellRangeCount(this.cellCtrl.getCellPosition());
    this.hasChartRange = this.getHasChartRange();
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_SELECTED, this.rangeCount !== 0);
    this.cellComp.addOrRemoveCssClass(`${CSS_CELL_RANGE_SELECTED}-1`, this.rangeCount === 1);
    this.cellComp.addOrRemoveCssClass(`${CSS_CELL_RANGE_SELECTED}-2`, this.rangeCount === 2);
    this.cellComp.addOrRemoveCssClass(`${CSS_CELL_RANGE_SELECTED}-3`, this.rangeCount === 3);
    this.cellComp.addOrRemoveCssClass(`${CSS_CELL_RANGE_SELECTED}-4`, this.rangeCount >= 4);
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_CHART, this.hasChartRange);
    setAriaSelected(this.eGui, this.rangeCount > 0 ? true : void 0);
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_SINGLE_CELL, this.isSingleCell());
    this.updateRangeBorders();
    this.refreshHandle();
  }
  updateRangeBorders() {
    const rangeBorders = this.getRangeBorders();
    const isSingleCell = this.isSingleCell();
    const isTop = !isSingleCell && rangeBorders.top;
    const isRight = !isSingleCell && rangeBorders.right;
    const isBottom = !isSingleCell && rangeBorders.bottom;
    const isLeft = !isSingleCell && rangeBorders.left;
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_TOP, isTop);
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_RIGHT, isRight);
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_BOTTOM, isBottom);
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_LEFT, isLeft);
  }
  isSingleCell() {
    const { rangeService } = this.beans;
    return this.rangeCount === 1 && !!rangeService && !rangeService.isMoreThanOneCell();
  }
  getHasChartRange() {
    const { rangeService } = this.beans;
    if (!this.rangeCount || !rangeService) {
      return false;
    }
    const cellRanges = rangeService.getCellRanges();
    return cellRanges.length > 0 && cellRanges.every((range) => includes([1 /* DIMENSION */, 0 /* VALUE */], range.type));
  }
  updateRangeBordersIfRangeCount() {
    if (this.rangeCount > 0) {
      this.updateRangeBorders();
      this.refreshHandle();
    }
  }
  getRangeBorders() {
    const isRtl = this.beans.gos.get("enableRtl");
    let top = false;
    let right = false;
    let bottom = false;
    let left = false;
    const thisCol = this.cellCtrl.getCellPosition().column;
    const columnModel = this.beans.columnModel;
    let leftCol;
    let rightCol;
    if (isRtl) {
      leftCol = columnModel.getDisplayedColAfter(thisCol);
      rightCol = columnModel.getDisplayedColBefore(thisCol);
    } else {
      leftCol = columnModel.getDisplayedColBefore(thisCol);
      rightCol = columnModel.getDisplayedColAfter(thisCol);
    }
    const ranges = this.rangeService.getCellRanges().filter(
      (range) => this.rangeService.isCellInSpecificRange(this.cellCtrl.getCellPosition(), range)
    );
    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 = this.rangeService.getRangeStartRow(range);
      const endRow = this.rangeService.getRangeEndRow(range);
      if (!top && this.beans.rowPositionUtils.sameRow(startRow, this.cellCtrl.getCellPosition())) {
        top = true;
      }
      if (!bottom && this.beans.rowPositionUtils.sameRow(endRow, this.cellCtrl.getCellPosition())) {
        bottom = true;
      }
      if (!left && leftCol && range.columns.indexOf(leftCol) < 0) {
        left = true;
      }
      if (!right && rightCol && range.columns.indexOf(rightCol) < 0) {
        right = true;
      }
    }
    return { top, right, bottom, left };
  }
  refreshHandle() {
    if (this.beans.context.isDestroyed()) {
      return;
    }
    const shouldHaveSelectionHandle = this.shouldHaveSelectionHandle();
    if (this.selectionHandle && !shouldHaveSelectionHandle) {
      this.selectionHandle = this.beans.context.destroyBean(this.selectionHandle);
    }
    if (shouldHaveSelectionHandle) {
      this.addSelectionHandle();
    }
    this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_HANDLE, !!this.selectionHandle);
  }
  shouldHaveSelectionHandle() {
    const gos = this.beans.gos;
    const cellRanges = this.rangeService.getCellRanges();
    const rangesLen = cellRanges.length;
    if (this.rangeCount < 1 || rangesLen < 1) {
      return false;
    }
    const cellRange = last(cellRanges);
    const cellPosition = this.cellCtrl.getCellPosition();
    const isFillHandleAvailable = gos.get("enableFillHandle") && !this.cellCtrl.isSuppressFillHandle();
    const isRangeHandleAvailable = gos.get("enableRangeHandle");
    let handleIsAvailable = rangesLen === 1 && !this.cellCtrl.isEditing() && (isFillHandleAvailable || isRangeHandleAvailable);
    if (this.hasChartRange) {
      const hasCategoryRange = cellRanges[0].type === 1 /* DIMENSION */;
      const isCategoryCell = hasCategoryRange && this.rangeService.isCellInSpecificRange(cellPosition, cellRanges[0]);
      this.cellComp.addOrRemoveCssClass(CSS_CELL_RANGE_CHART_CATEGORY, isCategoryCell);
      handleIsAvailable = cellRange.type === 0 /* VALUE */;
    }
    return handleIsAvailable && cellRange.endRow != null && this.rangeService.isContiguousRange(cellRange) && this.rangeService.isBottomRightCell(cellRange, cellPosition);
  }
  addSelectionHandle() {
    const gos = this.beans.gos;
    const cellRangeType = last(this.rangeService.getCellRanges()).type;
    const selectionHandleFill = gos.get("enableFillHandle") && missing(cellRangeType);
    const type = selectionHandleFill ? 0 /* FILL */ : 1 /* RANGE */;
    if (this.selectionHandle && this.selectionHandle.getType() !== type) {
      this.selectionHandle = this.beans.context.destroyBean(this.selectionHandle);
    }
    if (!this.selectionHandle) {
      this.selectionHandle = this.selectionHandleFactory.createSelectionHandle(type);
    }
    this.selectionHandle.refresh(this.cellCtrl);
  }
  destroy() {
    this.beans.context.destroyBean(this.selectionHandle);
  }
};

// community-modules/core/src/rendering/cell/cellPositionFeature.ts
var CellPositionFeature = class extends BeanStub {
  constructor(ctrl, beans) {
    super();
    this.cellCtrl = ctrl;
    this.beans = beans;
    this.column = ctrl.getColumn();
    this.rowNode = ctrl.getRowNode();
  }
  setupRowSpan() {
    this.rowSpan = this.column.getRowSpan(this.rowNode);
    this.addManagedListener(this.beans.eventService, Events.EVENT_NEW_COLUMNS_LOADED, () => this.onNewColumnsLoaded());
  }
  setComp(eGui) {
    this.eGui = eGui;
    this.setupColSpan();
    this.setupRowSpan();
    this.onLeftChanged();
    this.onWidthChanged();
    this.applyRowSpan();
  }
  onNewColumnsLoaded() {
    const rowSpan = this.column.getRowSpan(this.rowNode);
    if (this.rowSpan === rowSpan) {
      return;
    }
    this.rowSpan = rowSpan;
    this.applyRowSpan(true);
  }
  onDisplayColumnsChanged() {
    const colsSpanning = this.getColSpanningList();
    if (!areEqual(this.colsSpanning, colsSpanning)) {
      this.colsSpanning = colsSpanning;
      this.onWidthChanged();
      this.onLeftChanged();
    }
  }
  setupColSpan() {
    if (this.column.getColDef().colSpan == null) {
      return;
    }
    this.colsSpanning = this.getColSpanningList();
    this.addManagedListener(this.beans.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayColumnsChanged.bind(this));
    this.addManagedListener(this.beans.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, this.onWidthChanged.bind(this));
  }
  onWidthChanged() {
    if (!this.eGui) {
      return;
    }
    const width = this.getCellWidth();
    this.eGui.style.width = `${width}px`;
  }
  getCellWidth() {
    if (!this.colsSpanning) {
      return this.column.getActualWidth();
    }
    return this.colsSpanning.reduce((width, col) => width + col.getActualWidth(), 0);
  }
  getColSpanningList() {
    const colSpan = this.column.getColSpan(this.rowNode);
    const colsSpanning = [];
    if (colSpan === 1) {
      colsSpanning.push(this.column);
    } else {
      let pointer = this.column;
      const pinned = this.column.getPinned();
      for (let i = 0; pointer && i < colSpan; i++) {
        colsSpanning.push(pointer);
        pointer = this.beans.columnModel.getDisplayedColAfter(pointer);
        if (!pointer || missing(pointer)) {
          break;
        }
        if (pinned !== pointer.getPinned()) {
          break;
        }
      }
    }
    return colsSpanning;
  }
  onLeftChanged() {
    if (!this.eGui) {
      return;
    }
    const left = this.modifyLeftForPrintLayout(this.getCellLeft());
    this.eGui.style.left = left + "px";
  }
  getCellLeft() {
    let mostLeftCol;
    if (this.beans.gos.get("enableRtl") && this.colsSpanning) {
      mostLeftCol = last(this.colsSpanning);
    } else {
      mostLeftCol = this.column;
    }
    return mostLeftCol.getLeft();
  }
  modifyLeftForPrintLayout(leftPosition) {
    if (!this.cellCtrl.isPrintLayout() || this.column.getPinned() === "left") {
      return leftPosition;
    }
    const leftWidth = this.beans.columnModel.getDisplayedColumnsLeftWidth();
    if (this.column.getPinned() === "right") {
      const bodyWidth = this.beans.columnModel.getBodyContainerWidth();
      return leftWidth + bodyWidth + (leftPosition || 0);
    }
    return leftWidth + (leftPosition || 0);
  }
  applyRowSpan(force) {
    if (this.rowSpan === 1 && !force) {
      return;
    }
    const singleRowHeight = this.beans.gos.getRowHeightAsNumber();
    const totalRowHeight = singleRowHeight * this.rowSpan;
    this.eGui.style.height = `${totalRowHeight}px`;
    this.eGui.style.zIndex = "1";
  }
  // overriding to make public, as we don't dispose this bean via context
  destroy() {
    super.destroy();
  }
};

// community-modules/core/src/rendering/cell/cellCustomStyleFeature.ts
var CellCustomStyleFeature = class extends BeanStub {
  constructor(ctrl, beans) {
    super();
    this.staticClasses = [];
    this.cellCtrl = ctrl;
    this.beans = beans;
    this.column = ctrl.getColumn();
    this.rowNode = ctrl.getRowNode();
  }
  setComp(comp) {
    this.cellComp = comp;
    this.applyUserStyles();
    this.applyCellClassRules();
    this.applyClassesFromColDef();
  }
  applyCellClassRules() {
    const colDef = this.column.getColDef();
    const { cellClassRules } = colDef;
    const cellClassParams = this.beans.gos.addGridCommonParams({
      value: this.cellCtrl.getValue(),
      data: this.rowNode.data,
      node: this.rowNode,
      colDef,
      column: this.column,
      rowIndex: this.rowNode.rowIndex
    });
    this.beans.stylingService.processClassRules(
      // if current was previous, skip
      cellClassRules === this.cellClassRules ? void 0 : this.cellClassRules,
      cellClassRules,
      cellClassParams,
      (className) => this.cellComp.addOrRemoveCssClass(className, true),
      (className) => this.cellComp.addOrRemoveCssClass(className, false)
    );
    this.cellClassRules = cellClassRules;
  }
  applyUserStyles() {
    const colDef = this.column.getColDef();
    if (!colDef.cellStyle) {
      return;
    }
    let styles;
    if (typeof colDef.cellStyle === "function") {
      const cellStyleParams = this.beans.gos.addGridCommonParams({
        column: this.column,
        value: this.cellCtrl.getValue(),
        colDef,
        data: this.rowNode.data,
        node: this.rowNode,
        rowIndex: this.rowNode.rowIndex
      });
      const cellStyleFunc = colDef.cellStyle;
      styles = cellStyleFunc(cellStyleParams);
    } else {
      styles = colDef.cellStyle;
    }
    if (styles) {
      this.cellComp.setUserStyles(styles);
    }
  }
  applyClassesFromColDef() {
    const colDef = this.column.getColDef();
    const cellClassParams = this.beans.gos.addGridCommonParams({
      value: this.cellCtrl.getValue(),
      data: this.rowNode.data,
      node: this.rowNode,
      column: this.column,
      colDef,
      rowIndex: this.rowNode.rowIndex
    });
    if (this.staticClasses.length) {
      this.staticClasses.forEach((className) => this.cellComp.addOrRemoveCssClass(className, false));
    }
    this.staticClasses = this.beans.stylingService.getStaticCellClasses(colDef, cellClassParams);
    if (this.staticClasses.length) {
      this.staticClasses.forEach((className) => this.cellComp.addOrRemoveCssClass(className, true));
    }
  }
  // overriding to make public, as we don't dispose this bean via context
  destroy() {
    super.destroy();
  }
};

// community-modules/core/src/rendering/beans.ts
var Beans = class {
  postConstruct() {
    if (this.gos.isRowModelType("clientSide")) {
      this.clientSideRowModel = this.rowModel;
    }
    if (this.gos.isRowModelType("serverSide")) {
      this.serverSideRowModel = this.rowModel;
    }
  }
};
__decorateClass([
  Autowired("resizeObserverService")
], Beans.prototype, "resizeObserverService", 2);
__decorateClass([
  Autowired("paginationProxy")
], Beans.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("context")
], Beans.prototype, "context", 2);
__decorateClass([
  Autowired("gridOptionsService")
], Beans.prototype, "gos", 2);
__decorateClass([
  Autowired("environment")
], Beans.prototype, "environment", 2);
__decorateClass([
  Autowired("rowRenderer")
], Beans.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("valueService")
], Beans.prototype, "valueService", 2);
__decorateClass([
  Autowired("eventService")
], Beans.prototype, "eventService", 2);
__decorateClass([
  Autowired("columnModel")
], Beans.prototype, "columnModel", 2);
__decorateClass([
  Autowired("headerNavigationService")
], Beans.prototype, "headerNavigationService", 2);
__decorateClass([
  Autowired("navigationService")
], Beans.prototype, "navigationService", 2);
__decorateClass([
  Autowired("columnAnimationService")
], Beans.prototype, "columnAnimationService", 2);
__decorateClass([
  Autowired("focusService")
], Beans.prototype, "focusService", 2);
__decorateClass([
  Autowired("popupService")
], Beans.prototype, "popupService", 2);
__decorateClass([
  Autowired("stylingService")
], Beans.prototype, "stylingService", 2);
__decorateClass([
  Autowired("columnHoverService")
], Beans.prototype, "columnHoverService", 2);
__decorateClass([
  Autowired("userComponentFactory")
], Beans.prototype, "userComponentFactory", 2);
__decorateClass([
  Autowired("userComponentRegistry")
], Beans.prototype, "userComponentRegistry", 2);
__decorateClass([
  Autowired("animationFrameService")
], Beans.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("dragService")
], Beans.prototype, "dragService", 2);
__decorateClass([
  Autowired("dragAndDropService")
], Beans.prototype, "dragAndDropService", 2);
__decorateClass([
  Autowired("sortController")
], Beans.prototype, "sortController", 2);
__decorateClass([
  Autowired("filterManager")
], Beans.prototype, "filterManager", 2);
__decorateClass([
  Autowired("rowContainerHeightService")
], Beans.prototype, "rowContainerHeightService", 2);
__decorateClass([
  Autowired("frameworkOverrides")
], Beans.prototype, "frameworkOverrides", 2);
__decorateClass([
  Autowired("cellPositionUtils")
], Beans.prototype, "cellPositionUtils", 2);
__decorateClass([
  Autowired("rowPositionUtils")
], Beans.prototype, "rowPositionUtils", 2);
__decorateClass([
  Autowired("selectionService")
], Beans.prototype, "selectionService", 2);
__decorateClass([
  Autowired("rowCssClassCalculator")
], Beans.prototype, "rowCssClassCalculator", 2);
__decorateClass([
  Autowired("rowModel")
], Beans.prototype, "rowModel", 2);
__decorateClass([
  Autowired("ctrlsService")
], Beans.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("ctrlsFactory")
], Beans.prototype, "ctrlsFactory", 2);
__decorateClass([
  Autowired("agStackComponentsRegistry")
], Beans.prototype, "agStackComponentsRegistry", 2);
__decorateClass([
  Autowired("valueCache")
], Beans.prototype, "valueCache", 2);
__decorateClass([
  Autowired("rowNodeEventThrottle")
], Beans.prototype, "rowNodeEventThrottle", 2);
__decorateClass([
  Autowired("localeService")
], Beans.prototype, "localeService", 2);
__decorateClass([
  Autowired("syncService")
], Beans.prototype, "syncService", 2);
__decorateClass([
  Autowired("ariaAnnouncementService")
], Beans.prototype, "ariaAnnouncementService", 2);
__decorateClass([
  Optional("rangeService")
], Beans.prototype, "rangeService", 2);
__decorateClass([
  Optional("selectionHandleFactory")
], Beans.prototype, "selectionHandleFactory", 2);
__decorateClass([
  PostConstruct
], Beans.prototype, "postConstruct", 1);
Beans = __decorateClass([
  Bean("beans")
], Beans);

// community-modules/core/src/rendering/cell/cellMouseListenerFeature.ts
var CellMouseListenerFeature = class extends Beans {
  constructor(ctrl, beans, column) {
    super();
    this.cellCtrl = ctrl;
    this.beans = beans;
    this.column = column;
  }
  onMouseEvent(eventName, mouseEvent) {
    if (isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    switch (eventName) {
      case "click":
        this.onCellClicked(mouseEvent);
        break;
      case "mousedown":
      case "touchstart":
        this.onMouseDown(mouseEvent);
        break;
      case "dblclick":
        this.onCellDoubleClicked(mouseEvent);
        break;
      case "mouseout":
        this.onMouseOut(mouseEvent);
        break;
      case "mouseover":
        this.onMouseOver(mouseEvent);
        break;
    }
  }
  onCellClicked(mouseEvent) {
    if (this.isDoubleClickOnIPad()) {
      this.onCellDoubleClicked(mouseEvent);
      mouseEvent.preventDefault();
      return;
    }
    const { eventService, rangeService, gos } = this.beans;
    const isMultiKey = mouseEvent.ctrlKey || mouseEvent.metaKey;
    if (rangeService && isMultiKey) {
      if (rangeService.getCellRangeCount(this.cellCtrl.getCellPosition()) > 1) {
        rangeService.intersectLastRange(true);
      }
    }
    const cellClickedEvent = this.cellCtrl.createEvent(mouseEvent, Events.EVENT_CELL_CLICKED);
    eventService.dispatchEvent(cellClickedEvent);
    const colDef = this.column.getColDef();
    if (colDef.onCellClicked) {
      window.setTimeout(() => {
        this.beans.frameworkOverrides.wrapOutgoing(() => {
          colDef.onCellClicked(cellClickedEvent);
        });
      }, 0);
    }
    const editOnSingleClick = (gos.get("singleClickEdit") || colDef.singleClickEdit) && !gos.get("suppressClickEdit");
    if (editOnSingleClick && !(mouseEvent.shiftKey && (rangeService == null ? void 0 : rangeService.getCellRanges().length) != 0)) {
      this.cellCtrl.startRowOrCellEdit();
    }
  }
  // returns true if on iPad and this is second 'click' event in 200ms
  isDoubleClickOnIPad() {
    if (!isIOSUserAgent() || isEventSupported("dblclick")) {
      return false;
    }
    const nowMillis = (/* @__PURE__ */ new Date()).getTime();
    const res = nowMillis - this.lastIPadMouseClickEvent < 200;
    this.lastIPadMouseClickEvent = nowMillis;
    return res;
  }
  onCellDoubleClicked(mouseEvent) {
    const colDef = this.column.getColDef();
    const cellDoubleClickedEvent = this.cellCtrl.createEvent(mouseEvent, Events.EVENT_CELL_DOUBLE_CLICKED);
    this.beans.eventService.dispatchEvent(cellDoubleClickedEvent);
    if (typeof colDef.onCellDoubleClicked === "function") {
      window.setTimeout(() => {
        this.beans.frameworkOverrides.wrapOutgoing(() => {
          colDef.onCellDoubleClicked(cellDoubleClickedEvent);
        });
      }, 0);
    }
    const editOnDoubleClick = !this.beans.gos.get("singleClickEdit") && !this.beans.gos.get("suppressClickEdit");
    if (editOnDoubleClick) {
      this.cellCtrl.startRowOrCellEdit(null, mouseEvent);
    }
  }
  onMouseDown(mouseEvent) {
    const { ctrlKey, metaKey, shiftKey } = mouseEvent;
    const target = mouseEvent.target;
    const { cellCtrl, beans } = this;
    const { eventService, rangeService, focusService } = beans;
    if (this.isRightClickInExistingRange(mouseEvent)) {
      return;
    }
    const ranges = rangeService && rangeService.getCellRanges().length != 0;
    if (!shiftKey || !ranges) {
      const forceBrowserFocus = isBrowserSafari() && !cellCtrl.isEditing() && !isFocusableFormField(target);
      cellCtrl.focusCell(forceBrowserFocus);
    }
    if (shiftKey && ranges && !focusService.isCellFocused(cellCtrl.getCellPosition())) {
      mouseEvent.preventDefault();
      const focusedCellPosition = focusService.getFocusedCell();
      if (focusedCellPosition) {
        const { column, rowIndex, rowPinned } = focusedCellPosition;
        const focusedRowCtrl = beans.rowRenderer.getRowByPosition({ rowIndex, rowPinned });
        const focusedCellCtrl = focusedRowCtrl == null ? void 0 : focusedRowCtrl.getCellCtrl(column);
        if (focusedCellCtrl == null ? void 0 : focusedCellCtrl.isEditing()) {
          focusedCellCtrl.stopEditing();
        }
        focusService.setFocusedCell({
          column,
          rowIndex,
          rowPinned,
          forceBrowserFocus: true,
          preventScrollOnBrowserFocus: true
        });
      }
    }
    if (this.containsWidget(target)) {
      return;
    }
    if (rangeService) {
      const thisCell = this.cellCtrl.getCellPosition();
      if (shiftKey) {
        rangeService.extendLatestRangeToCell(thisCell);
      } else {
        const isMultiKey = ctrlKey || metaKey;
        rangeService.setRangeToCell(thisCell, isMultiKey);
      }
    }
    eventService.dispatchEvent(this.cellCtrl.createEvent(mouseEvent, Events.EVENT_CELL_MOUSE_DOWN));
  }
  isRightClickInExistingRange(mouseEvent) {
    const { rangeService } = this.beans;
    if (rangeService) {
      const cellInRange = rangeService.isCellInAnyRange(this.cellCtrl.getCellPosition());
      const isRightClick = mouseEvent.button === 2 || mouseEvent.ctrlKey && this.beans.gos.get("allowContextMenuWithControlKey");
      if (cellInRange && isRightClick) {
        return true;
      }
    }
    return false;
  }
  containsWidget(target) {
    return isElementChildOfClass(target, "ag-selection-checkbox", 3);
  }
  onMouseOut(mouseEvent) {
    if (this.mouseStayingInsideCell(mouseEvent)) {
      return;
    }
    const cellMouseOutEvent = this.cellCtrl.createEvent(mouseEvent, Events.EVENT_CELL_MOUSE_OUT);
    this.beans.eventService.dispatchEvent(cellMouseOutEvent);
    this.beans.columnHoverService.clearMouseOver();
  }
  onMouseOver(mouseEvent) {
    if (this.mouseStayingInsideCell(mouseEvent)) {
      return;
    }
    const cellMouseOverEvent = this.cellCtrl.createEvent(mouseEvent, Events.EVENT_CELL_MOUSE_OVER);
    this.beans.eventService.dispatchEvent(cellMouseOverEvent);
    this.beans.columnHoverService.setMouseOver([this.column]);
  }
  mouseStayingInsideCell(e) {
    if (!e.target || !e.relatedTarget) {
      return false;
    }
    const eGui = this.cellCtrl.getGui();
    const cellContainsTarget = eGui.contains(e.target);
    const cellContainsRelatedTarget = eGui.contains(e.relatedTarget);
    return cellContainsTarget && cellContainsRelatedTarget;
  }
  destroy() {
  }
};

// community-modules/core/src/rendering/cell/cellKeyboardListenerFeature.ts
var CellKeyboardListenerFeature = class extends BeanStub {
  constructor(ctrl, beans, column, rowNode, rowCtrl) {
    super();
    this.cellCtrl = ctrl;
    this.beans = beans;
    this.rowNode = rowNode;
    this.rowCtrl = rowCtrl;
  }
  setComp(eGui) {
    this.eGui = eGui;
  }
  onKeyDown(event) {
    const key = event.key;
    switch (key) {
      case KeyCode.ENTER:
        this.onEnterKeyDown(event);
        break;
      case KeyCode.F2:
        this.onF2KeyDown(event);
        break;
      case KeyCode.ESCAPE:
        this.onEscapeKeyDown(event);
        break;
      case KeyCode.TAB:
        this.onTabKeyDown(event);
        break;
      case KeyCode.BACKSPACE:
      case KeyCode.DELETE:
        this.onBackspaceOrDeleteKeyDown(key, event);
        break;
      case KeyCode.DOWN:
      case KeyCode.UP:
      case KeyCode.RIGHT:
      case KeyCode.LEFT:
        this.onNavigationKeyDown(event, key);
        break;
    }
  }
  onNavigationKeyDown(event, key) {
    if (this.cellCtrl.isEditing()) {
      return;
    }
    if (event.shiftKey && this.cellCtrl.isRangeSelectionEnabled()) {
      this.onShiftRangeSelect(event);
    } else {
      this.beans.navigationService.navigateToNextCell(event, key, this.cellCtrl.getCellPosition(), true);
    }
    event.preventDefault();
  }
  onShiftRangeSelect(event) {
    if (!this.beans.rangeService) {
      return;
    }
    const endCell = this.beans.rangeService.extendLatestRangeInDirection(event);
    if (endCell) {
      this.beans.navigationService.ensureCellVisible(endCell);
    }
  }
  onTabKeyDown(event) {
    this.beans.navigationService.onTabKeyDown(this.cellCtrl, event);
  }
  onBackspaceOrDeleteKeyDown(key, event) {
    var _a;
    const { cellCtrl, beans, rowNode } = this;
    const { gos, rangeService, eventService } = beans;
    if (cellCtrl.isEditing()) {
      return;
    }
    eventService.dispatchEvent({ type: Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_START });
    if (isDeleteKey(key, gos.get("enableCellEditingOnBackspace"))) {
      if (rangeService && gos.get("enableRangeSelection")) {
        rangeService.clearCellRangeCellValues({ dispatchWrapperEvents: true, wrapperEventSource: "deleteKey" });
      } else if (cellCtrl.isCellEditable()) {
        const column = cellCtrl.getColumn();
        const emptyValue = (_a = this.beans.valueService.parseValue(column, rowNode, "", rowNode.getValueFromValueService(column))) != null ? _a : null;
        rowNode.setDataValue(column, emptyValue, "cellClear");
      }
    } else {
      cellCtrl.startRowOrCellEdit(key, event);
    }
    eventService.dispatchEvent({ type: Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_END });
  }
  onEnterKeyDown(e) {
    if (this.cellCtrl.isEditing() || this.rowCtrl.isEditing()) {
      this.cellCtrl.stopEditingAndFocus(false, e.shiftKey);
    } else {
      if (this.beans.gos.get("enterNavigatesVertically")) {
        const key = e.shiftKey ? KeyCode.UP : KeyCode.DOWN;
        this.beans.navigationService.navigateToNextCell(null, key, this.cellCtrl.getCellPosition(), false);
      } else {
        this.cellCtrl.startRowOrCellEdit(KeyCode.ENTER, e);
        if (this.cellCtrl.isEditing()) {
          e.preventDefault();
        }
      }
    }
  }
  onF2KeyDown(event) {
    if (!this.cellCtrl.isEditing()) {
      this.cellCtrl.startRowOrCellEdit(KeyCode.F2, event);
    }
  }
  onEscapeKeyDown(event) {
    if (this.cellCtrl.isEditing()) {
      this.cellCtrl.stopRowOrCellEdit(true);
      this.cellCtrl.focusCell(true);
    }
  }
  processCharacter(event) {
    const eventTarget = event.target;
    const eventOnChildComponent = eventTarget !== this.eGui;
    if (eventOnChildComponent || this.cellCtrl.isEditing()) {
      return;
    }
    const key = event.key;
    if (key === " ") {
      this.onSpaceKeyDown(event);
    } else {
      this.cellCtrl.startRowOrCellEdit(key, event);
      event.preventDefault();
    }
  }
  onSpaceKeyDown(event) {
    const { gos } = this.beans;
    if (!this.cellCtrl.isEditing() && gos.isRowSelection()) {
      const currentSelection = this.rowNode.isSelected();
      const newSelection = !currentSelection;
      if (newSelection || !gos.get("suppressRowDeselection")) {
        const groupSelectsFiltered = this.beans.gos.get("groupSelectsFiltered");
        const updatedCount = this.rowNode.setSelectedParams({
          newValue: newSelection,
          rangeSelect: event.shiftKey,
          groupSelectsFiltered,
          event,
          source: "spaceKey"
        });
        if (currentSelection === void 0 && updatedCount === 0) {
          this.rowNode.setSelectedParams({
            newValue: false,
            rangeSelect: event.shiftKey,
            groupSelectsFiltered,
            event,
            source: "spaceKey"
          });
        }
      }
    }
    event.preventDefault();
  }
  destroy() {
    super.destroy();
  }
};

// community-modules/core/src/rendering/dndSourceComp.ts
var DndSourceComp = class extends Component {
  constructor(rowNode, column, eCell) {
    super(
      /* html */
      `<div class="ag-drag-handle ag-row-drag" draggable="true"></div>`
    );
    this.rowNode = rowNode;
    this.column = column;
    this.eCell = eCell;
  }
  postConstruct() {
    const eGui = this.getGui();
    eGui.appendChild(createIconNoSpan("rowDrag", this.gos, null));
    this.addGuiEventListener("mousedown", (e) => {
      e.stopPropagation();
    });
    this.addDragSource();
    this.checkVisibility();
  }
  addDragSource() {
    this.addGuiEventListener("dragstart", this.onDragStart.bind(this));
  }
  onDragStart(dragEvent) {
    const providedOnRowDrag = this.column.getColDef().dndSourceOnRowDrag;
    dragEvent.dataTransfer.setDragImage(this.eCell, 0, 0);
    const defaultOnRowDrag = () => {
      try {
        const jsonData = JSON.stringify(this.rowNode.data);
        dragEvent.dataTransfer.setData("application/json", jsonData);
        dragEvent.dataTransfer.setData("text/plain", jsonData);
      } catch (e) {
      }
    };
    if (providedOnRowDrag) {
      const params = this.gos.addGridCommonParams({
        rowNode: this.rowNode,
        dragEvent
      });
      providedOnRowDrag(params);
    } else {
      defaultOnRowDrag();
    }
  }
  checkVisibility() {
    const visible = this.column.isDndSource(this.rowNode);
    this.setDisplayed(visible);
  }
};
__decorateClass([
  PostConstruct
], DndSourceComp.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/cells/cssClassApplier.ts
var CSS_FIRST_COLUMN = "ag-column-first";
var CSS_LAST_COLUMN = "ag-column-last";
var CssClassApplier = class {
  static getHeaderClassesFromColDef(abstractColDef, gos, column, columnGroup) {
    if (missing(abstractColDef)) {
      return [];
    }
    return this.getColumnClassesFromCollDef(
      abstractColDef.headerClass,
      abstractColDef,
      gos,
      column,
      columnGroup
    );
  }
  static getToolPanelClassesFromColDef(abstractColDef, gos, column, columnGroup) {
    if (missing(abstractColDef)) {
      return [];
    }
    return this.getColumnClassesFromCollDef(
      abstractColDef.toolPanelClass,
      abstractColDef,
      gos,
      column,
      columnGroup
    );
  }
  static refreshFirstAndLastStyles(comp, column, columnModel) {
    comp.addOrRemoveCssClass(CSS_FIRST_COLUMN, columnModel.isColumnAtEdge(column, "first"));
    comp.addOrRemoveCssClass(CSS_LAST_COLUMN, columnModel.isColumnAtEdge(column, "last"));
  }
  static getClassParams(abstractColDef, gos, column, columnGroup) {
    return gos.addGridCommonParams({
      // bad naming, as colDef here can be a group or a column,
      // however most people won't appreciate the difference,
      // so keeping it as colDef to avoid confusion.
      colDef: abstractColDef,
      column,
      columnGroup
    });
  }
  static getColumnClassesFromCollDef(classesOrFunc, abstractColDef, gos, column, columnGroup) {
    if (missing(classesOrFunc)) {
      return [];
    }
    let classToUse;
    if (typeof classesOrFunc === "function") {
      const params = this.getClassParams(abstractColDef, gos, column, columnGroup);
      classToUse = classesOrFunc(params);
    } else {
      classToUse = classesOrFunc;
    }
    if (typeof classToUse === "string") {
      return [classToUse];
    }
    if (Array.isArray(classToUse)) {
      return [...classToUse];
    }
    return [];
  }
};

// community-modules/core/src/rendering/cell/cellCtrl.ts
var CSS_CELL = "ag-cell";
var CSS_AUTO_HEIGHT = "ag-cell-auto-height";
var CSS_NORMAL_HEIGHT = "ag-cell-normal-height";
var CSS_CELL_FOCUS = "ag-cell-focus";
var CSS_CELL_FIRST_RIGHT_PINNED = "ag-cell-first-right-pinned";
var CSS_CELL_LAST_LEFT_PINNED = "ag-cell-last-left-pinned";
var CSS_CELL_NOT_INLINE_EDITING = "ag-cell-not-inline-editing";
var CSS_COLUMN_HOVER = "ag-column-hover";
var CSS_CELL_WRAP_TEXT = "ag-cell-wrap-text";
var instanceIdSequence2 = 0;
var _CellCtrl = class _CellCtrl extends BeanStub {
  constructor(column, rowNode, beans, rowCtrl) {
    super();
    this.cellRangeFeature = null;
    this.cellPositionFeature = null;
    this.cellCustomStyleFeature = null;
    this.tooltipFeature = null;
    this.cellMouseListenerFeature = null;
    this.cellKeyboardListenerFeature = null;
    this.suppressRefreshCell = false;
    this.onCellCompAttachedFuncs = [];
    this.column = column;
    this.rowNode = rowNode;
    this.beans = beans;
    this.rowCtrl = rowCtrl;
    this.instanceId = column.getId() + "-" + instanceIdSequence2++;
    this.colIdSanitised = escapeString(this.column.getId());
    if (!beans.gos.get("suppressCellFocus")) {
      this.tabIndex = -1;
    }
    this.createCellPosition();
    this.addFeatures();
    this.updateAndFormatValue(false);
  }
  shouldRestoreFocus() {
    return this.beans.focusService.shouldRestoreFocus(this.cellPosition);
  }
  addFeatures() {
    this.cellPositionFeature = new CellPositionFeature(this, this.beans);
    this.addDestroyFunc(() => {
      var _a;
      (_a = this.cellPositionFeature) == null ? void 0 : _a.destroy();
      this.cellPositionFeature = null;
    });
    this.cellCustomStyleFeature = new CellCustomStyleFeature(this, this.beans);
    this.addDestroyFunc(() => {
      var _a;
      (_a = this.cellCustomStyleFeature) == null ? void 0 : _a.destroy();
      this.cellCustomStyleFeature = null;
    });
    this.cellMouseListenerFeature = new CellMouseListenerFeature(this, this.beans, this.column);
    this.addDestroyFunc(() => {
      var _a;
      (_a = this.cellMouseListenerFeature) == null ? void 0 : _a.destroy();
      this.cellMouseListenerFeature = null;
    });
    this.cellKeyboardListenerFeature = new CellKeyboardListenerFeature(this, this.beans, this.column, this.rowNode, this.rowCtrl);
    this.addDestroyFunc(() => {
      var _a;
      (_a = this.cellKeyboardListenerFeature) == null ? void 0 : _a.destroy();
      this.cellKeyboardListenerFeature = null;
    });
    if (this.column.isTooltipEnabled()) {
      this.enableTooltipFeature();
      this.addDestroyFunc(() => {
        this.disableTooltipFeature();
      });
    }
    const rangeSelectionEnabled = this.beans.rangeService && this.beans.gos.get("enableRangeSelection");
    if (rangeSelectionEnabled) {
      this.cellRangeFeature = new CellRangeFeature(this.beans, this);
      this.addDestroyFunc(() => {
        var _a;
        (_a = this.cellRangeFeature) == null ? void 0 : _a.destroy();
        this.cellRangeFeature = null;
      });
    }
  }
  enableTooltipFeature(value, shouldDisplayTooltip) {
    const getTooltipValue = () => {
      const colDef = this.column.getColDef();
      const data = this.rowNode.data;
      if (colDef.tooltipField && exists(data)) {
        return getValueUsingField(data, colDef.tooltipField, this.column.isTooltipFieldContainsDots());
      }
      const valueGetter = colDef.tooltipValueGetter;
      if (valueGetter) {
        return valueGetter(this.beans.gos.addGridCommonParams({
          location: "cell",
          colDef: this.column.getColDef(),
          column: this.column,
          rowIndex: this.cellPosition.rowIndex,
          node: this.rowNode,
          data: this.rowNode.data,
          value: this.value,
          valueFormatted: this.valueFormatted
        }));
      }
      return null;
    };
    const isTooltipWhenTruncated = this.beans.gos.get("tooltipShowMode") === "whenTruncated";
    if (!shouldDisplayTooltip && isTooltipWhenTruncated && !this.isCellRenderer()) {
      shouldDisplayTooltip = () => {
        const eGui = this.getGui();
        const textEl = eGui.children.length === 0 ? eGui : eGui.querySelector(".ag-cell-value");
        if (!textEl) {
          return true;
        }
        return textEl.scrollWidth > textEl.clientWidth;
      };
    }
    const tooltipCtrl = {
      getColumn: () => this.column,
      getColDef: () => this.column.getColDef(),
      getRowIndex: () => this.cellPosition.rowIndex,
      getRowNode: () => this.rowNode,
      getGui: () => this.getGui(),
      getLocation: () => "cell",
      getTooltipValue: value != null ? () => value : getTooltipValue,
      // this makes no sense, why is the cell formatted value passed to the tooltip???
      getValueFormatted: () => this.valueFormatted,
      shouldDisplayTooltip
    };
    this.tooltipFeature = new TooltipFeature(tooltipCtrl, this.beans);
  }
  disableTooltipFeature() {
    if (!this.tooltipFeature) {
      return;
    }
    this.tooltipFeature.destroy();
    this.tooltipFeature = null;
  }
  setComp(comp, eGui, eCellWrapper, printLayout, startEditing) {
    var _a, _b, _c, _d;
    this.cellComp = comp;
    this.eGui = eGui;
    this.printLayout = printLayout;
    this.addDomData();
    this.onCellFocused(this.focusEventToRestore);
    this.applyStaticCssClasses();
    this.setWrapText();
    this.onFirstRightPinnedChanged();
    this.onLastLeftPinnedChanged();
    this.onColumnHover();
    this.setupControlComps();
    this.setupAutoHeight(eCellWrapper);
    this.refreshFirstAndLastStyles();
    this.refreshAriaColIndex();
    (_a = this.cellPositionFeature) == null ? void 0 : _a.setComp(eGui);
    (_b = this.cellCustomStyleFeature) == null ? void 0 : _b.setComp(comp);
    (_c = this.tooltipFeature) == null ? void 0 : _c.refreshToolTip();
    (_d = this.cellKeyboardListenerFeature) == null ? void 0 : _d.setComp(this.eGui);
    if (this.cellRangeFeature) {
      this.cellRangeFeature.setComp(comp, eGui);
    }
    if (startEditing && this.isCellEditable()) {
      this.startEditing();
    } else {
      this.showValue();
    }
    if (this.onCellCompAttachedFuncs.length) {
      this.onCellCompAttachedFuncs.forEach((func) => func());
      this.onCellCompAttachedFuncs = [];
    }
  }
  setupAutoHeight(eCellWrapper) {
    this.isAutoHeight = this.column.isAutoHeight();
    if (!this.isAutoHeight || !eCellWrapper) {
      return;
    }
    const eParentCell = eCellWrapper.parentElement;
    const minRowHeight = this.beans.gos.getRowHeightForNode(this.rowNode).height;
    const measureHeight = (timesCalled) => {
      if (this.editing) {
        return;
      }
      if (!this.isAlive()) {
        return;
      }
      const { paddingTop, paddingBottom, borderBottomWidth, borderTopWidth } = getElementSize(eParentCell);
      const extraHeight = paddingTop + paddingBottom + borderBottomWidth + borderTopWidth;
      const wrapperHeight = eCellWrapper.offsetHeight;
      const autoHeight = wrapperHeight + extraHeight;
      if (timesCalled < 5) {
        const doc = this.beans.gos.getDocument();
        const notYetInDom = !doc || !doc.contains(eCellWrapper);
        const possiblyNoContentYet = autoHeight == 0;
        if (notYetInDom || possiblyNoContentYet) {
          window.setTimeout(() => measureHeight(timesCalled + 1), 0);
          return;
        }
      }
      const newHeight = Math.max(autoHeight, minRowHeight);
      this.rowNode.setRowAutoHeight(newHeight, this.column);
    };
    const listener = () => measureHeight(0);
    listener();
    const destroyResizeObserver = this.beans.resizeObserverService.observeResize(eCellWrapper, listener);
    this.addDestroyFunc(() => {
      destroyResizeObserver();
      this.rowNode.setRowAutoHeight(void 0, this.column);
    });
  }
  getCellAriaRole() {
    var _a;
    return (_a = this.column.getColDef().cellAriaRole) != null ? _a : "gridcell";
  }
  getInstanceId() {
    return this.instanceId;
  }
  getColumnIdSanitised() {
    return this.colIdSanitised;
  }
  getTabIndex() {
    return this.tabIndex;
  }
  isCellRenderer() {
    const colDef = this.column.getColDef();
    return colDef.cellRenderer != null || colDef.cellRendererSelector != null;
  }
  getValueToDisplay() {
    var _a;
    return (_a = this.valueFormatted) != null ? _a : this.value;
  }
  showValue(forceNewCellRendererInstance = false) {
    var _a;
    const valueToDisplay = this.getValueToDisplay();
    let compDetails;
    if (this.rowNode.stub) {
      const params = this.createCellRendererParams();
      compDetails = this.beans.userComponentFactory.getLoadingCellRendererDetails(this.column.getColDef(), params);
    } else if (this.isCellRenderer()) {
      const params = this.createCellRendererParams();
      compDetails = this.beans.userComponentFactory.getCellRendererDetails(this.column.getColDef(), params);
    }
    this.cellComp.setRenderDetails(compDetails, valueToDisplay, forceNewCellRendererInstance);
    (_a = this.cellRangeFeature) == null ? void 0 : _a.refreshHandle();
  }
  setupControlComps() {
    const colDef = this.column.getColDef();
    this.includeSelection = this.isIncludeControl(colDef.checkboxSelection);
    this.includeRowDrag = this.isIncludeControl(colDef.rowDrag);
    this.includeDndSource = this.isIncludeControl(colDef.dndSource);
    this.cellComp.setIncludeSelection(this.includeSelection);
    this.cellComp.setIncludeDndSource(this.includeDndSource);
    this.cellComp.setIncludeRowDrag(this.includeRowDrag);
  }
  isForceWrapper() {
    const forceWrapper = this.beans.gos.get("enableCellTextSelection") || this.column.isAutoHeight();
    return forceWrapper;
  }
  isIncludeControl(value) {
    const rowNodePinned = this.rowNode.rowPinned != null;
    const isFunc = typeof value === "function";
    const res = rowNodePinned ? false : isFunc || value === true;
    return res;
  }
  refreshShouldDestroy() {
    const colDef = this.column.getColDef();
    const selectionChanged = this.includeSelection != this.isIncludeControl(colDef.checkboxSelection);
    const rowDragChanged = this.includeRowDrag != this.isIncludeControl(colDef.rowDrag);
    const dndSourceChanged = this.includeDndSource != this.isIncludeControl(colDef.dndSource);
    const autoHeightChanged = this.isAutoHeight != this.column.isAutoHeight();
    return selectionChanged || rowDragChanged || dndSourceChanged || autoHeightChanged;
  }
  // either called internally if single cell editing, or called by rowRenderer if row editing
  startEditing(key = null, cellStartedEdit = false, event = null) {
    if (!this.isCellEditable() || this.editing) {
      return;
    }
    if (!this.cellComp) {
      this.onCellCompAttachedFuncs.push(() => {
        this.startEditing(key, cellStartedEdit, event);
      });
      return;
    }
    const editorParams = this.createCellEditorParams(key, cellStartedEdit);
    const colDef = this.column.getColDef();
    const compDetails = this.beans.userComponentFactory.getCellEditorDetails(colDef, editorParams);
    this.editCompDetails = compDetails;
    const popup = (compDetails == null ? void 0 : compDetails.popupFromSelector) != null ? compDetails.popupFromSelector : !!colDef.cellEditorPopup;
    const position = (compDetails == null ? void 0 : compDetails.popupPositionFromSelector) != null ? compDetails.popupPositionFromSelector : colDef.cellEditorPopupPosition;
    this.setEditing(true);
    this.cellComp.setEditDetails(compDetails, popup, position, this.beans.gos.get("reactiveCustomComponents"));
    const e = this.createEvent(event, Events.EVENT_CELL_EDITING_STARTED);
    this.beans.eventService.dispatchEvent(e);
  }
  setEditing(editing) {
    var _a;
    if (this.editing === editing) {
      return;
    }
    this.editing = editing;
    (_a = this.cellRangeFeature) == null ? void 0 : _a.refreshHandle();
  }
  // pass in 'true' to cancel the editing.
  stopRowOrCellEdit(cancel = false) {
    if (this.beans.gos.get("editType") === "fullRow") {
      this.rowCtrl.stopEditing(cancel);
    } else {
      this.stopEditing(cancel);
    }
  }
  onPopupEditorClosed() {
    if (!this.isEditing()) {
      return;
    }
    this.stopEditingAndFocus();
  }
  takeValueFromCellEditor(cancel) {
    const noValueResult = { newValueExists: false };
    if (cancel) {
      return noValueResult;
    }
    const cellEditor = this.cellComp.getCellEditor();
    if (!cellEditor) {
      return noValueResult;
    }
    const userWantsToCancel = cellEditor.isCancelAfterEnd && cellEditor.isCancelAfterEnd();
    if (userWantsToCancel) {
      return noValueResult;
    }
    const newValue = cellEditor.getValue();
    return {
      newValue,
      newValueExists: true
    };
  }
  /**
   * @returns `True` if the value changes, otherwise `False`.
   */
  saveNewValue(oldValue, newValue) {
    if (newValue === oldValue) {
      return false;
    }
    this.suppressRefreshCell = true;
    const valueChanged = this.rowNode.setDataValue(this.column, newValue, "edit");
    this.suppressRefreshCell = false;
    return valueChanged;
  }
  /**
   * Ends the Cell Editing
   * @param cancel `True` if the edit process is being canceled.
   * @returns `True` if the value of the `GridCell` has been updated, otherwise `False`.
   */
  stopEditing(cancel = false) {
    if (!this.editing) {
      return false;
    }
    const { newValue, newValueExists } = this.takeValueFromCellEditor(cancel);
    const oldValue = this.rowNode.getValueFromValueService(this.column);
    let valueChanged = false;
    if (newValueExists) {
      valueChanged = this.saveNewValue(oldValue, newValue);
    }
    this.setEditing(false);
    this.cellComp.setEditDetails();
    this.editCompDetails = void 0;
    this.updateAndFormatValue(false);
    this.refreshCell({ forceRefresh: true, suppressFlash: true });
    this.dispatchEditingStoppedEvent(oldValue, newValue, !cancel && !!valueChanged);
    return valueChanged;
  }
  dispatchEditingStoppedEvent(oldValue, newValue, valueChanged) {
    const editingStoppedEvent = __spreadProps(__spreadValues({}, this.createEvent(null, Events.EVENT_CELL_EDITING_STOPPED)), {
      oldValue,
      newValue,
      valueChanged
    });
    this.beans.eventService.dispatchEvent(editingStoppedEvent);
  }
  createCellEditorParams(key, cellStartedEdit) {
    return this.beans.gos.addGridCommonParams({
      value: this.rowNode.getValueFromValueService(this.column),
      eventKey: key,
      column: this.column,
      colDef: this.column.getColDef(),
      rowIndex: this.getCellPosition().rowIndex,
      node: this.rowNode,
      data: this.rowNode.data,
      cellStartedEdit,
      onKeyDown: this.onKeyDown.bind(this),
      stopEditing: this.stopEditingAndFocus.bind(this),
      eGridCell: this.getGui(),
      parseValue: this.parseValue.bind(this),
      formatValue: this.formatValue.bind(this)
    });
  }
  createCellRendererParams() {
    const res = this.beans.gos.addGridCommonParams({
      value: this.value,
      valueFormatted: this.valueFormatted,
      getValue: () => this.rowNode.getValueFromValueService(this.column),
      setValue: (value) => this.beans.valueService.setValue(this.rowNode, this.column, value),
      formatValue: this.formatValue.bind(this),
      data: this.rowNode.data,
      node: this.rowNode,
      pinned: this.column.getPinned(),
      colDef: this.column.getColDef(),
      column: this.column,
      rowIndex: this.getCellPosition().rowIndex,
      refreshCell: this.refreshCell.bind(this),
      eGridCell: this.getGui(),
      eParentOfValue: this.cellComp.getParentOfValue(),
      registerRowDragger: (rowDraggerElement, dragStartPixels, value, suppressVisibilityChange) => this.registerRowDragger(rowDraggerElement, dragStartPixels, suppressVisibilityChange),
      setTooltip: (value, shouldDisplayTooltip) => {
        var _a;
        if (this.tooltipFeature) {
          this.disableTooltipFeature();
        }
        this.enableTooltipFeature(value, shouldDisplayTooltip);
        (_a = this.tooltipFeature) == null ? void 0 : _a.refreshToolTip();
      }
    });
    return res;
  }
  parseValue(newValue) {
    return this.beans.valueService.parseValue(this.column, this.rowNode, newValue, this.getValue());
  }
  setFocusOutOnEditor() {
    if (!this.editing) {
      return;
    }
    const cellEditor = this.cellComp.getCellEditor();
    if (cellEditor && cellEditor.focusOut) {
      cellEditor.focusOut();
    }
  }
  setFocusInOnEditor() {
    if (!this.editing) {
      return;
    }
    const cellEditor = this.cellComp.getCellEditor();
    if (cellEditor && cellEditor.focusIn) {
      cellEditor.focusIn();
    } else {
      this.focusCell(true);
    }
  }
  onCellChanged(event) {
    const eventImpactsThisCell = event.column === this.column;
    if (eventImpactsThisCell) {
      this.refreshCell({});
    }
  }
  refreshOrDestroyCell(params) {
    var _a;
    if (this.refreshShouldDestroy()) {
      (_a = this.rowCtrl) == null ? void 0 : _a.recreateCell(this);
    } else {
      this.refreshCell(params);
    }
  }
  // + stop editing {forceRefresh: true, suppressFlash: true}
  // + event cellChanged {}
  // + cellRenderer.params.refresh() {} -> method passes 'as is' to the cellRenderer, so params could be anything
  // + rowCtrl: event dataChanged {suppressFlash: !update, newData: !update}
  // + rowCtrl: api refreshCells() {animate: true/false}
  // + rowRenderer: api softRefreshView() {}
  refreshCell(params) {
    var _a, _b, _c, _d;
    if (this.suppressRefreshCell || this.editing) {
      return;
    }
    const colDef = this.column.getColDef();
    const newData = params != null && !!params.newData;
    const suppressFlash = params != null && !!params.suppressFlash || !!colDef.suppressCellFlash;
    const noValueProvided = colDef.field == null && colDef.valueGetter == null && colDef.showRowGroup == null;
    const forceRefresh = params && params.forceRefresh || noValueProvided || newData;
    const isCellCompReady = !!this.cellComp;
    const valuesDifferent = this.updateAndFormatValue(isCellCompReady);
    const dataNeedsUpdating = forceRefresh || valuesDifferent;
    if (!isCellCompReady) {
      return;
    }
    if (dataNeedsUpdating) {
      this.showValue(newData);
      const processingFilterChange = this.beans.filterManager.isSuppressFlashingCellsBecauseFiltering();
      const flashCell = !suppressFlash && !processingFilterChange && (this.beans.gos.get("enableCellChangeFlash") || colDef.enableCellChangeFlash);
      if (flashCell) {
        this.flashCell();
      }
      (_a = this.cellCustomStyleFeature) == null ? void 0 : _a.applyUserStyles();
      (_b = this.cellCustomStyleFeature) == null ? void 0 : _b.applyClassesFromColDef();
    }
    (_c = this.tooltipFeature) == null ? void 0 : _c.refreshToolTip();
    (_d = this.cellCustomStyleFeature) == null ? void 0 : _d.applyCellClassRules();
  }
  // cell editors call this, when they want to stop for reasons other
  // than what we pick up on. eg selecting from a dropdown ends editing.
  stopEditingAndFocus(suppressNavigateAfterEdit = false, shiftKey = false) {
    this.stopRowOrCellEdit();
    this.focusCell(true);
    if (!suppressNavigateAfterEdit) {
      this.navigateAfterEdit(shiftKey);
    }
  }
  navigateAfterEdit(shiftKey) {
    const enterNavigatesVerticallyAfterEdit = this.beans.gos.get("enterNavigatesVerticallyAfterEdit");
    if (enterNavigatesVerticallyAfterEdit) {
      const key = shiftKey ? KeyCode.UP : KeyCode.DOWN;
      this.beans.navigationService.navigateToNextCell(null, key, this.getCellPosition(), false);
    }
  }
  // user can also call this via API
  flashCell(delays) {
    var _a, _b;
    const flashDuration = (_a = delays == null ? void 0 : delays.flashDuration) != null ? _a : delays == null ? void 0 : delays.flashDelay;
    const fadeDuration = (_b = delays == null ? void 0 : delays.fadeDuration) != null ? _b : delays == null ? void 0 : delays.fadeDelay;
    this.animateCell("data-changed", flashDuration, fadeDuration);
  }
  animateCell(cssName, flashDuration, fadeDuration) {
    if (!this.cellComp) {
      return;
    }
    const fullName = `ag-cell-${cssName}`;
    const animationFullName = `ag-cell-${cssName}-animation`;
    const { gos } = this.beans;
    if (!flashDuration) {
      flashDuration = gos.get("cellFlashDuration");
    }
    if (!exists(fadeDuration)) {
      fadeDuration = gos.get("cellFadeDuration");
    }
    this.cellComp.addOrRemoveCssClass(fullName, true);
    this.cellComp.addOrRemoveCssClass(animationFullName, false);
    this.beans.frameworkOverrides.wrapIncoming(() => {
      window.setTimeout(() => {
        if (!this.isAlive()) {
          return;
        }
        this.cellComp.addOrRemoveCssClass(fullName, false);
        this.cellComp.addOrRemoveCssClass(animationFullName, true);
        this.eGui.style.transition = `background-color ${fadeDuration}ms`;
        window.setTimeout(() => {
          if (!this.isAlive()) {
            return;
          }
          this.cellComp.addOrRemoveCssClass(animationFullName, false);
          this.eGui.style.transition = "";
        }, fadeDuration);
      }, flashDuration);
    });
  }
  onFlashCells(event) {
    if (!this.cellComp) {
      return;
    }
    const cellId = this.beans.cellPositionUtils.createId(this.getCellPosition());
    const shouldFlash = event.cells[cellId];
    if (shouldFlash) {
      this.animateCell("highlight");
    }
  }
  isCellEditable() {
    return this.column.isCellEditable(this.rowNode);
  }
  isSuppressFillHandle() {
    return this.column.isSuppressFillHandle();
  }
  formatValue(value) {
    var _a;
    return (_a = this.callValueFormatter(value)) != null ? _a : value;
  }
  callValueFormatter(value) {
    return this.beans.valueService.formatValue(this.column, this.rowNode, value);
  }
  updateAndFormatValue(compareValues) {
    const oldValue = this.value;
    const oldValueFormatted = this.valueFormatted;
    this.value = this.rowNode.getValueFromValueService(this.column);
    this.valueFormatted = this.callValueFormatter(this.value);
    if (compareValues) {
      return !this.valuesAreEqual(oldValue, this.value) || this.valueFormatted != oldValueFormatted;
    }
    return true;
  }
  valuesAreEqual(val1, val2) {
    const colDef = this.column.getColDef();
    return colDef.equals ? colDef.equals(val1, val2) : val1 === val2;
  }
  getComp() {
    return this.cellComp;
  }
  getValue() {
    return this.value;
  }
  addDomData() {
    const element = this.getGui();
    this.beans.gos.setDomData(element, _CellCtrl.DOM_DATA_KEY_CELL_CTRL, this);
    this.addDestroyFunc(() => this.beans.gos.setDomData(element, _CellCtrl.DOM_DATA_KEY_CELL_CTRL, null));
  }
  createEvent(domEvent, eventType) {
    const event = this.beans.gos.addGridCommonParams({
      type: eventType,
      node: this.rowNode,
      data: this.rowNode.data,
      value: this.value,
      column: this.column,
      colDef: this.column.getColDef(),
      rowPinned: this.rowNode.rowPinned,
      event: domEvent,
      rowIndex: this.rowNode.rowIndex
    });
    return event;
  }
  processCharacter(event) {
    var _a;
    (_a = this.cellKeyboardListenerFeature) == null ? void 0 : _a.processCharacter(event);
  }
  onKeyDown(event) {
    var _a;
    (_a = this.cellKeyboardListenerFeature) == null ? void 0 : _a.onKeyDown(event);
  }
  onMouseEvent(eventName, mouseEvent) {
    var _a;
    (_a = this.cellMouseListenerFeature) == null ? void 0 : _a.onMouseEvent(eventName, mouseEvent);
  }
  getGui() {
    return this.eGui;
  }
  getColSpanningList() {
    return this.cellPositionFeature.getColSpanningList();
  }
  onLeftChanged() {
    var _a;
    if (!this.cellComp) {
      return;
    }
    (_a = this.cellPositionFeature) == null ? void 0 : _a.onLeftChanged();
  }
  onDisplayedColumnsChanged() {
    if (!this.eGui) {
      return;
    }
    this.refreshAriaColIndex();
    this.refreshFirstAndLastStyles();
  }
  refreshFirstAndLastStyles() {
    const { cellComp, column, beans } = this;
    CssClassApplier.refreshFirstAndLastStyles(cellComp, column, beans.columnModel);
  }
  refreshAriaColIndex() {
    const colIdx = this.beans.columnModel.getAriaColumnIndex(this.column);
    setAriaColIndex(this.getGui(), colIdx);
  }
  isSuppressNavigable() {
    return this.column.isSuppressNavigable(this.rowNode);
  }
  onWidthChanged() {
    var _a;
    return (_a = this.cellPositionFeature) == null ? void 0 : _a.onWidthChanged();
  }
  getColumn() {
    return this.column;
  }
  getRowNode() {
    return this.rowNode;
  }
  isPrintLayout() {
    return this.printLayout;
  }
  getCellPosition() {
    return this.cellPosition;
  }
  isEditing() {
    return this.editing;
  }
  // called by rowRenderer when user navigates via tab key
  startRowOrCellEdit(key, event = null) {
    if (!this.cellComp) {
      this.onCellCompAttachedFuncs.push(() => {
        this.startRowOrCellEdit(key, event);
      });
      return;
    }
    if (this.beans.gos.get("editType") === "fullRow") {
      this.rowCtrl.startRowEditing(key, this);
    } else {
      this.startEditing(key, true, event);
    }
  }
  getRowCtrl() {
    return this.rowCtrl;
  }
  getRowPosition() {
    return {
      rowIndex: this.cellPosition.rowIndex,
      rowPinned: this.cellPosition.rowPinned
    };
  }
  updateRangeBordersIfRangeCount() {
    if (!this.cellComp) {
      return;
    }
    if (this.cellRangeFeature) {
      this.cellRangeFeature.updateRangeBordersIfRangeCount();
    }
  }
  onRangeSelectionChanged() {
    if (!this.cellComp) {
      return;
    }
    if (this.cellRangeFeature) {
      this.cellRangeFeature.onRangeSelectionChanged();
    }
  }
  isRangeSelectionEnabled() {
    return this.cellRangeFeature != null;
  }
  focusCell(forceBrowserFocus = false) {
    this.beans.focusService.setFocusedCell({
      rowIndex: this.getCellPosition().rowIndex,
      column: this.column,
      rowPinned: this.rowNode.rowPinned,
      forceBrowserFocus
    });
  }
  onRowIndexChanged() {
    this.createCellPosition();
    this.onCellFocused();
    if (this.cellRangeFeature) {
      this.cellRangeFeature.onRangeSelectionChanged();
    }
  }
  onFirstRightPinnedChanged() {
    if (!this.cellComp) {
      return;
    }
    const firstRightPinned = this.column.isFirstRightPinned();
    this.cellComp.addOrRemoveCssClass(CSS_CELL_FIRST_RIGHT_PINNED, firstRightPinned);
  }
  onLastLeftPinnedChanged() {
    if (!this.cellComp) {
      return;
    }
    const lastLeftPinned = this.column.isLastLeftPinned();
    this.cellComp.addOrRemoveCssClass(CSS_CELL_LAST_LEFT_PINNED, lastLeftPinned);
  }
  onCellFocused(event) {
    if (this.beans.gos.get("suppressCellFocus")) {
      return;
    }
    const cellFocused = this.beans.focusService.isCellFocused(this.cellPosition);
    if (!this.cellComp) {
      if (cellFocused && (event == null ? void 0 : event.forceBrowserFocus)) {
        this.focusEventToRestore = event;
      }
      return;
    }
    this.focusEventToRestore = void 0;
    this.cellComp.addOrRemoveCssClass(CSS_CELL_FOCUS, cellFocused);
    if (cellFocused && event && event.forceBrowserFocus) {
      const focusEl = this.cellComp.getFocusableElement();
      focusEl.focus({ preventScroll: !!event.preventScrollOnBrowserFocus });
    }
    const fullRowEdit = this.beans.gos.get("editType") === "fullRow";
    if (!cellFocused && !fullRowEdit && this.editing) {
      this.stopRowOrCellEdit();
    }
    if (cellFocused) {
      this.rowCtrl.announceDescription();
    }
  }
  createCellPosition() {
    this.cellPosition = {
      rowIndex: this.rowNode.rowIndex,
      rowPinned: makeNull(this.rowNode.rowPinned),
      column: this.column
    };
  }
  // CSS Classes that only get applied once, they never change
  applyStaticCssClasses() {
    this.cellComp.addOrRemoveCssClass(CSS_CELL, true);
    this.cellComp.addOrRemoveCssClass(CSS_CELL_NOT_INLINE_EDITING, true);
    const autoHeight = this.column.isAutoHeight() == true;
    this.cellComp.addOrRemoveCssClass(CSS_AUTO_HEIGHT, autoHeight);
    this.cellComp.addOrRemoveCssClass(CSS_NORMAL_HEIGHT, !autoHeight);
  }
  onColumnHover() {
    if (!this.cellComp) {
      return;
    }
    if (!this.beans.gos.get("columnHoverHighlight")) {
      return;
    }
    const isHovered = this.beans.columnHoverService.isHovered(this.column);
    this.cellComp.addOrRemoveCssClass(CSS_COLUMN_HOVER, isHovered);
  }
  onColDefChanged() {
    if (!this.cellComp) {
      return;
    }
    const isTooltipEnabled = this.column.isTooltipEnabled();
    if (isTooltipEnabled) {
      this.disableTooltipFeature();
      this.enableTooltipFeature();
    } else {
      this.disableTooltipFeature();
    }
    this.setWrapText();
    if (!this.editing) {
      this.refreshOrDestroyCell({ forceRefresh: true, suppressFlash: true });
    } else {
      const cellEditor = this.getCellEditor();
      if (cellEditor == null ? void 0 : cellEditor.refresh) {
        const { eventKey, cellStartedEdit } = this.editCompDetails.params;
        const editorParams = this.createCellEditorParams(eventKey, cellStartedEdit);
        const colDef = this.column.getColDef();
        const compDetails = this.beans.userComponentFactory.getCellEditorDetails(colDef, editorParams);
        cellEditor.refresh(compDetails.params);
      }
    }
  }
  setWrapText() {
    const value = this.column.getColDef().wrapText == true;
    this.cellComp.addOrRemoveCssClass(CSS_CELL_WRAP_TEXT, value);
  }
  dispatchCellContextMenuEvent(event) {
    const colDef = this.column.getColDef();
    const cellContextMenuEvent = this.createEvent(event, Events.EVENT_CELL_CONTEXT_MENU);
    this.beans.eventService.dispatchEvent(cellContextMenuEvent);
    if (colDef.onCellContextMenu) {
      window.setTimeout(() => {
        this.beans.frameworkOverrides.wrapOutgoing(() => {
          colDef.onCellContextMenu(cellContextMenuEvent);
        });
      }, 0);
    }
  }
  getCellRenderer() {
    return this.cellComp ? this.cellComp.getCellRenderer() : null;
  }
  getCellEditor() {
    return this.cellComp ? this.cellComp.getCellEditor() : null;
  }
  destroy() {
    this.onCellCompAttachedFuncs = [];
    super.destroy();
  }
  createSelectionCheckbox() {
    const cbSelectionComponent = new CheckboxSelectionComponent();
    this.beans.context.createBean(cbSelectionComponent);
    cbSelectionComponent.init({ rowNode: this.rowNode, column: this.column });
    return cbSelectionComponent;
  }
  createDndSource() {
    const dndSourceComp = new DndSourceComp(this.rowNode, this.column, this.eGui);
    this.beans.context.createBean(dndSourceComp);
    return dndSourceComp;
  }
  registerRowDragger(customElement, dragStartPixels, suppressVisibilityChange) {
    if (this.customRowDragComp) {
      this.customRowDragComp.setDragElement(customElement, dragStartPixels);
      return;
    }
    const newComp = this.createRowDragComp(customElement, dragStartPixels, suppressVisibilityChange);
    if (newComp) {
      this.customRowDragComp = newComp;
      this.addDestroyFunc(() => {
        this.beans.context.destroyBean(newComp);
        this.customRowDragComp = null;
      });
    }
  }
  createRowDragComp(customElement, dragStartPixels, suppressVisibilityChange) {
    const pagination = this.beans.gos.get("pagination");
    const rowDragManaged = this.beans.gos.get("rowDragManaged");
    const clientSideRowModelActive = this.beans.gos.isRowModelType("clientSide");
    if (rowDragManaged) {
      if (!clientSideRowModelActive) {
        warnOnce("managed row dragging is only allowed in the Client Side Row Model");
        return;
      }
      if (pagination) {
        warnOnce("managed row dragging is not possible when doing pagination");
        return;
      }
    }
    const rowDragComp = new RowDragComp(() => this.value, this.rowNode, this.column, customElement, dragStartPixels, suppressVisibilityChange);
    this.beans.context.createBean(rowDragComp);
    return rowDragComp;
  }
};
_CellCtrl.DOM_DATA_KEY_CELL_CTRL = "cellCtrl";
var CellCtrl = _CellCtrl;

// community-modules/core/src/rendering/row/rowCtrl.ts
var instanceIdSequence3 = 0;
var _RowCtrl = class _RowCtrl extends BeanStub {
  constructor(rowNode, beans, animateIn, useAnimationFrameForCreate, printLayout) {
    super();
    this.allRowGuis = [];
    this.active = true;
    this.centerCellCtrls = { list: [], map: {} };
    this.leftCellCtrls = { list: [], map: {} };
    this.rightCellCtrls = { list: [], map: {} };
    this.slideInAnimation = {
      left: false,
      center: false,
      right: false,
      fullWidth: false
    };
    this.fadeInAnimation = {
      left: false,
      center: false,
      right: false,
      fullWidth: false
    };
    this.rowDragComps = [];
    this.lastMouseDownOnDragger = false;
    this.emptyStyle = {};
    this.updateColumnListsPending = false;
    this.rowId = null;
    this.businessKeySanitised = null;
    this.beans = beans;
    this.gos = beans.gos;
    this.rowNode = rowNode;
    this.paginationPage = beans.paginationProxy.getCurrentPage();
    this.useAnimationFrameForCreate = useAnimationFrameForCreate;
    this.printLayout = printLayout;
    this.suppressRowTransform = this.gos.get("suppressRowTransform");
    this.instanceId = rowNode.id + "-" + instanceIdSequence3++;
    this.rowId = escapeString(rowNode.id);
    this.initRowBusinessKey();
    this.rowFocused = beans.focusService.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned);
    this.rowLevel = beans.rowCssClassCalculator.calculateRowLevel(this.rowNode);
    this.setRowType();
    this.setAnimateFlags(animateIn);
    this.rowStyles = this.processStylesFromGridOptions();
    if (this.isFullWidth() && !this.gos.get("suppressCellFocus")) {
      this.tabIndex = -1;
    }
    this.addListeners();
  }
  initRowBusinessKey() {
    this.businessKeyForNodeFunc = this.gos.get("getBusinessKeyForNode");
    this.updateRowBusinessKey();
  }
  updateRowBusinessKey() {
    if (typeof this.businessKeyForNodeFunc !== "function") {
      return;
    }
    const businessKey = this.businessKeyForNodeFunc(this.rowNode);
    this.businessKeySanitised = escapeString(businessKey);
  }
  getRowId() {
    return this.rowId;
  }
  getRowStyles() {
    return this.rowStyles;
  }
  getTabIndex() {
    return this.tabIndex;
  }
  isSticky() {
    return this.rowNode.sticky;
  }
  getInstanceId() {
    return this.instanceId;
  }
  setComp(rowComp, element, containerType) {
    const gui = { rowComp, element, containerType };
    this.allRowGuis.push(gui);
    if (containerType === "left" /* LEFT */) {
      this.leftGui = gui;
    } else if (containerType === "right" /* RIGHT */) {
      this.rightGui = gui;
    } else if (containerType === "fullWidth" /* FULL_WIDTH */) {
      this.fullWidthGui = gui;
    } else {
      this.centerGui = gui;
    }
    this.initialiseRowComp(gui);
    if (this.rowType !== "FullWidthLoading" && !this.rowNode.rowPinned) {
      this.beans.rowRenderer.dispatchFirstDataRenderedEvent();
    }
  }
  unsetComp(containerType) {
    this.allRowGuis = this.allRowGuis.filter((rowGui) => rowGui.containerType !== containerType);
    switch (containerType) {
      case "left" /* LEFT */:
        this.leftGui = void 0;
        break;
      case "right" /* RIGHT */:
        this.rightGui = void 0;
        break;
      case "fullWidth" /* FULL_WIDTH */:
        this.fullWidthGui = void 0;
        break;
      case "center" /* CENTER */:
        this.centerGui = void 0;
        break;
      default:
    }
  }
  isCacheable() {
    return this.rowType === "FullWidthDetail" /* FullWidthDetail */ && this.gos.get("keepDetailRows");
  }
  setCached(cached) {
    const displayValue = cached ? "none" : "";
    this.allRowGuis.forEach((rg) => rg.element.style.display = displayValue);
  }
  initialiseRowComp(gui) {
    const gos = this.gos;
    this.listenOnDomOrder(gui);
    if (this.beans.columnModel.wasAutoRowHeightEverActive()) {
      this.rowNode.checkAutoHeights();
    }
    this.onRowHeightChanged(gui);
    this.updateRowIndexes(gui);
    this.setFocusedClasses(gui);
    this.setStylesFromGridOptions(false, gui);
    if (gos.isRowSelection() && this.rowNode.selectable) {
      this.onRowSelected(gui);
    }
    this.updateColumnLists(!this.useAnimationFrameForCreate);
    const comp = gui.rowComp;
    const initialRowClasses = this.getInitialRowClasses(gui.containerType);
    initialRowClasses.forEach((name) => comp.addOrRemoveCssClass(name, true));
    this.executeSlideAndFadeAnimations(gui);
    if (this.rowNode.group) {
      setAriaExpanded(gui.element, this.rowNode.expanded == true);
    }
    this.setRowCompRowId(comp);
    this.setRowCompRowBusinessKey(comp);
    gos.setDomData(gui.element, _RowCtrl.DOM_DATA_KEY_ROW_CTRL, this);
    this.addDestroyFunc(
      () => gos.setDomData(gui.element, _RowCtrl.DOM_DATA_KEY_ROW_CTRL, null)
    );
    if (this.useAnimationFrameForCreate) {
      this.beans.animationFrameService.createTask(
        this.addHoverFunctionality.bind(this, gui.element),
        this.rowNode.rowIndex,
        "createTasksP2"
      );
    } else {
      this.addHoverFunctionality(gui.element);
    }
    if (this.isFullWidth()) {
      this.setupFullWidth(gui);
    }
    if (gos.get("rowDragEntireRow")) {
      this.addRowDraggerToRow(gui);
    }
    if (this.useAnimationFrameForCreate) {
      this.beans.animationFrameService.addDestroyTask(() => {
        if (!this.isAlive()) {
          return;
        }
        gui.rowComp.addOrRemoveCssClass("ag-after-created", true);
      });
    }
    this.executeProcessRowPostCreateFunc();
  }
  setRowCompRowBusinessKey(comp) {
    if (this.businessKeySanitised == null) {
      return;
    }
    comp.setRowBusinessKey(this.businessKeySanitised);
  }
  getBusinessKey() {
    return this.businessKeySanitised;
  }
  setRowCompRowId(comp) {
    this.rowId = escapeString(this.rowNode.id);
    if (this.rowId == null) {
      return;
    }
    comp.setRowId(this.rowId);
  }
  executeSlideAndFadeAnimations(gui) {
    const { containerType } = gui;
    const shouldSlide = this.slideInAnimation[containerType];
    if (shouldSlide) {
      executeNextVMTurn(() => {
        this.onTopChanged();
      });
      this.slideInAnimation[containerType] = false;
    }
    const shouldFade = this.fadeInAnimation[containerType];
    if (shouldFade) {
      executeNextVMTurn(() => {
        gui.rowComp.addOrRemoveCssClass("ag-opacity-zero", false);
      });
      this.fadeInAnimation[containerType] = false;
    }
  }
  addRowDraggerToRow(gui) {
    if (this.gos.get("enableRangeSelection")) {
      warnOnce("Setting `rowDragEntireRow: true` in the gridOptions doesn't work with `enableRangeSelection: true`");
      return;
    }
    const translate = this.beans.localeService.getLocaleTextFunc();
    const rowDragComp = new RowDragComp(
      () => `1 ${translate("rowDragRow", "row")}`,
      this.rowNode,
      void 0,
      gui.element,
      void 0,
      true
    );
    const rowDragBean = this.createBean(rowDragComp, this.beans.context);
    this.rowDragComps.push(rowDragBean);
  }
  setupFullWidth(gui) {
    const pinned = this.getPinnedForContainer(gui.containerType);
    if (this.rowType == "FullWidthDetail" /* FullWidthDetail */) {
      if (!ModuleRegistry.__assertRegistered("@ag-grid-enterprise/master-detail" /* MasterDetailModule */, "cell renderer 'agDetailCellRenderer' (for master detail)", this.beans.context.getGridId())) {
        return;
      }
    }
    const compDetails = this.createFullWidthCompDetails(gui.element, pinned);
    gui.rowComp.showFullWidth(compDetails);
  }
  isPrintLayout() {
    return this.printLayout;
  }
  getFullWidthCellRenderers() {
    var _a, _b;
    if (this.gos.get("embedFullWidthRows")) {
      return this.allRowGuis.map((gui) => {
        var _a2;
        return (_a2 = gui == null ? void 0 : gui.rowComp) == null ? void 0 : _a2.getFullWidthCellRenderer();
      });
    }
    return [(_b = (_a = this.fullWidthGui) == null ? void 0 : _a.rowComp) == null ? void 0 : _b.getFullWidthCellRenderer()];
  }
  // use by autoWidthCalculator, as it clones the elements
  getCellElement(column) {
    const cellCtrl = this.getCellCtrl(column);
    return cellCtrl ? cellCtrl.getGui() : null;
  }
  executeProcessRowPostCreateFunc() {
    const func = this.gos.getCallback("processRowPostCreate");
    if (!func || !this.areAllContainersReady()) {
      return;
    }
    const params = {
      // areAllContainersReady asserts that centerGui is not null
      eRow: this.centerGui.element,
      ePinnedLeftRow: this.leftGui ? this.leftGui.element : void 0,
      ePinnedRightRow: this.rightGui ? this.rightGui.element : void 0,
      node: this.rowNode,
      rowIndex: this.rowNode.rowIndex,
      addRenderedRowListener: this.addEventListener.bind(this)
    };
    func(params);
  }
  areAllContainersReady() {
    const isLeftReady = !!this.leftGui || !this.beans.columnModel.isPinningLeft();
    const isCenterReady = !!this.centerGui;
    const isRightReady = !!this.rightGui || !this.beans.columnModel.isPinningRight();
    return isLeftReady && isCenterReady && isRightReady;
  }
  setRowType() {
    const isStub = this.rowNode.stub && !this.gos.get("suppressServerSideFullWidthLoadingRow");
    const isFullWidthCell = this.rowNode.isFullWidthCell();
    const isDetailCell = this.gos.get("masterDetail") && this.rowNode.detail;
    const pivotMode = this.beans.columnModel.isPivotMode();
    const isGroupRow = !!this.rowNode.group && !this.rowNode.footer;
    const isFullWidthGroup = isGroupRow && this.gos.isGroupUseEntireRow(pivotMode);
    if (isStub) {
      this.rowType = "FullWidthLoading" /* FullWidthLoading */;
    } else if (isDetailCell) {
      this.rowType = "FullWidthDetail" /* FullWidthDetail */;
    } else if (isFullWidthCell) {
      this.rowType = "FullWidth" /* FullWidth */;
    } else if (isFullWidthGroup) {
      this.rowType = "FullWidthGroup" /* FullWidthGroup */;
    } else {
      this.rowType = "Normal" /* Normal */;
    }
  }
  updateColumnLists(suppressAnimationFrame = false, useFlushSync = false) {
    if (this.isFullWidth()) {
      return;
    }
    const noAnimation = suppressAnimationFrame || this.gos.get("suppressAnimationFrame") || this.printLayout;
    if (noAnimation) {
      this.updateColumnListsImpl(useFlushSync);
      return;
    }
    if (this.updateColumnListsPending) {
      return;
    }
    this.beans.animationFrameService.createTask(
      () => {
        if (!this.active) {
          return;
        }
        this.updateColumnListsImpl(true);
      },
      this.rowNode.rowIndex,
      "createTasksP1"
    );
    this.updateColumnListsPending = true;
  }
  createCellCtrls(prev, cols, pinned = null) {
    const res = {
      list: [],
      map: {}
    };
    const addCell = (colInstanceId, cellCtrl) => {
      res.list.push(cellCtrl);
      res.map[colInstanceId] = cellCtrl;
    };
    cols.forEach((col) => {
      const colInstanceId = col.getInstanceId();
      let cellCtrl = prev.map[colInstanceId];
      if (!cellCtrl) {
        cellCtrl = new CellCtrl(col, this.rowNode, this.beans, this);
      }
      addCell(colInstanceId, cellCtrl);
    });
    prev.list.forEach((prevCellCtrl) => {
      const cellInResult = res.map[prevCellCtrl.getColumn().getInstanceId()] != null;
      if (cellInResult) {
        return;
      }
      const keepCell = !this.isCellEligibleToBeRemoved(prevCellCtrl, pinned);
      if (keepCell) {
        addCell(prevCellCtrl.getColumn().getInstanceId(), prevCellCtrl);
        return;
      }
      prevCellCtrl.destroy();
    });
    return res;
  }
  updateColumnListsImpl(useFlushSync) {
    this.updateColumnListsPending = false;
    this.createAllCellCtrls();
    this.setCellCtrls(useFlushSync);
  }
  setCellCtrls(useFlushSync) {
    this.allRowGuis.forEach((item) => {
      const cellControls = this.getCellCtrlsForContainer(item.containerType);
      item.rowComp.setCellCtrls(cellControls, useFlushSync);
    });
  }
  getCellCtrlsForContainer(containerType) {
    switch (containerType) {
      case "left" /* LEFT */:
        return this.leftCellCtrls.list;
      case "right" /* RIGHT */:
        return this.rightCellCtrls.list;
      case "fullWidth" /* FULL_WIDTH */:
        return [];
      case "center" /* CENTER */:
        return this.centerCellCtrls.list;
      default:
        const exhaustiveCheck = containerType;
        throw new Error(`Unhandled case: ${exhaustiveCheck}`);
    }
  }
  createAllCellCtrls() {
    const columnModel = this.beans.columnModel;
    if (this.printLayout) {
      this.centerCellCtrls = this.createCellCtrls(this.centerCellCtrls, columnModel.getAllDisplayedColumns());
      this.leftCellCtrls = { list: [], map: {} };
      this.rightCellCtrls = { list: [], map: {} };
    } else {
      const centerCols = columnModel.getViewportCenterColumnsForRow(this.rowNode);
      this.centerCellCtrls = this.createCellCtrls(this.centerCellCtrls, centerCols);
      const leftCols = columnModel.getDisplayedLeftColumnsForRow(this.rowNode);
      this.leftCellCtrls = this.createCellCtrls(this.leftCellCtrls, leftCols, "left");
      const rightCols = columnModel.getDisplayedRightColumnsForRow(this.rowNode);
      this.rightCellCtrls = this.createCellCtrls(this.rightCellCtrls, rightCols, "right");
    }
  }
  isCellEligibleToBeRemoved(cellCtrl, nextContainerPinned) {
    const REMOVE_CELL = true;
    const KEEP_CELL = false;
    const column = cellCtrl.getColumn();
    if (column.getPinned() != nextContainerPinned) {
      return REMOVE_CELL;
    }
    const editing = cellCtrl.isEditing();
    const focused = this.beans.focusService.isCellFocused(cellCtrl.getCellPosition());
    const mightWantToKeepCell = editing || focused;
    if (mightWantToKeepCell) {
      const column2 = cellCtrl.getColumn();
      const displayedColumns = this.beans.columnModel.getAllDisplayedColumns();
      const cellStillDisplayed = displayedColumns.indexOf(column2) >= 0;
      return cellStillDisplayed ? KEEP_CELL : REMOVE_CELL;
    }
    return REMOVE_CELL;
  }
  getDomOrder() {
    const isEnsureDomOrder = this.gos.get("ensureDomOrder");
    return isEnsureDomOrder || this.gos.isDomLayout("print");
  }
  listenOnDomOrder(gui) {
    const listener = () => {
      gui.rowComp.setDomOrder(this.getDomOrder());
    };
    this.addManagedPropertyListener("domLayout", listener);
    this.addManagedPropertyListener("ensureDomOrder", listener);
  }
  setAnimateFlags(animateIn) {
    if (this.isSticky() || !animateIn) {
      return;
    }
    const oldRowTopExists = exists(this.rowNode.oldRowTop);
    const pinningLeft = this.beans.columnModel.isPinningLeft();
    const pinningRight = this.beans.columnModel.isPinningRight();
    if (oldRowTopExists) {
      if (this.isFullWidth() && !this.gos.get("embedFullWidthRows")) {
        this.slideInAnimation.fullWidth = true;
        return;
      }
      this.slideInAnimation.center = true;
      this.slideInAnimation.left = pinningLeft;
      this.slideInAnimation.right = pinningRight;
    } else {
      if (this.isFullWidth() && !this.gos.get("embedFullWidthRows")) {
        this.fadeInAnimation.fullWidth = true;
        return;
      }
      this.fadeInAnimation.center = true;
      this.fadeInAnimation.left = pinningLeft;
      this.fadeInAnimation.right = pinningRight;
    }
  }
  isEditing() {
    return this.editingRow;
  }
  isFullWidth() {
    return this.rowType !== "Normal" /* Normal */;
  }
  refreshFullWidth() {
    const tryRefresh = (gui, pinned) => {
      if (!gui) {
        return true;
      }
      return gui.rowComp.refreshFullWidth(() => {
        const compDetails = this.createFullWidthCompDetails(gui.element, pinned);
        return compDetails.params;
      });
    };
    const fullWidthSuccess = tryRefresh(this.fullWidthGui, null);
    const centerSuccess = tryRefresh(this.centerGui, null);
    const leftSuccess = tryRefresh(this.leftGui, "left");
    const rightSuccess = tryRefresh(this.rightGui, "right");
    const allFullWidthRowsRefreshed = fullWidthSuccess && centerSuccess && leftSuccess && rightSuccess;
    return allFullWidthRowsRefreshed;
  }
  addListeners() {
    this.addManagedListener(this.rowNode, RowNode.EVENT_HEIGHT_CHANGED, () => this.onRowHeightChanged());
    this.addManagedListener(this.rowNode, RowNode.EVENT_ROW_SELECTED, () => this.onRowSelected());
    this.addManagedListener(this.rowNode, RowNode.EVENT_ROW_INDEX_CHANGED, this.onRowIndexChanged.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_TOP_CHANGED, this.onTopChanged.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_EXPANDED_CHANGED, this.updateExpandedCss.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_HAS_CHILDREN_CHANGED, this.updateExpandedCss.bind(this));
    if (this.rowNode.detail) {
      this.addManagedListener(this.rowNode.parent, RowNode.EVENT_DATA_CHANGED, this.onRowNodeDataChanged.bind(this));
    }
    this.addManagedListener(this.rowNode, RowNode.EVENT_DATA_CHANGED, this.onRowNodeDataChanged.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, this.postProcessCss.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_HIGHLIGHT_CHANGED, this.onRowNodeHighlightChanged.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_DRAGGING_CHANGED, this.postProcessRowDragging.bind(this));
    this.addManagedListener(this.rowNode, RowNode.EVENT_UI_LEVEL_CHANGED, this.onUiLevelChanged.bind(this));
    const eventService = this.beans.eventService;
    this.addManagedListener(eventService, Events.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED, this.onPaginationPixelOffsetChanged.bind(this));
    this.addManagedListener(eventService, Events.EVENT_HEIGHT_SCALE_CHANGED, this.onTopChanged.bind(this));
    this.addManagedListener(eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.addManagedListener(eventService, Events.EVENT_VIRTUAL_COLUMNS_CHANGED, this.onVirtualColumnsChanged.bind(this));
    this.addManagedListener(eventService, Events.EVENT_CELL_FOCUSED, this.onCellFocusChanged.bind(this));
    this.addManagedListener(eventService, Events.EVENT_CELL_FOCUS_CLEARED, this.onCellFocusChanged.bind(this));
    this.addManagedListener(eventService, Events.EVENT_PAGINATION_CHANGED, this.onPaginationChanged.bind(this));
    this.addManagedListener(eventService, Events.EVENT_MODEL_UPDATED, this.refreshFirstAndLastRowStyles.bind(this));
    this.addManagedListener(eventService, Events.EVENT_COLUMN_MOVED, this.updateColumnLists.bind(this));
    this.addDestroyFunc(() => {
      this.destroyBeans(this.rowDragComps, this.beans.context);
      if (this.tooltipFeature) {
        this.tooltipFeature = this.destroyBean(this.tooltipFeature, this.beans.context);
      }
    });
    this.addManagedPropertyListeners(["rowDragEntireRow"], () => {
      const useRowDragEntireRow = this.gos.get("rowDragEntireRow");
      if (useRowDragEntireRow) {
        this.allRowGuis.forEach((gui) => {
          this.addRowDraggerToRow(gui);
        });
        return;
      }
      this.destroyBeans(this.rowDragComps, this.beans.context);
      this.rowDragComps = [];
    });
    this.addListenersForCellComps();
  }
  addListenersForCellComps() {
    this.addManagedListener(this.rowNode, RowNode.EVENT_ROW_INDEX_CHANGED, () => {
      this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onRowIndexChanged());
    });
    this.addManagedListener(this.rowNode, RowNode.EVENT_CELL_CHANGED, (event) => {
      this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onCellChanged(event));
    });
  }
  onRowNodeDataChanged(event) {
    const fullWidthChanged = this.isFullWidth() !== !!this.rowNode.isFullWidthCell();
    if (fullWidthChanged) {
      this.beans.rowRenderer.redrawRow(this.rowNode);
      return;
    }
    if (this.isFullWidth()) {
      const refresh = this.refreshFullWidth();
      if (!refresh) {
        this.beans.rowRenderer.redrawRow(this.rowNode);
      }
      return;
    }
    this.getAllCellCtrls().forEach(
      (cellCtrl) => cellCtrl.refreshCell({
        suppressFlash: !event.update,
        newData: !event.update
      })
    );
    this.allRowGuis.forEach((gui) => {
      this.setRowCompRowId(gui.rowComp);
      this.updateRowBusinessKey();
      this.setRowCompRowBusinessKey(gui.rowComp);
    });
    this.onRowSelected();
    this.postProcessCss();
  }
  postProcessCss() {
    this.setStylesFromGridOptions(true);
    this.postProcessClassesFromGridOptions();
    this.postProcessRowClassRules();
    this.postProcessRowDragging();
  }
  onRowNodeHighlightChanged() {
    const highlighted = this.rowNode.highlighted;
    this.allRowGuis.forEach((gui) => {
      const aboveOn = highlighted === 0 /* Above */;
      const belowOn = highlighted === 1 /* Below */;
      gui.rowComp.addOrRemoveCssClass("ag-row-highlight-above", aboveOn);
      gui.rowComp.addOrRemoveCssClass("ag-row-highlight-below", belowOn);
    });
  }
  postProcessRowDragging() {
    const dragging = this.rowNode.dragging;
    this.allRowGuis.forEach((gui) => gui.rowComp.addOrRemoveCssClass("ag-row-dragging", dragging));
  }
  updateExpandedCss() {
    const expandable = this.rowNode.isExpandable();
    const expanded = this.rowNode.expanded == true;
    this.allRowGuis.forEach((gui) => {
      gui.rowComp.addOrRemoveCssClass("ag-row-group", expandable);
      gui.rowComp.addOrRemoveCssClass("ag-row-group-expanded", expandable && expanded);
      gui.rowComp.addOrRemoveCssClass("ag-row-group-contracted", expandable && !expanded);
      setAriaExpanded(gui.element, expandable && expanded);
    });
  }
  onDisplayedColumnsChanged() {
    this.updateColumnLists(true);
    if (this.beans.columnModel.wasAutoRowHeightEverActive()) {
      this.rowNode.checkAutoHeights();
    }
  }
  onVirtualColumnsChanged() {
    this.updateColumnLists(false, true);
  }
  getRowPosition() {
    return {
      rowPinned: makeNull(this.rowNode.rowPinned),
      rowIndex: this.rowNode.rowIndex
    };
  }
  onKeyboardNavigate(keyboardEvent) {
    const currentFullWidthComp = this.allRowGuis.find((c) => c.element.contains(keyboardEvent.target));
    const currentFullWidthContainer = currentFullWidthComp ? currentFullWidthComp.element : null;
    const isFullWidthContainerFocused = currentFullWidthContainer === keyboardEvent.target;
    if (!isFullWidthContainerFocused) {
      return;
    }
    const node = this.rowNode;
    const lastFocusedCell = this.beans.focusService.getFocusedCell();
    const cellPosition = {
      rowIndex: node.rowIndex,
      rowPinned: node.rowPinned,
      column: lastFocusedCell && lastFocusedCell.column
    };
    this.beans.navigationService.navigateToNextCell(keyboardEvent, keyboardEvent.key, cellPosition, true);
    keyboardEvent.preventDefault();
  }
  onTabKeyDown(keyboardEvent) {
    if (keyboardEvent.defaultPrevented || isStopPropagationForAgGrid(keyboardEvent)) {
      return;
    }
    const currentFullWidthComp = this.allRowGuis.find((c) => c.element.contains(keyboardEvent.target));
    const currentFullWidthContainer = currentFullWidthComp ? currentFullWidthComp.element : null;
    const isFullWidthContainerFocused = currentFullWidthContainer === keyboardEvent.target;
    let nextEl = null;
    if (!isFullWidthContainerFocused) {
      nextEl = this.beans.focusService.findNextFocusableElement(currentFullWidthContainer, false, keyboardEvent.shiftKey);
    }
    if (this.isFullWidth() && isFullWidthContainerFocused || !nextEl) {
      this.beans.navigationService.onTabKeyDown(this, keyboardEvent);
    }
  }
  getFullWidthElement() {
    if (this.fullWidthGui) {
      return this.fullWidthGui.element;
    }
    return null;
  }
  getRowYPosition() {
    var _a;
    const displayedEl = (_a = this.allRowGuis.find((el) => isVisible(el.element))) == null ? void 0 : _a.element;
    if (displayedEl) {
      return displayedEl.getBoundingClientRect().top;
    }
    return 0;
  }
  onFullWidthRowFocused(event) {
    var _a;
    const node = this.rowNode;
    const isFocused = !event ? false : this.isFullWidth() && event.rowIndex === node.rowIndex && event.rowPinned == node.rowPinned;
    const element = this.fullWidthGui ? this.fullWidthGui.element : (_a = this.centerGui) == null ? void 0 : _a.element;
    if (!element) {
      return;
    }
    element.classList.toggle("ag-full-width-focus", isFocused);
    if (isFocused) {
      element.focus({ preventScroll: true });
    }
  }
  recreateCell(cellCtrl) {
    this.centerCellCtrls = this.removeCellCtrl(this.centerCellCtrls, cellCtrl);
    this.leftCellCtrls = this.removeCellCtrl(this.leftCellCtrls, cellCtrl);
    this.rightCellCtrls = this.removeCellCtrl(this.rightCellCtrls, cellCtrl);
    cellCtrl.destroy();
    this.updateColumnLists();
  }
  removeCellCtrl(prev, cellCtrlToRemove) {
    const res = {
      list: [],
      map: {}
    };
    prev.list.forEach((cellCtrl) => {
      if (cellCtrl === cellCtrlToRemove) {
        return;
      }
      res.list.push(cellCtrl);
      res.map[cellCtrl.getColumn().getInstanceId()] = cellCtrl;
    });
    return res;
  }
  onMouseEvent(eventName, mouseEvent) {
    switch (eventName) {
      case "dblclick":
        this.onRowDblClick(mouseEvent);
        break;
      case "click":
        this.onRowClick(mouseEvent);
        break;
      case "touchstart":
      case "mousedown":
        this.onRowMouseDown(mouseEvent);
        break;
    }
  }
  createRowEvent(type, domEvent) {
    return this.gos.addGridCommonParams({
      type,
      node: this.rowNode,
      data: this.rowNode.data,
      rowIndex: this.rowNode.rowIndex,
      rowPinned: this.rowNode.rowPinned,
      event: domEvent
    });
  }
  createRowEventWithSource(type, domEvent) {
    const event = this.createRowEvent(type, domEvent);
    event.source = this;
    return event;
  }
  onRowDblClick(mouseEvent) {
    if (isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    const agEvent = this.createRowEventWithSource(Events.EVENT_ROW_DOUBLE_CLICKED, mouseEvent);
    this.beans.eventService.dispatchEvent(agEvent);
  }
  onRowMouseDown(mouseEvent) {
    this.lastMouseDownOnDragger = isElementChildOfClass(mouseEvent.target, "ag-row-drag", 3);
    if (!this.isFullWidth()) {
      return;
    }
    const node = this.rowNode;
    const columnModel = this.beans.columnModel;
    if (this.beans.rangeService) {
      this.beans.rangeService.removeAllCellRanges();
    }
    this.beans.focusService.setFocusedCell({
      rowIndex: node.rowIndex,
      column: columnModel.getAllDisplayedColumns()[0],
      rowPinned: node.rowPinned,
      forceBrowserFocus: true
    });
  }
  onRowClick(mouseEvent) {
    const stop = isStopPropagationForAgGrid(mouseEvent) || this.lastMouseDownOnDragger;
    if (stop) {
      return;
    }
    const agEvent = this.createRowEventWithSource(Events.EVENT_ROW_CLICKED, mouseEvent);
    this.beans.eventService.dispatchEvent(agEvent);
    const isMultiKey = mouseEvent.ctrlKey || mouseEvent.metaKey;
    const isShiftKey = mouseEvent.shiftKey;
    const groupSelectsChildren = this.gos.get("groupSelectsChildren");
    if (
      // we do not allow selecting groups by clicking (as the click here expands the group), or if it's a detail row,
      // so return if it's a group row
      groupSelectsChildren && this.rowNode.group || this.isRowSelectionBlocked() || // if click selection suppressed, do nothing
      this.gos.get("suppressRowClickSelection")
    ) {
      return;
    }
    const multiSelectOnClick = this.gos.get("rowMultiSelectWithClick");
    const rowDeselectionWithCtrl = !this.gos.get("suppressRowDeselection");
    const source = "rowClicked";
    if (this.rowNode.isSelected()) {
      if (multiSelectOnClick) {
        this.rowNode.setSelectedParams({ newValue: false, event: mouseEvent, source });
      } else if (isMultiKey) {
        if (rowDeselectionWithCtrl) {
          this.rowNode.setSelectedParams({ newValue: false, event: mouseEvent, source });
        }
      } else {
        this.rowNode.setSelectedParams({ newValue: true, clearSelection: !isShiftKey, rangeSelect: isShiftKey, event: mouseEvent, source });
      }
    } else {
      const clearSelection = multiSelectOnClick ? false : !isMultiKey;
      this.rowNode.setSelectedParams({ newValue: true, clearSelection, rangeSelect: isShiftKey, event: mouseEvent, source });
    }
  }
  isRowSelectionBlocked() {
    return !this.rowNode.selectable || !!this.rowNode.rowPinned || !this.gos.isRowSelection();
  }
  setupDetailRowAutoHeight(eDetailGui) {
    if (this.rowType !== "FullWidthDetail" /* FullWidthDetail */) {
      return;
    }
    if (!this.gos.get("detailRowAutoHeight")) {
      return;
    }
    const checkRowSizeFunc = () => {
      const clientHeight = eDetailGui.clientHeight;
      if (clientHeight != null && clientHeight > 0) {
        const updateRowHeightFunc = () => {
          this.rowNode.setRowHeight(clientHeight);
          if (this.beans.clientSideRowModel) {
            this.beans.clientSideRowModel.onRowHeightChanged();
          } else if (this.beans.serverSideRowModel) {
            this.beans.serverSideRowModel.onRowHeightChanged();
          }
        };
        window.setTimeout(updateRowHeightFunc, 0);
      }
    };
    const resizeObserverDestroyFunc = this.beans.resizeObserverService.observeResize(eDetailGui, checkRowSizeFunc);
    this.addDestroyFunc(resizeObserverDestroyFunc);
    checkRowSizeFunc();
  }
  createFullWidthCompDetails(eRow, pinned) {
    const params = this.gos.addGridCommonParams({
      fullWidth: true,
      data: this.rowNode.data,
      node: this.rowNode,
      value: this.rowNode.key,
      valueFormatted: this.rowNode.key,
      rowIndex: this.rowNode.rowIndex,
      // these need to be taken out, as part of 'afterAttached' now
      eGridCell: eRow,
      eParentOfValue: eRow,
      pinned,
      addRenderedRowListener: this.addEventListener.bind(this),
      registerRowDragger: (rowDraggerElement, dragStartPixels, value, suppressVisibilityChange) => this.addFullWidthRowDragging(rowDraggerElement, dragStartPixels, value, suppressVisibilityChange),
      setTooltip: (value, shouldDisplayTooltip) => this.refreshRowTooltip(value, shouldDisplayTooltip)
    });
    switch (this.rowType) {
      case "FullWidthDetail" /* FullWidthDetail */:
        return this.beans.userComponentFactory.getFullWidthDetailCellRendererDetails(params);
      case "FullWidthGroup" /* FullWidthGroup */:
        return this.beans.userComponentFactory.getFullWidthGroupCellRendererDetails(params);
      case "FullWidthLoading" /* FullWidthLoading */:
        return this.beans.userComponentFactory.getFullWidthLoadingCellRendererDetails(params);
      default:
        return this.beans.userComponentFactory.getFullWidthCellRendererDetails(params);
    }
  }
  refreshRowTooltip(value, shouldDisplayTooltip) {
    if (!this.fullWidthGui) {
      return;
    }
    const tooltipParams = {
      getGui: () => this.fullWidthGui.element,
      getTooltipValue: () => value,
      getLocation: () => "fullWidthRow",
      shouldDisplayTooltip
    };
    if (this.tooltipFeature) {
      this.destroyBean(this.tooltipFeature, this.beans.context);
    }
    this.tooltipFeature = this.createBean(new TooltipFeature(tooltipParams, this.beans));
  }
  addFullWidthRowDragging(rowDraggerElement, dragStartPixels, value = "", suppressVisibilityChange) {
    if (!this.isFullWidth()) {
      return;
    }
    const rowDragComp = new RowDragComp(() => value, this.rowNode, void 0, rowDraggerElement, dragStartPixels, suppressVisibilityChange);
    this.createBean(rowDragComp, this.beans.context);
    this.addDestroyFunc(() => {
      this.destroyBean(rowDragComp, this.beans.context);
    });
  }
  onUiLevelChanged() {
    const newLevel = this.beans.rowCssClassCalculator.calculateRowLevel(this.rowNode);
    if (this.rowLevel != newLevel) {
      const classToAdd = "ag-row-level-" + newLevel;
      const classToRemove = "ag-row-level-" + this.rowLevel;
      this.allRowGuis.forEach((gui) => {
        gui.rowComp.addOrRemoveCssClass(classToAdd, true);
        gui.rowComp.addOrRemoveCssClass(classToRemove, false);
      });
    }
    this.rowLevel = newLevel;
  }
  isFirstRowOnPage() {
    return this.rowNode.rowIndex === this.beans.paginationProxy.getPageFirstRow();
  }
  isLastRowOnPage() {
    return this.rowNode.rowIndex === this.beans.paginationProxy.getPageLastRow();
  }
  refreshFirstAndLastRowStyles() {
    const newFirst = this.isFirstRowOnPage();
    const newLast = this.isLastRowOnPage();
    if (this.firstRowOnPage !== newFirst) {
      this.firstRowOnPage = newFirst;
      this.allRowGuis.forEach((gui) => gui.rowComp.addOrRemoveCssClass("ag-row-first", newFirst));
    }
    if (this.lastRowOnPage !== newLast) {
      this.lastRowOnPage = newLast;
      this.allRowGuis.forEach((gui) => gui.rowComp.addOrRemoveCssClass("ag-row-last", newLast));
    }
  }
  stopEditing(cancel = false) {
    if (this.stoppingRowEdit) {
      return;
    }
    const cellControls = this.getAllCellCtrls();
    const isRowEdit = this.editingRow;
    this.stoppingRowEdit = true;
    let fireRowEditEvent = false;
    for (const ctrl of cellControls) {
      const valueChanged = ctrl.stopEditing(cancel);
      if (isRowEdit && !cancel && !fireRowEditEvent && valueChanged) {
        fireRowEditEvent = true;
      }
    }
    if (fireRowEditEvent) {
      const event = this.createRowEvent(Events.EVENT_ROW_VALUE_CHANGED);
      this.beans.eventService.dispatchEvent(event);
    }
    if (isRowEdit) {
      this.setEditingRow(false);
    }
    this.stoppingRowEdit = false;
  }
  setInlineEditingCss(editing) {
    this.allRowGuis.forEach((gui) => {
      gui.rowComp.addOrRemoveCssClass("ag-row-inline-editing", editing);
      gui.rowComp.addOrRemoveCssClass("ag-row-not-inline-editing", !editing);
    });
  }
  setEditingRow(value) {
    this.editingRow = value;
    this.allRowGuis.forEach((gui) => gui.rowComp.addOrRemoveCssClass("ag-row-editing", value));
    const event = value ? this.createRowEvent(Events.EVENT_ROW_EDITING_STARTED) : this.createRowEvent(Events.EVENT_ROW_EDITING_STOPPED);
    this.beans.eventService.dispatchEvent(event);
  }
  startRowEditing(key = null, sourceRenderedCell = null, event = null) {
    if (this.editingRow) {
      return;
    }
    const atLeastOneEditing = this.getAllCellCtrls().reduce((prev, cellCtrl) => {
      const cellStartedEdit = cellCtrl === sourceRenderedCell;
      if (cellStartedEdit) {
        cellCtrl.startEditing(key, cellStartedEdit, event);
      } else {
        cellCtrl.startEditing(null, cellStartedEdit, event);
      }
      if (prev) {
        return true;
      }
      return cellCtrl.isEditing();
    }, false);
    if (atLeastOneEditing) {
      this.setEditingRow(true);
    }
  }
  getAllCellCtrls() {
    if (this.leftCellCtrls.list.length === 0 && this.rightCellCtrls.list.length === 0) {
      return this.centerCellCtrls.list;
    }
    const res = [...this.centerCellCtrls.list, ...this.leftCellCtrls.list, ...this.rightCellCtrls.list];
    return res;
  }
  postProcessClassesFromGridOptions() {
    const cssClasses = this.beans.rowCssClassCalculator.processClassesFromGridOptions(this.rowNode);
    if (!cssClasses || !cssClasses.length) {
      return;
    }
    cssClasses.forEach((classStr) => {
      this.allRowGuis.forEach((c) => c.rowComp.addOrRemoveCssClass(classStr, true));
    });
  }
  postProcessRowClassRules() {
    this.beans.rowCssClassCalculator.processRowClassRules(
      this.rowNode,
      (className) => {
        this.allRowGuis.forEach((gui) => gui.rowComp.addOrRemoveCssClass(className, true));
      },
      (className) => {
        this.allRowGuis.forEach((gui) => gui.rowComp.addOrRemoveCssClass(className, false));
      }
    );
  }
  setStylesFromGridOptions(updateStyles, gui) {
    if (updateStyles) {
      this.rowStyles = this.processStylesFromGridOptions();
    }
    this.forEachGui(gui, (gui2) => gui2.rowComp.setUserStyles(this.rowStyles));
  }
  getPinnedForContainer(rowContainerType) {
    const pinned = rowContainerType === "left" /* LEFT */ ? "left" : rowContainerType === "right" /* RIGHT */ ? "right" : null;
    return pinned;
  }
  getInitialRowClasses(rowContainerType) {
    const pinned = this.getPinnedForContainer(rowContainerType);
    const params = {
      rowNode: this.rowNode,
      rowFocused: this.rowFocused,
      fadeRowIn: this.fadeInAnimation[rowContainerType],
      rowIsEven: this.rowNode.rowIndex % 2 === 0,
      rowLevel: this.rowLevel,
      fullWidthRow: this.isFullWidth(),
      firstRowOnPage: this.isFirstRowOnPage(),
      lastRowOnPage: this.isLastRowOnPage(),
      printLayout: this.printLayout,
      expandable: this.rowNode.isExpandable(),
      pinned
    };
    return this.beans.rowCssClassCalculator.getInitialRowClasses(params);
  }
  processStylesFromGridOptions() {
    const rowStyle = this.gos.get("rowStyle");
    if (rowStyle && typeof rowStyle === "function") {
      console.warn("AG Grid: rowStyle should be an object of key/value styles, not be a function, use getRowStyle() instead");
      return;
    }
    const rowStyleFunc = this.gos.getCallback("getRowStyle");
    let rowStyleFuncResult;
    if (rowStyleFunc) {
      const params = {
        data: this.rowNode.data,
        node: this.rowNode,
        rowIndex: this.rowNode.rowIndex
      };
      rowStyleFuncResult = rowStyleFunc(params);
    }
    if (rowStyleFuncResult || rowStyle) {
      return Object.assign({}, rowStyle, rowStyleFuncResult);
    }
    return this.emptyStyle;
  }
  onRowSelected(gui) {
    const selected = !!this.rowNode.isSelected();
    this.forEachGui(gui, (gui2) => {
      gui2.rowComp.addOrRemoveCssClass("ag-row-selected", selected);
      setAriaSelected(gui2.element, selected);
      const hasFocus = gui2.element.contains(this.beans.gos.getActiveDomElement());
      if (hasFocus && (gui2 === this.centerGui || gui2 === this.fullWidthGui)) {
        this.announceDescription();
      }
    });
  }
  announceDescription() {
    if (this.isRowSelectionBlocked()) {
      return;
    }
    const selected = this.rowNode.isSelected();
    if (selected && this.beans.gos.get("suppressRowDeselection")) {
      return;
    }
    const translate = this.beans.localeService.getLocaleTextFunc();
    const label = translate(
      selected ? "ariaRowDeselect" : "ariaRowSelect",
      `Press SPACE to ${selected ? "deselect" : "select"} this row.`
    );
    this.beans.ariaAnnouncementService.announceValue(label);
  }
  addHoverFunctionality(eRow) {
    if (!this.active) {
      return;
    }
    this.addManagedListener(eRow, "mouseenter", () => this.rowNode.onMouseEnter());
    this.addManagedListener(eRow, "mouseleave", () => this.rowNode.onMouseLeave());
    this.addManagedListener(this.rowNode, RowNode.EVENT_MOUSE_ENTER, () => {
      if (!this.beans.dragService.isDragging() && !this.gos.get("suppressRowHoverHighlight")) {
        eRow.classList.add("ag-row-hover");
        this.rowNode.setHovered(true);
      }
    });
    this.addManagedListener(this.rowNode, RowNode.EVENT_MOUSE_LEAVE, () => {
      eRow.classList.remove("ag-row-hover");
      this.rowNode.setHovered(false);
    });
  }
  // for animation, we don't want to animate entry or exit to a very far away pixel,
  // otherwise the row would move so fast, it would appear to disappear. so this method
  // moves the row closer to the viewport if it is far away, so the row slide in / out
  // at a speed the user can see.
  roundRowTopToBounds(rowTop) {
    const range = this.beans.ctrlsService.getGridBodyCtrl().getScrollFeature().getApproximateVScollPosition();
    const minPixel = this.applyPaginationOffset(range.top, true) - 100;
    const maxPixel = this.applyPaginationOffset(range.bottom, true) + 100;
    return Math.min(Math.max(minPixel, rowTop), maxPixel);
  }
  getFrameworkOverrides() {
    return this.beans.frameworkOverrides;
  }
  forEachGui(gui, callback) {
    if (gui) {
      callback(gui);
    } else {
      this.allRowGuis.forEach(callback);
    }
  }
  onRowHeightChanged(gui) {
    if (this.rowNode.rowHeight == null) {
      return;
    }
    const rowHeight = this.rowNode.rowHeight;
    const defaultRowHeight = this.beans.environment.getDefaultRowHeight();
    const isHeightFromFunc = this.gos.isGetRowHeightFunction();
    const heightFromFunc = isHeightFromFunc ? this.gos.getRowHeightForNode(this.rowNode).height : void 0;
    const lineHeight = heightFromFunc ? `${Math.min(defaultRowHeight, heightFromFunc) - 2}px` : void 0;
    this.forEachGui(gui, (gui2) => {
      gui2.element.style.height = `${rowHeight}px`;
      if (lineHeight) {
        gui2.element.style.setProperty("--ag-line-height", lineHeight);
      }
    });
  }
  addEventListener(eventType, listener) {
    super.addEventListener(eventType, listener);
  }
  removeEventListener(eventType, listener) {
    super.removeEventListener(eventType, listener);
  }
  // note - this is NOT called by context, as we don't wire / unwire the CellComp for performance reasons.
  destroyFirstPass(suppressAnimation = false) {
    this.active = false;
    if (!suppressAnimation && this.gos.isAnimateRows() && !this.isSticky()) {
      const rowStillVisibleJustNotInViewport = this.rowNode.rowTop != null;
      if (rowStillVisibleJustNotInViewport) {
        const rowTop = this.roundRowTopToBounds(this.rowNode.rowTop);
        this.setRowTop(rowTop);
      } else {
        this.allRowGuis.forEach((gui) => gui.rowComp.addOrRemoveCssClass("ag-opacity-zero", true));
      }
    }
    this.rowNode.setHovered(false);
    const event = this.createRowEvent(Events.EVENT_VIRTUAL_ROW_REMOVED);
    this.dispatchEvent(event);
    this.beans.eventService.dispatchEvent(event);
    super.destroy();
  }
  destroySecondPass() {
    this.allRowGuis.length = 0;
    this.stopEditing();
    const destroyCellCtrls = (ctrls) => {
      ctrls.list.forEach((c) => c.destroy());
      return { list: [], map: {} };
    };
    this.centerCellCtrls = destroyCellCtrls(this.centerCellCtrls);
    this.leftCellCtrls = destroyCellCtrls(this.leftCellCtrls);
    this.rightCellCtrls = destroyCellCtrls(this.rightCellCtrls);
  }
  setFocusedClasses(gui) {
    this.forEachGui(gui, (gui2) => {
      gui2.rowComp.addOrRemoveCssClass("ag-row-focus", this.rowFocused);
      gui2.rowComp.addOrRemoveCssClass("ag-row-no-focus", !this.rowFocused);
    });
  }
  onCellFocusChanged() {
    const rowFocused = this.beans.focusService.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned);
    if (rowFocused !== this.rowFocused) {
      this.rowFocused = rowFocused;
      this.setFocusedClasses();
    }
    if (!rowFocused && this.editingRow) {
      this.stopEditing(false);
    }
  }
  onPaginationChanged() {
    const currentPage = this.beans.paginationProxy.getCurrentPage();
    if (this.paginationPage !== currentPage) {
      this.paginationPage = currentPage;
      this.onTopChanged();
    }
    this.refreshFirstAndLastRowStyles();
  }
  onTopChanged() {
    this.setRowTop(this.rowNode.rowTop);
  }
  onPaginationPixelOffsetChanged() {
    this.onTopChanged();
  }
  // applies pagination offset, eg if on second page, and page height is 500px, then removes
  // 500px from the top position, so a row with rowTop 600px is displayed at location 100px.
  // reverse will take the offset away rather than add.
  applyPaginationOffset(topPx, reverse = false) {
    if (this.rowNode.isRowPinned() || this.rowNode.sticky) {
      return topPx;
    }
    const pixelOffset = this.beans.paginationProxy.getPixelOffset();
    const multiplier = reverse ? 1 : -1;
    return topPx + pixelOffset * multiplier;
  }
  setRowTop(pixels) {
    if (this.printLayout) {
      return;
    }
    if (exists(pixels)) {
      const afterPaginationPixels = this.applyPaginationOffset(pixels);
      const skipScaling = this.rowNode.isRowPinned() || this.rowNode.sticky;
      const afterScalingPixels = skipScaling ? afterPaginationPixels : this.beans.rowContainerHeightService.getRealPixelPosition(afterPaginationPixels);
      const topPx = `${afterScalingPixels}px`;
      this.setRowTopStyle(topPx);
    }
  }
  // the top needs to be set into the DOM element when the element is created, not updated afterwards.
  // otherwise the transition would not work, as it would be transitioning from zero (the unset value).
  // for example, suppose a row that is outside the viewport, then user does a filter to remove other rows
  // and this row now appears in the viewport, and the row moves up (ie it was under the viewport and not rendered,
  // but now is in the viewport) then a new RowComp is created, however it should have it's position initialised
  // to below the viewport, so the row will appear to animate up. if we didn't set the initial position at creation
  // time, the row would animate down (ie from position zero).
  getInitialRowTop(rowContainerType) {
    return this.suppressRowTransform ? this.getInitialRowTopShared(rowContainerType) : void 0;
  }
  getInitialTransform(rowContainerType) {
    return this.suppressRowTransform ? void 0 : `translateY(${this.getInitialRowTopShared(rowContainerType)})`;
  }
  getInitialRowTopShared(rowContainerType) {
    if (this.printLayout) {
      return "";
    }
    let rowTop;
    if (this.isSticky()) {
      rowTop = this.rowNode.stickyRowTop;
    } else {
      const pixels = this.slideInAnimation[rowContainerType] ? this.roundRowTopToBounds(this.rowNode.oldRowTop) : this.rowNode.rowTop;
      const afterPaginationPixels = this.applyPaginationOffset(pixels);
      rowTop = this.rowNode.isRowPinned() ? afterPaginationPixels : this.beans.rowContainerHeightService.getRealPixelPosition(afterPaginationPixels);
    }
    return rowTop + "px";
  }
  setRowTopStyle(topPx) {
    this.allRowGuis.forEach(
      (gui) => this.suppressRowTransform ? gui.rowComp.setTop(topPx) : gui.rowComp.setTransform(`translateY(${topPx})`)
    );
  }
  getRowNode() {
    return this.rowNode;
  }
  getCellCtrl(column) {
    let res = null;
    this.getAllCellCtrls().forEach((cellCtrl) => {
      if (cellCtrl.getColumn() == column) {
        res = cellCtrl;
      }
    });
    if (res != null) {
      return res;
    }
    this.getAllCellCtrls().forEach((cellCtrl) => {
      if (cellCtrl.getColSpanningList().indexOf(column) >= 0) {
        res = cellCtrl;
      }
    });
    return res;
  }
  onRowIndexChanged() {
    if (this.rowNode.rowIndex != null) {
      this.onCellFocusChanged();
      this.updateRowIndexes();
      this.postProcessCss();
    }
  }
  getRowIndex() {
    return this.rowNode.getRowIndexString();
  }
  updateRowIndexes(gui) {
    const rowIndexStr = this.rowNode.getRowIndexString();
    const headerRowCount = this.beans.headerNavigationService.getHeaderRowCount() + this.beans.filterManager.getHeaderRowCount();
    const rowIsEven = this.rowNode.rowIndex % 2 === 0;
    const ariaRowIndex = headerRowCount + this.rowNode.rowIndex + 1;
    this.forEachGui(gui, (c) => {
      c.rowComp.setRowIndex(rowIndexStr);
      c.rowComp.addOrRemoveCssClass("ag-row-even", rowIsEven);
      c.rowComp.addOrRemoveCssClass("ag-row-odd", !rowIsEven);
      setAriaRowIndex(c.element, ariaRowIndex);
    });
  }
};
_RowCtrl.DOM_DATA_KEY_ROW_CTRL = "renderedRow";
var RowCtrl = _RowCtrl;

// community-modules/core/src/gridBodyComp/rowContainer/rowContainerEventsFeature.ts
var RowContainerEventsFeature = class extends BeanStub {
  constructor(element) {
    super();
    this.element = element;
  }
  postConstruct() {
    this.addKeyboardListeners();
    this.addMouseListeners();
    this.mockContextMenuForIPad();
  }
  addKeyboardListeners() {
    const eventName = "keydown";
    const listener = this.processKeyboardEvent.bind(this, eventName);
    this.addManagedListener(this.element, eventName, listener);
  }
  addMouseListeners() {
    const mouseDownEvent = isEventSupported("touchstart") ? "touchstart" : "mousedown";
    const eventNames = ["dblclick", "contextmenu", "mouseover", "mouseout", "click", mouseDownEvent];
    eventNames.forEach((eventName) => {
      const listener = this.processMouseEvent.bind(this, eventName);
      this.addManagedListener(this.element, eventName, listener);
    });
  }
  processMouseEvent(eventName, mouseEvent) {
    if (!this.mouseEventService.isEventFromThisGrid(mouseEvent) || isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    const rowComp = this.getRowForEvent(mouseEvent);
    const cellCtrl = this.mouseEventService.getRenderedCellForEvent(mouseEvent);
    if (eventName === "contextmenu") {
      this.handleContextMenuMouseEvent(mouseEvent, void 0, rowComp, cellCtrl);
    } else {
      if (cellCtrl) {
        cellCtrl.onMouseEvent(eventName, mouseEvent);
      }
      if (rowComp) {
        rowComp.onMouseEvent(eventName, mouseEvent);
      }
    }
  }
  mockContextMenuForIPad() {
    if (!isIOSUserAgent()) {
      return;
    }
    const touchListener = new TouchListener(this.element);
    const longTapListener = (event) => {
      const rowComp = this.getRowForEvent(event.touchEvent);
      const cellComp = this.mouseEventService.getRenderedCellForEvent(event.touchEvent);
      this.handleContextMenuMouseEvent(void 0, event.touchEvent, rowComp, cellComp);
    };
    this.addManagedListener(touchListener, TouchListener.EVENT_LONG_TAP, longTapListener);
    this.addDestroyFunc(() => touchListener.destroy());
  }
  getRowForEvent(event) {
    let sourceElement = event.target;
    while (sourceElement) {
      const rowCon = this.gos.getDomData(sourceElement, RowCtrl.DOM_DATA_KEY_ROW_CTRL);
      if (rowCon) {
        return rowCon;
      }
      sourceElement = sourceElement.parentElement;
    }
    return null;
  }
  handleContextMenuMouseEvent(mouseEvent, touchEvent, rowComp, cellCtrl) {
    const rowNode = rowComp ? rowComp.getRowNode() : null;
    const column = cellCtrl ? cellCtrl.getColumn() : null;
    let value = null;
    if (column) {
      const event = mouseEvent ? mouseEvent : touchEvent;
      cellCtrl.dispatchCellContextMenuEvent(event != null ? event : null);
      value = this.valueService.getValue(column, rowNode);
    }
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    const anchorToElement = cellCtrl ? cellCtrl.getGui() : gridBodyCon.getGridBodyElement();
    this.menuService.showContextMenu({ mouseEvent, touchEvent, rowNode, column, value, anchorToElement });
  }
  getControlsForEventTarget(target) {
    return {
      cellCtrl: getCtrlForEventTarget(this.gos, target, CellCtrl.DOM_DATA_KEY_CELL_CTRL),
      rowCtrl: getCtrlForEventTarget(this.gos, target, RowCtrl.DOM_DATA_KEY_ROW_CTRL)
    };
  }
  processKeyboardEvent(eventName, keyboardEvent) {
    const { cellCtrl, rowCtrl } = this.getControlsForEventTarget(keyboardEvent.target);
    if (keyboardEvent.defaultPrevented) {
      return;
    }
    if (cellCtrl) {
      this.processCellKeyboardEvent(cellCtrl, eventName, keyboardEvent);
    } else if (rowCtrl && rowCtrl.isFullWidth()) {
      this.processFullWidthRowKeyboardEvent(rowCtrl, eventName, keyboardEvent);
    }
  }
  processCellKeyboardEvent(cellCtrl, eventName, keyboardEvent) {
    const rowNode = cellCtrl.getRowNode();
    const column = cellCtrl.getColumn();
    const editing = cellCtrl.isEditing();
    const gridProcessingAllowed = !isUserSuppressingKeyboardEvent(this.gos, keyboardEvent, rowNode, column, editing);
    if (gridProcessingAllowed) {
      if (eventName === "keydown") {
        const wasScrollKey = !editing && this.navigationService.handlePageScrollingKey(keyboardEvent);
        if (!wasScrollKey) {
          cellCtrl.onKeyDown(keyboardEvent);
        }
        this.doGridOperations(keyboardEvent, cellCtrl.isEditing());
        if (isEventFromPrintableCharacter(keyboardEvent)) {
          cellCtrl.processCharacter(keyboardEvent);
        }
      }
    }
    if (eventName === "keydown") {
      const cellKeyDownEvent = cellCtrl.createEvent(keyboardEvent, Events.EVENT_CELL_KEY_DOWN);
      this.eventService.dispatchEvent(cellKeyDownEvent);
    }
  }
  processFullWidthRowKeyboardEvent(rowComp, eventName, keyboardEvent) {
    const rowNode = rowComp.getRowNode();
    const focusedCell = this.focusService.getFocusedCell();
    const column = focusedCell && focusedCell.column;
    const gridProcessingAllowed = !isUserSuppressingKeyboardEvent(this.gos, keyboardEvent, rowNode, column, false);
    if (gridProcessingAllowed) {
      const key = keyboardEvent.key;
      if (eventName === "keydown") {
        switch (key) {
          case KeyCode.PAGE_HOME:
          case KeyCode.PAGE_END:
          case KeyCode.PAGE_UP:
          case KeyCode.PAGE_DOWN:
            this.navigationService.handlePageScrollingKey(keyboardEvent, true);
            break;
          case KeyCode.UP:
          case KeyCode.DOWN:
            rowComp.onKeyboardNavigate(keyboardEvent);
            break;
          case KeyCode.TAB:
            rowComp.onTabKeyDown(keyboardEvent);
            break;
          default:
        }
      }
    }
    if (eventName === "keydown") {
      const cellKeyDownEvent = rowComp.createRowEvent(Events.EVENT_CELL_KEY_DOWN, keyboardEvent);
      this.eventService.dispatchEvent(cellKeyDownEvent);
    }
  }
  doGridOperations(keyboardEvent, editing) {
    if (!keyboardEvent.ctrlKey && !keyboardEvent.metaKey) {
      return;
    }
    if (editing) {
      return;
    }
    if (!this.mouseEventService.isEventFromThisGrid(keyboardEvent)) {
      return;
    }
    const keyCode = normaliseQwertyAzerty(keyboardEvent);
    if (keyCode === KeyCode.A) {
      return this.onCtrlAndA(keyboardEvent);
    }
    if (keyCode === KeyCode.C) {
      return this.onCtrlAndC(keyboardEvent);
    }
    if (keyCode === KeyCode.D) {
      return this.onCtrlAndD(keyboardEvent);
    }
    if (keyCode === KeyCode.V) {
      return this.onCtrlAndV(keyboardEvent);
    }
    if (keyCode === KeyCode.X) {
      return this.onCtrlAndX(keyboardEvent);
    }
    if (keyCode === KeyCode.Y) {
      return this.onCtrlAndY();
    }
    if (keyCode === KeyCode.Z) {
      return this.onCtrlAndZ(keyboardEvent);
    }
  }
  onCtrlAndA(event) {
    const { pinnedRowModel, paginationProxy, rangeService } = this;
    if (rangeService && paginationProxy.isRowsToRender()) {
      const [isEmptyPinnedTop, isEmptyPinnedBottom] = [
        pinnedRowModel.isEmpty("top"),
        pinnedRowModel.isEmpty("bottom")
      ];
      const floatingStart = isEmptyPinnedTop ? null : "top";
      let floatingEnd;
      let rowEnd;
      if (isEmptyPinnedBottom) {
        floatingEnd = null;
        rowEnd = this.paginationProxy.getRowCount() - 1;
      } else {
        floatingEnd = "bottom";
        rowEnd = pinnedRowModel.getPinnedBottomRowData().length - 1;
      }
      const allDisplayedColumns = this.columnModel.getAllDisplayedColumns();
      if (missingOrEmpty(allDisplayedColumns)) {
        return;
      }
      rangeService.setCellRange({
        rowStartIndex: 0,
        rowStartPinned: floatingStart,
        rowEndIndex: rowEnd,
        rowEndPinned: floatingEnd,
        columnStart: allDisplayedColumns[0],
        columnEnd: last(allDisplayedColumns)
      });
    }
    event.preventDefault();
  }
  onCtrlAndC(event) {
    if (!this.clipboardService || this.gos.get("enableCellTextSelection")) {
      return;
    }
    const { cellCtrl, rowCtrl } = this.getControlsForEventTarget(event.target);
    if ((cellCtrl == null ? void 0 : cellCtrl.isEditing()) || (rowCtrl == null ? void 0 : rowCtrl.isEditing())) {
      return;
    }
    event.preventDefault();
    this.clipboardService.copyToClipboard();
  }
  onCtrlAndX(event) {
    if (!this.clipboardService || this.gos.get("enableCellTextSelection") || this.gos.get("suppressCutToClipboard")) {
      return;
    }
    const { cellCtrl, rowCtrl } = this.getControlsForEventTarget(event.target);
    if ((cellCtrl == null ? void 0 : cellCtrl.isEditing()) || (rowCtrl == null ? void 0 : rowCtrl.isEditing())) {
      return;
    }
    event.preventDefault();
    this.clipboardService.cutToClipboard(void 0, "ui");
  }
  onCtrlAndV(event) {
    const { cellCtrl, rowCtrl } = this.getControlsForEventTarget(event.target);
    if ((cellCtrl == null ? void 0 : cellCtrl.isEditing()) || (rowCtrl == null ? void 0 : rowCtrl.isEditing())) {
      return;
    }
    if (this.clipboardService && !this.gos.get("suppressClipboardPaste")) {
      this.clipboardService.pasteFromClipboard();
    }
  }
  onCtrlAndD(event) {
    if (this.clipboardService && !this.gos.get("suppressClipboardPaste")) {
      this.clipboardService.copyRangeDown();
    }
    event.preventDefault();
  }
  onCtrlAndZ(event) {
    if (!this.gos.get("undoRedoCellEditing")) {
      return;
    }
    event.preventDefault();
    if (event.shiftKey) {
      this.undoRedoService.redo("ui");
    } else {
      this.undoRedoService.undo("ui");
    }
  }
  onCtrlAndY() {
    this.undoRedoService.redo("ui");
  }
};
__decorateClass([
  Autowired("mouseEventService")
], RowContainerEventsFeature.prototype, "mouseEventService", 2);
__decorateClass([
  Autowired("valueService")
], RowContainerEventsFeature.prototype, "valueService", 2);
__decorateClass([
  Autowired("menuService")
], RowContainerEventsFeature.prototype, "menuService", 2);
__decorateClass([
  Autowired("ctrlsService")
], RowContainerEventsFeature.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("navigationService")
], RowContainerEventsFeature.prototype, "navigationService", 2);
__decorateClass([
  Autowired("focusService")
], RowContainerEventsFeature.prototype, "focusService", 2);
__decorateClass([
  Autowired("undoRedoService")
], RowContainerEventsFeature.prototype, "undoRedoService", 2);
__decorateClass([
  Autowired("columnModel")
], RowContainerEventsFeature.prototype, "columnModel", 2);
__decorateClass([
  Autowired("paginationProxy")
], RowContainerEventsFeature.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], RowContainerEventsFeature.prototype, "pinnedRowModel", 2);
__decorateClass([
  Optional("rangeService")
], RowContainerEventsFeature.prototype, "rangeService", 2);
__decorateClass([
  Optional("clipboardService")
], RowContainerEventsFeature.prototype, "clipboardService", 2);
__decorateClass([
  PostConstruct
], RowContainerEventsFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/viewportSizeFeature.ts
var ViewportSizeFeature = class extends BeanStub {
  constructor(centerContainerCtrl) {
    super();
    this.centerContainerCtrl = centerContainerCtrl;
  }
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
      this.listenForResize();
    });
    this.addManagedListener(this.eventService, Events.EVENT_SCROLLBAR_WIDTH_CHANGED, this.onScrollbarWidthChanged.bind(this));
    this.addManagedPropertyListeners(["alwaysShowHorizontalScroll", "alwaysShowVerticalScroll"], () => {
      this.checkViewportAndScrolls();
    });
  }
  listenForResize() {
    const listener = () => this.onCenterViewportResized();
    this.centerContainerCtrl.registerViewportResizeListener(listener);
    this.gridBodyCtrl.registerBodyViewportResizeListener(listener);
  }
  onScrollbarWidthChanged() {
    this.checkViewportAndScrolls();
  }
  onCenterViewportResized() {
    if (this.centerContainerCtrl.isViewportInTheDOMTree()) {
      this.keepPinnedColumnsNarrowerThanViewport();
      this.checkViewportAndScrolls();
      const newWidth = this.centerContainerCtrl.getCenterWidth();
      if (newWidth !== this.centerWidth) {
        this.centerWidth = newWidth;
        this.columnModel.refreshFlexedColumns(
          { viewportWidth: this.centerWidth, updateBodyWidths: true, fireResizedEvent: true }
        );
      }
    } else {
      this.bodyHeight = 0;
    }
  }
  keepPinnedColumnsNarrowerThanViewport() {
    const eBodyViewport = this.gridBodyCtrl.getBodyViewportElement();
    const bodyWidth = getInnerWidth(eBodyViewport);
    if (bodyWidth <= 50) {
      return;
    }
    let columnsToRemove = this.getPinnedColumnsOverflowingViewport(bodyWidth - 50);
    const processUnpinnedColumns = this.gos.getCallback("processUnpinnedColumns");
    if (!columnsToRemove.length) {
      return;
    }
    if (processUnpinnedColumns) {
      const params = {
        columns: columnsToRemove,
        viewportWidth: bodyWidth
      };
      columnsToRemove = processUnpinnedColumns(params);
    }
    this.columnModel.setColumnsPinned(columnsToRemove, null, "viewportSizeFeature");
  }
  getPinnedColumnsOverflowingViewport(viewportWidth) {
    const pinnedRightWidth = this.pinnedWidthService.getPinnedRightWidth();
    const pinnedLeftWidth = this.pinnedWidthService.getPinnedLeftWidth();
    const totalPinnedWidth = pinnedRightWidth + pinnedLeftWidth;
    if (totalPinnedWidth < viewportWidth) {
      return [];
    }
    const pinnedLeftColumns = [...this.columnModel.getDisplayedLeftColumns()];
    const pinnedRightColumns = [...this.columnModel.getDisplayedRightColumns()];
    let indexRight = 0;
    let indexLeft = 0;
    let totalWidthRemoved = 0;
    const columnsToRemove = [];
    let spaceNecessary = totalPinnedWidth - totalWidthRemoved - viewportWidth;
    while ((indexLeft < pinnedLeftColumns.length || indexRight < pinnedRightColumns.length) && spaceNecessary > 0) {
      if (indexRight < pinnedRightColumns.length) {
        const currentColumn = pinnedRightColumns[indexRight++];
        spaceNecessary -= currentColumn.getActualWidth();
        columnsToRemove.push(currentColumn);
      }
      if (indexLeft < pinnedLeftColumns.length && spaceNecessary > 0) {
        const currentColumn = pinnedLeftColumns[indexLeft++];
        spaceNecessary -= currentColumn.getActualWidth();
        columnsToRemove.push(currentColumn);
      }
    }
    return columnsToRemove;
  }
  // gets called every time the viewport size changes. we use this to check visibility of scrollbars
  // in the grid panel, and also to check size and position of viewport for row and column virtualisation.
  checkViewportAndScrolls() {
    this.updateScrollVisibleService();
    this.checkBodyHeight();
    this.onHorizontalViewportChanged();
    this.gridBodyCtrl.getScrollFeature().checkScrollLeft();
  }
  getBodyHeight() {
    return this.bodyHeight;
  }
  checkBodyHeight() {
    const eBodyViewport = this.gridBodyCtrl.getBodyViewportElement();
    const bodyHeight = getInnerHeight(eBodyViewport);
    if (this.bodyHeight !== bodyHeight) {
      this.bodyHeight = bodyHeight;
      const event = {
        type: Events.EVENT_BODY_HEIGHT_CHANGED
      };
      this.eventService.dispatchEvent(event);
    }
  }
  updateScrollVisibleService() {
    this.updateScrollVisibleServiceImpl();
    setTimeout(this.updateScrollVisibleServiceImpl.bind(this), 500);
  }
  updateScrollVisibleServiceImpl() {
    const params = {
      horizontalScrollShowing: this.isHorizontalScrollShowing(),
      verticalScrollShowing: this.gridBodyCtrl.isVerticalScrollShowing()
    };
    this.scrollVisibleService.setScrollsVisible(params);
  }
  isHorizontalScrollShowing() {
    return this.centerContainerCtrl.isHorizontalScrollShowing();
  }
  // this gets called whenever a change in the viewport, so we can inform column controller it has to work
  // out the virtual columns again. gets called from following locations:
  // + ensureColVisible, scroll, init, layoutChanged, displayedColumnsChanged
  onHorizontalViewportChanged() {
    const scrollWidth = this.centerContainerCtrl.getCenterWidth();
    const scrollPosition = this.centerContainerCtrl.getViewportScrollLeft();
    this.columnModel.setViewportPosition(scrollWidth, scrollPosition);
  }
};
__decorateClass([
  Autowired("ctrlsService")
], ViewportSizeFeature.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("pinnedWidthService")
], ViewportSizeFeature.prototype, "pinnedWidthService", 2);
__decorateClass([
  Autowired("columnModel")
], ViewportSizeFeature.prototype, "columnModel", 2);
__decorateClass([
  Autowired("scrollVisibleService")
], ViewportSizeFeature.prototype, "scrollVisibleService", 2);
__decorateClass([
  PostConstruct
], ViewportSizeFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/rowContainer/setPinnedLeftWidthFeature.ts
var SetPinnedLeftWidthFeature = class extends BeanStub {
  constructor(element) {
    super();
    this.element = element;
  }
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_LEFT_PINNED_WIDTH_CHANGED, this.onPinnedLeftWidthChanged.bind(this));
  }
  onPinnedLeftWidthChanged() {
    const leftWidth = this.pinnedWidthService.getPinnedLeftWidth();
    const displayed = leftWidth > 0;
    setDisplayed(this.element, displayed);
    setFixedWidth(this.element, leftWidth);
  }
  getWidth() {
    return this.pinnedWidthService.getPinnedLeftWidth();
  }
};
__decorateClass([
  Autowired("pinnedWidthService")
], SetPinnedLeftWidthFeature.prototype, "pinnedWidthService", 2);
__decorateClass([
  PostConstruct
], SetPinnedLeftWidthFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/rowContainer/setPinnedRightWidthFeature.ts
var SetPinnedRightWidthFeature = class extends BeanStub {
  constructor(element) {
    super();
    this.element = element;
  }
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_RIGHT_PINNED_WIDTH_CHANGED, this.onPinnedRightWidthChanged.bind(this));
  }
  onPinnedRightWidthChanged() {
    const rightWidth = this.pinnedWidthService.getPinnedRightWidth();
    const displayed = rightWidth > 0;
    setDisplayed(this.element, displayed);
    setFixedWidth(this.element, rightWidth);
  }
  getWidth() {
    return this.pinnedWidthService.getPinnedRightWidth();
  }
};
__decorateClass([
  Autowired("pinnedWidthService")
], SetPinnedRightWidthFeature.prototype, "pinnedWidthService", 2);
__decorateClass([
  PostConstruct
], SetPinnedRightWidthFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/rowContainer/setHeightFeature.ts
var SetHeightFeature = class extends BeanStub {
  constructor(eContainer, eViewport) {
    super();
    this.eContainer = eContainer;
    this.eViewport = eViewport;
  }
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_ROW_CONTAINER_HEIGHT_CHANGED, this.onHeightChanged.bind(this));
  }
  onHeightChanged() {
    const height = this.maxDivHeightScaler.getUiContainerHeight();
    const heightString = height != null ? `${height}px` : ``;
    this.eContainer.style.height = heightString;
    if (this.eViewport) {
      this.eViewport.style.height = heightString;
    }
  }
};
__decorateClass([
  Autowired("rowContainerHeightService")
], SetHeightFeature.prototype, "maxDivHeightScaler", 2);
__decorateClass([
  PostConstruct
], SetHeightFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/rowContainer/dragListenerFeature.ts
var DragListenerFeature = class extends BeanStub {
  constructor(eContainer) {
    super();
    this.eContainer = eContainer;
  }
  postConstruct() {
    if (!this.rangeService) {
      return;
    }
    this.params = {
      eElement: this.eContainer,
      onDragStart: this.rangeService.onDragStart.bind(this.rangeService),
      onDragStop: this.rangeService.onDragStop.bind(this.rangeService),
      onDragging: this.rangeService.onDragging.bind(this.rangeService)
    };
    this.addManagedPropertyListener("enableRangeSelection", (props) => {
      const isEnabled = props.currentValue;
      if (isEnabled) {
        this.enableFeature();
        return;
      }
      this.disableFeature();
    });
    this.addDestroyFunc(() => this.disableFeature());
    const isRangeSelection = this.gos.get("enableRangeSelection");
    if (isRangeSelection) {
      this.enableFeature();
    }
  }
  enableFeature() {
    this.dragService.addDragSource(this.params);
  }
  disableFeature() {
    this.dragService.removeDragSource(this.params);
  }
};
__decorateClass([
  Autowired("dragService")
], DragListenerFeature.prototype, "dragService", 2);
__decorateClass([
  Optional("rangeService")
], DragListenerFeature.prototype, "rangeService", 2);
__decorateClass([
  PostConstruct
], DragListenerFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/centerWidthFeature.ts
var CenterWidthFeature = class extends BeanStub {
  constructor(callback, addSpacer = false) {
    super();
    this.callback = callback;
    this.addSpacer = addSpacer;
  }
  postConstruct() {
    const listener = this.setWidth.bind(this);
    this.addManagedPropertyListener("domLayout", listener);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_CONTAINER_WIDTH_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_LEFT_PINNED_WIDTH_CHANGED, listener);
    if (this.addSpacer) {
      this.addManagedListener(this.eventService, Events.EVENT_RIGHT_PINNED_WIDTH_CHANGED, listener);
      this.addManagedListener(this.eventService, Events.EVENT_SCROLL_VISIBILITY_CHANGED, listener);
      this.addManagedListener(this.eventService, Events.EVENT_SCROLLBAR_WIDTH_CHANGED, listener);
    }
    this.setWidth();
  }
  setWidth() {
    const { columnModel } = this;
    const printLayout = this.gos.isDomLayout("print");
    const centerWidth = columnModel.getBodyContainerWidth();
    const leftWidth = columnModel.getDisplayedColumnsLeftWidth();
    const rightWidth = columnModel.getDisplayedColumnsRightWidth();
    let totalWidth;
    if (printLayout) {
      totalWidth = centerWidth + leftWidth + rightWidth;
    } else {
      totalWidth = centerWidth;
      if (this.addSpacer) {
        const relevantWidth = this.gos.get("enableRtl") ? leftWidth : rightWidth;
        if (relevantWidth === 0 && this.scrollVisibleService.isVerticalScrollShowing()) {
          totalWidth += this.gos.getScrollbarWidth();
        }
      }
    }
    this.callback(totalWidth);
  }
};
__decorateClass([
  Autowired("columnModel")
], CenterWidthFeature.prototype, "columnModel", 2);
__decorateClass([
  Autowired("scrollVisibleService")
], CenterWidthFeature.prototype, "scrollVisibleService", 2);
__decorateClass([
  PostConstruct
], CenterWidthFeature.prototype, "postConstruct", 1);

// community-modules/core/src/gridBodyComp/rowContainer/rowContainerCtrl.ts
var RowContainerName = /* @__PURE__ */ ((RowContainerName2) => {
  RowContainerName2["LEFT"] = "left";
  RowContainerName2["RIGHT"] = "right";
  RowContainerName2["CENTER"] = "center";
  RowContainerName2["FULL_WIDTH"] = "fullWidth";
  RowContainerName2["TOP_LEFT"] = "topLeft";
  RowContainerName2["TOP_RIGHT"] = "topRight";
  RowContainerName2["TOP_CENTER"] = "topCenter";
  RowContainerName2["TOP_FULL_WIDTH"] = "topFullWidth";
  RowContainerName2["STICKY_TOP_LEFT"] = "stickyTopLeft";
  RowContainerName2["STICKY_TOP_RIGHT"] = "stickyTopRight";
  RowContainerName2["STICKY_TOP_CENTER"] = "stickyTopCenter";
  RowContainerName2["STICKY_TOP_FULL_WIDTH"] = "stickyTopFullWidth";
  RowContainerName2["STICKY_BOTTOM_LEFT"] = "stickyBottomLeft";
  RowContainerName2["STICKY_BOTTOM_RIGHT"] = "stickyBottomRight";
  RowContainerName2["STICKY_BOTTOM_CENTER"] = "stickyBottomCenter";
  RowContainerName2["STICKY_BOTTOM_FULL_WIDTH"] = "stickyBottomFullWidth";
  RowContainerName2["BOTTOM_LEFT"] = "bottomLeft";
  RowContainerName2["BOTTOM_RIGHT"] = "bottomRight";
  RowContainerName2["BOTTOM_CENTER"] = "bottomCenter";
  RowContainerName2["BOTTOM_FULL_WIDTH"] = "bottomFullWidth";
  return RowContainerName2;
})(RowContainerName || {});
var RowContainerType = /* @__PURE__ */ ((RowContainerType3) => {
  RowContainerType3["LEFT"] = "left";
  RowContainerType3["RIGHT"] = "right";
  RowContainerType3["CENTER"] = "center";
  RowContainerType3["FULL_WIDTH"] = "fullWidth";
  return RowContainerType3;
})(RowContainerType || {});
function getRowContainerTypeForName(name) {
  switch (name) {
    case "center" /* CENTER */:
    case "topCenter" /* TOP_CENTER */:
    case "stickyTopCenter" /* STICKY_TOP_CENTER */:
    case "bottomCenter" /* BOTTOM_CENTER */:
    case "stickyBottomCenter" /* STICKY_BOTTOM_CENTER */:
      return "center" /* CENTER */;
    case "left" /* LEFT */:
    case "topLeft" /* TOP_LEFT */:
    case "stickyTopLeft" /* STICKY_TOP_LEFT */:
    case "bottomLeft" /* BOTTOM_LEFT */:
    case "stickyBottomLeft" /* STICKY_BOTTOM_LEFT */:
      return "left" /* LEFT */;
    case "right" /* RIGHT */:
    case "topRight" /* TOP_RIGHT */:
    case "stickyTopRight" /* STICKY_TOP_RIGHT */:
    case "bottomRight" /* BOTTOM_RIGHT */:
    case "stickyBottomRight" /* STICKY_BOTTOM_RIGHT */:
      return "right" /* RIGHT */;
    case "fullWidth" /* FULL_WIDTH */:
    case "topFullWidth" /* TOP_FULL_WIDTH */:
    case "stickyTopFullWidth" /* STICKY_TOP_FULL_WIDTH */:
    case "bottomFullWidth" /* BOTTOM_FULL_WIDTH */:
    case "stickyBottomFullWidth" /* STICKY_BOTTOM_FULL_WIDTH */:
      return "fullWidth" /* FULL_WIDTH */;
    default:
      throw Error("Invalid Row Container Type");
  }
}
var ContainerCssClasses = convertToMap([
  ["center" /* CENTER */, "ag-center-cols-container"],
  ["left" /* LEFT */, "ag-pinned-left-cols-container"],
  ["right" /* RIGHT */, "ag-pinned-right-cols-container"],
  ["fullWidth" /* FULL_WIDTH */, "ag-full-width-container"],
  ["topCenter" /* TOP_CENTER */, "ag-floating-top-container"],
  ["topLeft" /* TOP_LEFT */, "ag-pinned-left-floating-top"],
  ["topRight" /* TOP_RIGHT */, "ag-pinned-right-floating-top"],
  ["topFullWidth" /* TOP_FULL_WIDTH */, "ag-floating-top-full-width-container"],
  ["stickyTopCenter" /* STICKY_TOP_CENTER */, "ag-sticky-top-container"],
  ["stickyTopLeft" /* STICKY_TOP_LEFT */, "ag-pinned-left-sticky-top"],
  ["stickyTopRight" /* STICKY_TOP_RIGHT */, "ag-pinned-right-sticky-top"],
  ["stickyTopFullWidth" /* STICKY_TOP_FULL_WIDTH */, "ag-sticky-top-full-width-container"],
  ["stickyBottomCenter" /* STICKY_BOTTOM_CENTER */, "ag-sticky-bottom-container"],
  ["stickyBottomLeft" /* STICKY_BOTTOM_LEFT */, "ag-pinned-left-sticky-bottom"],
  ["stickyBottomRight" /* STICKY_BOTTOM_RIGHT */, "ag-pinned-right-sticky-bottom"],
  ["stickyBottomFullWidth" /* STICKY_BOTTOM_FULL_WIDTH */, "ag-sticky-bottom-full-width-container"],
  ["bottomCenter" /* BOTTOM_CENTER */, "ag-floating-bottom-container"],
  ["bottomLeft" /* BOTTOM_LEFT */, "ag-pinned-left-floating-bottom"],
  ["bottomRight" /* BOTTOM_RIGHT */, "ag-pinned-right-floating-bottom"],
  ["bottomFullWidth" /* BOTTOM_FULL_WIDTH */, "ag-floating-bottom-full-width-container"]
]);
var ViewportCssClasses = convertToMap([
  ["center" /* CENTER */, "ag-center-cols-viewport"],
  ["topCenter" /* TOP_CENTER */, "ag-floating-top-viewport"],
  ["stickyTopCenter" /* STICKY_TOP_CENTER */, "ag-sticky-top-viewport"],
  ["bottomCenter" /* BOTTOM_CENTER */, "ag-floating-bottom-viewport"],
  ["stickyBottomCenter" /* STICKY_BOTTOM_CENTER */, "ag-sticky-bottom-viewport"]
]);
var _RowContainerCtrl = class _RowContainerCtrl extends BeanStub {
  constructor(name) {
    super();
    this.visible = true;
    // Maintaining a constant reference enables optimization in React.
    this.EMPTY_CTRLS = [];
    this.name = name;
    this.isFullWithContainer = this.name === "topFullWidth" /* TOP_FULL_WIDTH */ || this.name === "stickyTopFullWidth" /* STICKY_TOP_FULL_WIDTH */ || this.name === "stickyBottomFullWidth" /* STICKY_BOTTOM_FULL_WIDTH */ || this.name === "bottomFullWidth" /* BOTTOM_FULL_WIDTH */ || this.name === "fullWidth" /* FULL_WIDTH */;
  }
  static getRowContainerCssClasses(name) {
    const containerClass = ContainerCssClasses.get(name);
    const viewportClass = ViewportCssClasses.get(name);
    return { container: containerClass, viewport: viewportClass };
  }
  static getPinned(name) {
    switch (name) {
      case "bottomLeft" /* BOTTOM_LEFT */:
      case "topLeft" /* TOP_LEFT */:
      case "stickyTopLeft" /* STICKY_TOP_LEFT */:
      case "stickyBottomLeft" /* STICKY_BOTTOM_LEFT */:
      case "left" /* LEFT */:
        return "left";
      case "bottomRight" /* BOTTOM_RIGHT */:
      case "topRight" /* TOP_RIGHT */:
      case "stickyTopRight" /* STICKY_TOP_RIGHT */:
      case "stickyBottomRight" /* STICKY_BOTTOM_RIGHT */:
      case "right" /* RIGHT */:
        return "right";
      default:
        return null;
    }
  }
  postConstruct() {
    this.enableRtl = this.gos.get("enableRtl");
    this.forContainers(
      ["center" /* CENTER */],
      () => this.viewportSizeFeature = this.createManagedBean(new ViewportSizeFeature(this))
    );
  }
  registerWithCtrlsService() {
    switch (this.name) {
      case "fullWidth" /* FULL_WIDTH */:
      case "topFullWidth" /* TOP_FULL_WIDTH */:
      case "stickyTopFullWidth" /* STICKY_TOP_FULL_WIDTH */:
      case "bottomFullWidth" /* BOTTOM_FULL_WIDTH */:
      case "stickyBottomFullWidth" /* STICKY_BOTTOM_FULL_WIDTH */:
        return;
      default: {
        this.ctrlsService.register(this.name, this);
      }
    }
  }
  forContainers(names, callback) {
    if (names.indexOf(this.name) >= 0) {
      callback();
    }
  }
  getContainerElement() {
    return this.eContainer;
  }
  getViewportSizeFeature() {
    return this.viewportSizeFeature;
  }
  setComp(view, eContainer, eViewport) {
    this.comp = view;
    this.eContainer = eContainer;
    this.eViewport = eViewport;
    this.createManagedBean(new RowContainerEventsFeature(this.eContainer));
    this.addPreventScrollWhileDragging();
    this.listenOnDomOrder();
    this.stopHScrollOnPinnedRows();
    const allTopNoFW = ["topCenter" /* TOP_CENTER */, "topLeft" /* TOP_LEFT */, "topRight" /* TOP_RIGHT */];
    const allStickyTopNoFW = ["stickyTopCenter" /* STICKY_TOP_CENTER */, "stickyTopLeft" /* STICKY_TOP_LEFT */, "stickyTopRight" /* STICKY_TOP_RIGHT */];
    const allStickyBottomNoFW = ["stickyBottomCenter" /* STICKY_BOTTOM_CENTER */, "stickyBottomLeft" /* STICKY_BOTTOM_LEFT */, "stickyBottomRight" /* STICKY_BOTTOM_RIGHT */];
    const allBottomNoFW = ["bottomCenter" /* BOTTOM_CENTER */, "bottomLeft" /* BOTTOM_LEFT */, "bottomRight" /* BOTTOM_RIGHT */];
    const allMiddleNoFW = ["center" /* CENTER */, "left" /* LEFT */, "right" /* RIGHT */];
    const allNoFW = [...allTopNoFW, ...allBottomNoFW, ...allMiddleNoFW, ...allStickyTopNoFW, ...allStickyBottomNoFW];
    const allMiddle = ["center" /* CENTER */, "left" /* LEFT */, "right" /* RIGHT */, "fullWidth" /* FULL_WIDTH */];
    const allCenter = ["center" /* CENTER */, "topCenter" /* TOP_CENTER */, "stickyTopCenter" /* STICKY_TOP_CENTER */, "bottomCenter" /* BOTTOM_CENTER */, "stickyBottomCenter" /* STICKY_BOTTOM_CENTER */];
    const allLeft = ["left" /* LEFT */, "bottomLeft" /* BOTTOM_LEFT */, "topLeft" /* TOP_LEFT */, "stickyTopLeft" /* STICKY_TOP_LEFT */, "stickyBottomLeft" /* STICKY_BOTTOM_LEFT */];
    const allRight = ["right" /* RIGHT */, "bottomRight" /* BOTTOM_RIGHT */, "topRight" /* TOP_RIGHT */, "stickyTopRight" /* STICKY_TOP_RIGHT */, "stickyBottomRight" /* STICKY_BOTTOM_RIGHT */];
    this.forContainers(allLeft, () => {
      this.pinnedWidthFeature = this.createManagedBean(new SetPinnedLeftWidthFeature(this.eContainer));
      this.addManagedListener(this.eventService, Events.EVENT_LEFT_PINNED_WIDTH_CHANGED, () => this.onPinnedWidthChanged());
    });
    this.forContainers(allRight, () => {
      this.pinnedWidthFeature = this.createManagedBean(new SetPinnedRightWidthFeature(this.eContainer));
      this.addManagedListener(this.eventService, Events.EVENT_RIGHT_PINNED_WIDTH_CHANGED, () => this.onPinnedWidthChanged());
    });
    this.forContainers(allMiddle, () => this.createManagedBean(new SetHeightFeature(this.eContainer, this.name === "center" /* CENTER */ ? eViewport : void 0)));
    this.forContainers(allNoFW, () => this.createManagedBean(new DragListenerFeature(this.eContainer)));
    this.forContainers(allCenter, () => this.createManagedBean(
      new CenterWidthFeature((width) => this.comp.setContainerWidth(`${width}px`))
    ));
    this.addListeners();
    this.registerWithCtrlsService();
  }
  addListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, () => this.onDisplayedColumnsChanged());
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, () => this.onDisplayedColumnsWidthChanged());
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_ROWS_CHANGED, (params) => this.onDisplayedRowsChanged(params.afterScroll));
    this.onDisplayedColumnsChanged();
    this.onDisplayedColumnsWidthChanged();
    this.onDisplayedRowsChanged();
  }
  listenOnDomOrder() {
    const allStickyContainers = [
      "stickyTopCenter" /* STICKY_TOP_CENTER */,
      "stickyTopLeft" /* STICKY_TOP_LEFT */,
      "stickyTopRight" /* STICKY_TOP_RIGHT */,
      "stickyTopFullWidth" /* STICKY_TOP_FULL_WIDTH */,
      "stickyBottomCenter" /* STICKY_BOTTOM_CENTER */,
      "stickyBottomLeft" /* STICKY_BOTTOM_LEFT */,
      "stickyBottomRight" /* STICKY_BOTTOM_RIGHT */,
      "stickyBottomFullWidth" /* STICKY_BOTTOM_FULL_WIDTH */
    ];
    const isStickContainer = allStickyContainers.indexOf(this.name) >= 0;
    if (isStickContainer) {
      this.comp.setDomOrder(true);
      return;
    }
    const listener = () => {
      const isEnsureDomOrder = this.gos.get("ensureDomOrder");
      const isPrintLayout = this.gos.isDomLayout("print");
      this.comp.setDomOrder(isEnsureDomOrder || isPrintLayout);
    };
    this.addManagedPropertyListener("domLayout", listener);
    listener();
  }
  // when editing a pinned row, if the cell is half outside the scrollable area, the browser can
  // scroll the column into view. we do not want this, the pinned sections should never scroll.
  // so we listen to scrolls on these containers and reset the scroll if we find one.
  stopHScrollOnPinnedRows() {
    this.forContainers([
      "topCenter" /* TOP_CENTER */,
      "stickyTopCenter" /* STICKY_TOP_CENTER */,
      "bottomCenter" /* BOTTOM_CENTER */,
      "stickyBottomCenter" /* STICKY_BOTTOM_CENTER */
    ], () => {
      const resetScrollLeft = () => this.eViewport.scrollLeft = 0;
      this.addManagedListener(this.eViewport, "scroll", resetScrollLeft);
    });
  }
  onDisplayedColumnsChanged() {
    this.forContainers(["center" /* CENTER */], () => this.onHorizontalViewportChanged());
  }
  onDisplayedColumnsWidthChanged() {
    this.forContainers(["center" /* CENTER */], () => this.onHorizontalViewportChanged());
  }
  // this methods prevents the grid views from being scrolled while the dragService is being used
  // eg. the view should not scroll up and down while dragging rows using the rowDragComp.
  addPreventScrollWhileDragging() {
    const preventScroll = (e) => {
      if (this.dragService.isDragging()) {
        if (e.cancelable) {
          e.preventDefault();
        }
      }
    };
    this.eContainer.addEventListener("touchmove", preventScroll, { passive: false });
    this.addDestroyFunc(() => this.eContainer.removeEventListener("touchmove", preventScroll));
  }
  // this gets called whenever a change in the viewport, so we can inform column controller it has to work
  // out the virtual columns again. gets called from following locations:
  // + ensureColVisible, scroll, init, layoutChanged, displayedColumnsChanged
  onHorizontalViewportChanged(afterScroll = false) {
    const scrollWidth = this.getCenterWidth();
    const scrollPosition = this.getCenterViewportScrollLeft();
    this.columnModel.setViewportPosition(scrollWidth, scrollPosition, afterScroll);
  }
  getCenterWidth() {
    return getInnerWidth(this.eViewport);
  }
  getCenterViewportScrollLeft() {
    return getScrollLeft(this.eViewport, this.enableRtl);
  }
  registerViewportResizeListener(listener) {
    const unsubscribeFromResize = this.resizeObserverService.observeResize(this.eViewport, listener);
    this.addDestroyFunc(() => unsubscribeFromResize());
  }
  isViewportInTheDOMTree() {
    return isInDOM(this.eViewport);
  }
  getViewportScrollLeft() {
    return getScrollLeft(this.eViewport, this.enableRtl);
  }
  isHorizontalScrollShowing() {
    const isAlwaysShowHorizontalScroll = this.gos.get("alwaysShowHorizontalScroll");
    return isAlwaysShowHorizontalScroll || isHorizontalScrollShowing(this.eViewport);
  }
  getViewportElement() {
    return this.eViewport;
  }
  setContainerTranslateX(amount) {
    this.eContainer.style.transform = `translateX(${amount}px)`;
  }
  getHScrollPosition() {
    const res = {
      left: this.eViewport.scrollLeft,
      right: this.eViewport.scrollLeft + this.eViewport.offsetWidth
    };
    return res;
  }
  setCenterViewportScrollLeft(value) {
    setScrollLeft(this.eViewport, value, this.enableRtl);
  }
  isContainerVisible() {
    const pinned = _RowContainerCtrl.getPinned(this.name);
    return !pinned || !!this.pinnedWidthFeature && this.pinnedWidthFeature.getWidth() > 0;
  }
  onPinnedWidthChanged() {
    const visible = this.isContainerVisible();
    if (this.visible != visible) {
      this.visible = visible;
      this.onDisplayedRowsChanged();
    }
  }
  onDisplayedRowsChanged(afterScroll = false) {
    const rows = this.getRowCtrls();
    if (!this.visible || rows.length === 0) {
      this.comp.setRowCtrls({ rowCtrls: this.EMPTY_CTRLS });
      return;
    }
    const printLayout = this.gos.isDomLayout("print");
    const embedFullWidthRows = this.gos.get("embedFullWidthRows");
    const embedFW = embedFullWidthRows || printLayout;
    const rowsThisContainer = rows.filter((rowCtrl) => {
      const fullWidthRow = rowCtrl.isFullWidth();
      const match = this.isFullWithContainer ? !embedFW && fullWidthRow : embedFW || !fullWidthRow;
      return match;
    });
    this.comp.setRowCtrls({ rowCtrls: rowsThisContainer, useFlushSync: afterScroll });
  }
  getRowCtrls() {
    switch (this.name) {
      case "topCenter" /* TOP_CENTER */:
      case "topLeft" /* TOP_LEFT */:
      case "topRight" /* TOP_RIGHT */:
      case "topFullWidth" /* TOP_FULL_WIDTH */:
        return this.rowRenderer.getTopRowCtrls();
      case "stickyTopCenter" /* STICKY_TOP_CENTER */:
      case "stickyTopLeft" /* STICKY_TOP_LEFT */:
      case "stickyTopRight" /* STICKY_TOP_RIGHT */:
      case "stickyTopFullWidth" /* STICKY_TOP_FULL_WIDTH */:
        return this.rowRenderer.getStickyTopRowCtrls();
      case "stickyBottomCenter" /* STICKY_BOTTOM_CENTER */:
      case "stickyBottomLeft" /* STICKY_BOTTOM_LEFT */:
      case "stickyBottomRight" /* STICKY_BOTTOM_RIGHT */:
      case "stickyBottomFullWidth" /* STICKY_BOTTOM_FULL_WIDTH */:
        return this.rowRenderer.getStickyBottomRowCtrls();
      case "bottomCenter" /* BOTTOM_CENTER */:
      case "bottomLeft" /* BOTTOM_LEFT */:
      case "bottomRight" /* BOTTOM_RIGHT */:
      case "bottomFullWidth" /* BOTTOM_FULL_WIDTH */:
        return this.rowRenderer.getBottomRowCtrls();
      default:
        return this.rowRenderer.getCentreRowCtrls();
    }
  }
};
__decorateClass([
  Autowired("dragService")
], _RowContainerCtrl.prototype, "dragService", 2);
__decorateClass([
  Autowired("ctrlsService")
], _RowContainerCtrl.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("columnModel")
], _RowContainerCtrl.prototype, "columnModel", 2);
__decorateClass([
  Autowired("resizeObserverService")
], _RowContainerCtrl.prototype, "resizeObserverService", 2);
__decorateClass([
  Autowired("rowRenderer")
], _RowContainerCtrl.prototype, "rowRenderer", 2);
__decorateClass([
  PostConstruct
], _RowContainerCtrl.prototype, "postConstruct", 1);
var RowContainerCtrl = _RowContainerCtrl;

// community-modules/core/src/gridBodyComp/gridBodyComp.ts
var GRID_BODY_TEMPLATE = (
  /* html */
  `<div class="ag-root ag-unselectable" role="treegrid">
        <ag-header-root ref="gridHeader"></ag-header-root>
        <div class="ag-floating-top" ref="eTop" role="presentation">
            <ag-row-container ref="topLeftContainer" name="${"topLeft" /* TOP_LEFT */}"></ag-row-container>
            <ag-row-container ref="topCenterContainer" name="${"topCenter" /* TOP_CENTER */}"></ag-row-container>
            <ag-row-container ref="topRightContainer" name="${"topRight" /* TOP_RIGHT */}"></ag-row-container>
            <ag-row-container ref="topFullWidthContainer" name="${"topFullWidth" /* TOP_FULL_WIDTH */}"></ag-row-container>
        </div>
        <div class="ag-body" ref="eBody" role="presentation">
            <div class="ag-body-viewport" ref="eBodyViewport" role="presentation">
                <ag-row-container ref="leftContainer" name="${"left" /* LEFT */}"></ag-row-container>
                <ag-row-container ref="centerContainer" name="${"center" /* CENTER */}"></ag-row-container>
                <ag-row-container ref="rightContainer" name="${"right" /* RIGHT */}"></ag-row-container>
                <ag-row-container ref="fullWidthContainer" name="${"fullWidth" /* FULL_WIDTH */}"></ag-row-container>
            </div>
            <ag-fake-vertical-scroll></ag-fake-vertical-scroll>
        </div>
        <div class="ag-sticky-top" ref="eStickyTop" role="presentation">
            <ag-row-container ref="stickyTopLeftContainer" name="${"stickyTopLeft" /* STICKY_TOP_LEFT */}"></ag-row-container>
            <ag-row-container ref="stickyTopCenterContainer" name="${"stickyTopCenter" /* STICKY_TOP_CENTER */}"></ag-row-container>
            <ag-row-container ref="stickyTopRightContainer" name="${"stickyTopRight" /* STICKY_TOP_RIGHT */}"></ag-row-container>
            <ag-row-container ref="stickyTopFullWidthContainer" name="${"stickyTopFullWidth" /* STICKY_TOP_FULL_WIDTH */}"></ag-row-container>
        </div>
        <div class="ag-sticky-bottom" ref="eStickyBottom" role="presentation">
            <ag-row-container ref="stickyBottomLeftContainer" name="${"stickyBottomLeft" /* STICKY_BOTTOM_LEFT */}"></ag-row-container>
            <ag-row-container ref="stickyBottomCenterContainer" name="${"stickyBottomCenter" /* STICKY_BOTTOM_CENTER */}"></ag-row-container>
            <ag-row-container ref="stickyBottomRightContainer" name="${"stickyBottomRight" /* STICKY_BOTTOM_RIGHT */}"></ag-row-container>
            <ag-row-container ref="stickyBottomFullWidthContainer" name="${"stickyBottomFullWidth" /* STICKY_BOTTOM_FULL_WIDTH */}"></ag-row-container>
        </div>
        <div class="ag-floating-bottom" ref="eBottom" role="presentation">
            <ag-row-container ref="bottomLeftContainer" name="${"bottomLeft" /* BOTTOM_LEFT */}"></ag-row-container>
            <ag-row-container ref="bottomCenterContainer" name="${"bottomCenter" /* BOTTOM_CENTER */}"></ag-row-container>
            <ag-row-container ref="bottomRightContainer" name="${"bottomRight" /* BOTTOM_RIGHT */}"></ag-row-container>
            <ag-row-container ref="bottomFullWidthContainer" name="${"bottomFullWidth" /* BOTTOM_FULL_WIDTH */}"></ag-row-container>
        </div>
        <ag-fake-horizontal-scroll></ag-fake-horizontal-scroll>
        <ag-overlay-wrapper></ag-overlay-wrapper>
    </div>`
);
var GridBodyComp = class extends Component {
  constructor() {
    super(GRID_BODY_TEMPLATE);
  }
  init() {
    const setHeight = (height, element) => {
      const heightString = `${height}px`;
      element.style.minHeight = heightString;
      element.style.height = heightString;
    };
    const compProxy = {
      setRowAnimationCssOnBodyViewport: (cssClass, animate) => this.setRowAnimationCssOnBodyViewport(cssClass, animate),
      setColumnCount: (count) => setAriaColCount(this.getGui(), count),
      setRowCount: (count) => setAriaRowCount(this.getGui(), count),
      setTopHeight: (height) => setHeight(height, this.eTop),
      setBottomHeight: (height) => setHeight(height, this.eBottom),
      setTopDisplay: (display) => this.eTop.style.display = display,
      setBottomDisplay: (display) => this.eBottom.style.display = display,
      setStickyTopHeight: (height) => this.eStickyTop.style.height = height,
      setStickyTopTop: (top) => this.eStickyTop.style.top = top,
      setStickyTopWidth: (width) => this.eStickyTop.style.width = width,
      setStickyBottomHeight: (height) => this.eStickyBottom.style.height = height,
      setStickyBottomBottom: (bottom) => this.eStickyBottom.style.bottom = bottom,
      setStickyBottomWidth: (width) => this.eStickyBottom.style.width = width,
      setColumnMovingCss: (cssClass, flag) => this.addOrRemoveCssClass(cssClass, flag),
      updateLayoutClasses: (cssClass, params) => {
        const classLists = [
          this.eBodyViewport.classList,
          this.eBody.classList
        ];
        classLists.forEach((classList) => {
          classList.toggle("ag-layout-auto-height" /* AUTO_HEIGHT */, params.autoHeight);
          classList.toggle("ag-layout-normal" /* NORMAL */, params.normal);
          classList.toggle("ag-layout-print" /* PRINT */, params.print);
        });
        this.addOrRemoveCssClass("ag-layout-auto-height" /* AUTO_HEIGHT */, params.autoHeight);
        this.addOrRemoveCssClass("ag-layout-normal" /* NORMAL */, params.normal);
        this.addOrRemoveCssClass("ag-layout-print" /* PRINT */, params.print);
      },
      setAlwaysVerticalScrollClass: (cssClass, on) => this.eBodyViewport.classList.toggle(CSS_CLASS_FORCE_VERTICAL_SCROLL, on),
      registerBodyViewportResizeListener: (listener) => {
        const unsubscribeFromResize = this.resizeObserverService.observeResize(this.eBodyViewport, listener);
        this.addDestroyFunc(() => unsubscribeFromResize());
      },
      setPinnedTopBottomOverflowY: (overflow) => this.eTop.style.overflowY = this.eBottom.style.overflowY = overflow,
      setCellSelectableCss: (cssClass, selectable) => {
        [this.eTop, this.eBodyViewport, this.eBottom].forEach((ct) => ct.classList.toggle(cssClass, selectable));
      },
      setBodyViewportWidth: (width) => this.eBodyViewport.style.width = width
    };
    this.ctrl = this.createManagedBean(new GridBodyCtrl());
    this.ctrl.setComp(
      compProxy,
      this.getGui(),
      this.eBodyViewport,
      this.eTop,
      this.eBottom,
      this.eStickyTop,
      this.eStickyBottom
    );
    if (this.rangeService && this.gos.get("enableRangeSelection") || this.gos.get("rowSelection") === "multiple") {
      setAriaMultiSelectable(this.getGui(), true);
    }
  }
  setRowAnimationCssOnBodyViewport(cssClass, animateRows) {
    const bodyViewportClassList = this.eBodyViewport.classList;
    bodyViewportClassList.toggle("ag-row-animation" /* ANIMATION_ON */, animateRows);
    bodyViewportClassList.toggle("ag-row-no-animation" /* ANIMATION_OFF */, !animateRows);
  }
  getFloatingTopBottom() {
    return [this.eTop, this.eBottom];
  }
};
__decorateClass([
  Autowired("resizeObserverService")
], GridBodyComp.prototype, "resizeObserverService", 2);
__decorateClass([
  Optional("rangeService")
], GridBodyComp.prototype, "rangeService", 2);
__decorateClass([
  RefSelector("eBodyViewport")
], GridBodyComp.prototype, "eBodyViewport", 2);
__decorateClass([
  RefSelector("eStickyTop")
], GridBodyComp.prototype, "eStickyTop", 2);
__decorateClass([
  RefSelector("eStickyBottom")
], GridBodyComp.prototype, "eStickyBottom", 2);
__decorateClass([
  RefSelector("eTop")
], GridBodyComp.prototype, "eTop", 2);
__decorateClass([
  RefSelector("eBottom")
], GridBodyComp.prototype, "eBottom", 2);
__decorateClass([
  RefSelector("gridHeader")
], GridBodyComp.prototype, "headerRootComp", 2);
__decorateClass([
  RefSelector("eBody")
], GridBodyComp.prototype, "eBody", 2);
__decorateClass([
  PostConstruct
], GridBodyComp.prototype, "init", 1);

// community-modules/core/src/gridBodyComp/scrollVisibleService.ts
var ScrollVisibleService = class extends BeanStub {
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, this.onDisplayedColumnsWidthChanged.bind(this));
  }
  onDisplayedColumnsChanged() {
    this.update();
  }
  onDisplayedColumnsWidthChanged() {
    this.update();
  }
  update() {
    if (this.columnAnimationService.isActive()) {
      this.columnAnimationService.executeLaterVMTurn(() => {
        this.columnAnimationService.executeLaterVMTurn(() => this.updateImpl());
      });
    } else {
      this.updateImpl();
    }
  }
  updateImpl() {
    const centerRowCtrl = this.ctrlsService.get("center");
    if (!centerRowCtrl || this.columnAnimationService.isActive()) {
      return;
    }
    const params = {
      horizontalScrollShowing: centerRowCtrl.isHorizontalScrollShowing(),
      verticalScrollShowing: this.isVerticalScrollShowing()
    };
    this.setScrollsVisible(params);
  }
  setScrollsVisible(params) {
    const atLeastOneDifferent = this.horizontalScrollShowing !== params.horizontalScrollShowing || this.verticalScrollShowing !== params.verticalScrollShowing;
    if (atLeastOneDifferent) {
      this.horizontalScrollShowing = params.horizontalScrollShowing;
      this.verticalScrollShowing = params.verticalScrollShowing;
      const event = {
        type: Events.EVENT_SCROLL_VISIBILITY_CHANGED
      };
      this.eventService.dispatchEvent(event);
    }
  }
  // used by pagination service - to know page height
  isHorizontalScrollShowing() {
    return this.horizontalScrollShowing;
  }
  // used by header container
  isVerticalScrollShowing() {
    return this.verticalScrollShowing;
  }
};
__decorateClass([
  Autowired("ctrlsService")
], ScrollVisibleService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("columnAnimationService")
], ScrollVisibleService.prototype, "columnAnimationService", 2);
__decorateClass([
  PostConstruct
], ScrollVisibleService.prototype, "postConstruct", 1);
ScrollVisibleService = __decorateClass([
  Bean("scrollVisibleService")
], ScrollVisibleService);

// community-modules/core/src/gridBodyComp/mouseEventService.ts
var MouseEventService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.gridInstanceId = MouseEventService.gridInstanceSequence.next();
  }
  // we put the instance id onto the main DOM element. this is used for events, when grids are inside grids,
  // so the grid can work out if the even came from this grid or a grid inside this one. see the ctrl+v logic
  // for where this is used.
  stampTopLevelGridCompWithGridInstance(eGridDiv) {
    eGridDiv[MouseEventService.GRID_DOM_KEY] = this.gridInstanceId;
  }
  getRenderedCellForEvent(event) {
    return getCtrlForEventTarget(this.gos, event.target, CellCtrl.DOM_DATA_KEY_CELL_CTRL);
  }
  // walks the path of the event, and returns true if this grid is the first one that it finds. if doing
  // master / detail grids, and a child grid is found, then it returns false. this stops things like copy/paste
  // getting executed on many grids at the same time.
  isEventFromThisGrid(event) {
    const res = this.isElementInThisGrid(event.target);
    return res;
  }
  isElementInThisGrid(element) {
    let pointer = element;
    while (pointer) {
      const instanceId = pointer[MouseEventService.GRID_DOM_KEY];
      if (exists(instanceId)) {
        const eventFromThisGrid = instanceId === this.gridInstanceId;
        return eventFromThisGrid;
      }
      pointer = pointer.parentElement;
    }
    return false;
  }
  getCellPositionForEvent(event) {
    const cellComp = this.getRenderedCellForEvent(event);
    return cellComp ? cellComp.getCellPosition() : null;
  }
  getNormalisedPosition(event) {
    const gridPanelHasScrolls = this.gos.isDomLayout("normal");
    const e = event;
    let x;
    let y;
    if (e.clientX != null || e.clientY != null) {
      x = e.clientX;
      y = e.clientY;
    } else {
      x = e.x;
      y = e.y;
    }
    if (gridPanelHasScrolls) {
      const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
      const vRange = gridBodyCon.getScrollFeature().getVScrollPosition();
      const hRange = gridBodyCon.getScrollFeature().getHScrollPosition();
      x += hRange.left;
      y += vRange.top;
    }
    return { x, y };
  }
};
MouseEventService.gridInstanceSequence = new NumberSequence();
MouseEventService.GRID_DOM_KEY = "__ag_grid_instance";
__decorateClass([
  Autowired("ctrlsService")
], MouseEventService.prototype, "ctrlsService", 2);
MouseEventService = __decorateClass([
  Bean("mouseEventService")
], MouseEventService);

// community-modules/core/src/gridBodyComp/navigationService.ts
var NavigationService = class extends BeanStub {
  constructor() {
    super();
    this.onPageDown = throttle(this.onPageDown, 100);
    this.onPageUp = throttle(this.onPageUp, 100);
  }
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      this.gridBodyCon = p.gridBodyCtrl;
    });
  }
  handlePageScrollingKey(event, fromFullWidth = false) {
    const key = event.key;
    const alt = event.altKey;
    const ctrl = event.ctrlKey || event.metaKey;
    const rangeServiceShouldHandleShift = !!this.rangeService && event.shiftKey;
    const currentCell = this.mouseEventService.getCellPositionForEvent(event);
    let processed = false;
    switch (key) {
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        if (!ctrl && !alt) {
          this.onHomeOrEndKey(key);
          processed = true;
        }
        break;
      case KeyCode.LEFT:
      case KeyCode.RIGHT:
      case KeyCode.UP:
      case KeyCode.DOWN:
        if (!currentCell) {
          return false;
        }
        if (ctrl && !alt && !rangeServiceShouldHandleShift) {
          this.onCtrlUpDownLeftRight(key, currentCell);
          processed = true;
        }
        break;
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_UP:
        if (!ctrl && !alt) {
          processed = this.handlePageUpDown(key, currentCell, fromFullWidth);
        }
        break;
    }
    if (processed) {
      event.preventDefault();
    }
    return processed;
  }
  handlePageUpDown(key, currentCell, fromFullWidth) {
    if (fromFullWidth) {
      currentCell = this.focusService.getFocusedCell();
    }
    if (!currentCell) {
      return false;
    }
    if (key === KeyCode.PAGE_UP) {
      this.onPageUp(currentCell);
    } else {
      this.onPageDown(currentCell);
    }
    return true;
  }
  navigateTo(navigateParams) {
    var _a;
    const { scrollIndex, scrollType, scrollColumn, focusIndex, focusColumn } = navigateParams;
    if (exists(scrollColumn) && !scrollColumn.isPinned()) {
      this.gridBodyCon.getScrollFeature().ensureColumnVisible(scrollColumn);
    }
    if (exists(scrollIndex)) {
      this.gridBodyCon.getScrollFeature().ensureIndexVisible(scrollIndex, scrollType);
    }
    if (!navigateParams.isAsync) {
      this.gridBodyCon.getScrollFeature().ensureIndexVisible(focusIndex);
    }
    this.focusService.setFocusedCell({ rowIndex: focusIndex, column: focusColumn, rowPinned: null, forceBrowserFocus: true });
    (_a = this.rangeService) == null ? void 0 : _a.setRangeToCell({ rowIndex: focusIndex, rowPinned: null, column: focusColumn });
  }
  // this method is throttled, see the `constructor`
  onPageDown(gridCell) {
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    const scrollPosition = gridBodyCon.getScrollFeature().getVScrollPosition();
    const pixelsInOnePage = this.getViewportHeight();
    const pagingPixelOffset = this.paginationProxy.getPixelOffset();
    const currentPageBottomPixel = scrollPosition.top + pixelsInOnePage;
    const currentPageBottomRow = this.paginationProxy.getRowIndexAtPixel(currentPageBottomPixel + pagingPixelOffset);
    if (this.columnModel.isAutoRowHeightActive()) {
      this.navigateToNextPageWithAutoHeight(gridCell, currentPageBottomRow);
    } else {
      this.navigateToNextPage(gridCell, currentPageBottomRow);
    }
  }
  // this method is throttled, see the `constructor`
  onPageUp(gridCell) {
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    const scrollPosition = gridBodyCon.getScrollFeature().getVScrollPosition();
    const pagingPixelOffset = this.paginationProxy.getPixelOffset();
    const currentPageTopPixel = scrollPosition.top;
    const currentPageTopRow = this.paginationProxy.getRowIndexAtPixel(currentPageTopPixel + pagingPixelOffset);
    if (this.columnModel.isAutoRowHeightActive()) {
      this.navigateToNextPageWithAutoHeight(gridCell, currentPageTopRow, true);
    } else {
      this.navigateToNextPage(gridCell, currentPageTopRow, true);
    }
  }
  navigateToNextPage(gridCell, scrollIndex, up = false) {
    const pixelsInOnePage = this.getViewportHeight();
    const firstRow = this.paginationProxy.getPageFirstRow();
    const lastRow = this.paginationProxy.getPageLastRow();
    const pagingPixelOffset = this.paginationProxy.getPixelOffset();
    const currentRowNode = this.paginationProxy.getRow(gridCell.rowIndex);
    const rowPixelDiff = up ? (currentRowNode == null ? void 0 : currentRowNode.rowHeight) - pixelsInOnePage - pagingPixelOffset : pixelsInOnePage - pagingPixelOffset;
    const nextCellPixel = (currentRowNode == null ? void 0 : currentRowNode.rowTop) + rowPixelDiff;
    let focusIndex = this.paginationProxy.getRowIndexAtPixel(nextCellPixel + pagingPixelOffset);
    if (focusIndex === gridCell.rowIndex) {
      const diff = up ? -1 : 1;
      scrollIndex = focusIndex = gridCell.rowIndex + diff;
    }
    let scrollType;
    if (up) {
      scrollType = "bottom";
      if (focusIndex < firstRow) {
        focusIndex = firstRow;
      }
      if (scrollIndex < firstRow) {
        scrollIndex = firstRow;
      }
    } else {
      scrollType = "top";
      if (focusIndex > lastRow) {
        focusIndex = lastRow;
      }
      if (scrollIndex > lastRow) {
        scrollIndex = lastRow;
      }
    }
    if (this.isRowTallerThanView(focusIndex)) {
      scrollIndex = focusIndex;
      scrollType = "top";
    }
    this.navigateTo({
      scrollIndex,
      scrollType,
      scrollColumn: null,
      focusIndex,
      focusColumn: gridCell.column
    });
  }
  navigateToNextPageWithAutoHeight(gridCell, scrollIndex, up = false) {
    this.navigateTo({
      scrollIndex,
      scrollType: up ? "bottom" : "top",
      scrollColumn: null,
      focusIndex: scrollIndex,
      focusColumn: gridCell.column
    });
    setTimeout(() => {
      const focusIndex = this.getNextFocusIndexForAutoHeight(gridCell, up);
      this.navigateTo({
        scrollIndex,
        scrollType: up ? "bottom" : "top",
        scrollColumn: null,
        focusIndex,
        focusColumn: gridCell.column,
        isAsync: true
      });
    }, 50);
  }
  getNextFocusIndexForAutoHeight(gridCell, up = false) {
    var _a;
    const step = up ? -1 : 1;
    const pixelsInOnePage = this.getViewportHeight();
    const lastRowIndex = this.paginationProxy.getPageLastRow();
    let pixelSum = 0;
    let currentIndex = gridCell.rowIndex;
    while (currentIndex >= 0 && currentIndex <= lastRowIndex) {
      const currentCell = this.paginationProxy.getRow(currentIndex);
      if (currentCell) {
        const currentCellHeight = (_a = currentCell.rowHeight) != null ? _a : 0;
        if (pixelSum + currentCellHeight > pixelsInOnePage) {
          break;
        }
        pixelSum += currentCellHeight;
      }
      currentIndex += step;
    }
    return Math.max(0, Math.min(currentIndex, lastRowIndex));
  }
  getViewportHeight() {
    const { gridBodyCtrl, center } = this.ctrlsService.getParams();
    const scrollPosition = gridBodyCtrl.getScrollFeature().getVScrollPosition();
    const scrollbarWidth = this.gos.getScrollbarWidth();
    let pixelsInOnePage = scrollPosition.bottom - scrollPosition.top;
    if (center.isHorizontalScrollShowing()) {
      pixelsInOnePage -= scrollbarWidth;
    }
    return pixelsInOnePage;
  }
  isRowTallerThanView(rowIndex) {
    const rowNode = this.paginationProxy.getRow(rowIndex);
    if (!rowNode) {
      return false;
    }
    const rowHeight = rowNode.rowHeight;
    if (typeof rowHeight !== "number") {
      return false;
    }
    return rowHeight > this.getViewportHeight();
  }
  onCtrlUpDownLeftRight(key, gridCell) {
    const cellToFocus = this.cellNavigationService.getNextCellToFocus(key, gridCell, true);
    const { rowIndex, column } = cellToFocus;
    this.navigateTo({
      scrollIndex: rowIndex,
      scrollType: null,
      scrollColumn: column,
      focusIndex: rowIndex,
      focusColumn: column
    });
  }
  // home brings focus to top left cell, end brings focus to bottom right, grid scrolled to bring
  // same cell into view (which means either scroll all the way up, or all the way down).
  onHomeOrEndKey(key) {
    const homeKey = key === KeyCode.PAGE_HOME;
    const allColumns = this.columnModel.getAllDisplayedColumns();
    const columnToSelect = homeKey ? allColumns[0] : last(allColumns);
    const scrollIndex = homeKey ? this.paginationProxy.getPageFirstRow() : this.paginationProxy.getPageLastRow();
    this.navigateTo({
      scrollIndex,
      scrollType: null,
      scrollColumn: columnToSelect,
      focusIndex: scrollIndex,
      focusColumn: columnToSelect
    });
  }
  // result of keyboard event
  onTabKeyDown(previous, keyboardEvent) {
    const backwards = keyboardEvent.shiftKey;
    const movedToNextCell = this.tabToNextCellCommon(previous, backwards, keyboardEvent);
    if (movedToNextCell !== false) {
      if (movedToNextCell) {
        keyboardEvent.preventDefault();
      }
      return;
    }
    if (backwards) {
      const { rowIndex, rowPinned } = previous.getRowPosition();
      const firstRow = rowPinned ? rowIndex === 0 : rowIndex === this.paginationProxy.getPageFirstRow();
      if (firstRow) {
        if (this.gos.get("headerHeight") === 0 || this.gos.get("suppressHeaderFocus")) {
          this.focusService.focusNextGridCoreContainer(true, true);
        } else {
          keyboardEvent.preventDefault();
          this.focusService.focusPreviousFromFirstCell(keyboardEvent);
        }
      }
    } else {
      if (previous instanceof CellCtrl) {
        previous.focusCell(true);
      }
      if (this.focusService.focusNextGridCoreContainer(backwards)) {
        keyboardEvent.preventDefault();
      }
    }
  }
  // comes from API
  tabToNextCell(backwards, event) {
    const focusedCell = this.focusService.getFocusedCell();
    if (!focusedCell) {
      return false;
    }
    let cellOrRow = this.getCellByPosition(focusedCell);
    if (!cellOrRow) {
      cellOrRow = this.rowRenderer.getRowByPosition(focusedCell);
      if (!cellOrRow || !cellOrRow.isFullWidth()) {
        return false;
      }
    }
    return !!this.tabToNextCellCommon(cellOrRow, backwards, event);
  }
  tabToNextCellCommon(previous, backwards, event) {
    let editing = previous.isEditing();
    if (!editing && previous instanceof CellCtrl) {
      const cell = previous;
      const row = cell.getRowCtrl();
      if (row) {
        editing = row.isEditing();
      }
    }
    let res;
    if (editing) {
      if (this.gos.get("editType") === "fullRow") {
        res = this.moveToNextEditingRow(previous, backwards, event);
      } else {
        res = this.moveToNextEditingCell(previous, backwards, event);
      }
    } else {
      res = this.moveToNextCellNotEditing(previous, backwards);
    }
    if (res === null) {
      return res;
    }
    return res || !!this.focusService.getFocusedHeader();
  }
  // returns null if no navigation should be performed
  moveToNextEditingCell(previousCell, backwards, event = null) {
    const previousPos = previousCell.getCellPosition();
    previousCell.getGui().focus();
    previousCell.stopEditing();
    const nextCell = this.findNextCellToFocusOn(previousPos, backwards, true);
    if (nextCell === false) {
      return null;
    }
    if (nextCell == null) {
      return false;
    }
    nextCell.startEditing(null, true, event);
    nextCell.focusCell(false);
    return true;
  }
  // returns null if no navigation should be performed
  moveToNextEditingRow(previousCell, backwards, event = null) {
    const previousPos = previousCell.getCellPosition();
    const nextCell = this.findNextCellToFocusOn(previousPos, backwards, true);
    if (nextCell === false) {
      return null;
    }
    if (nextCell == null) {
      return false;
    }
    const nextPos = nextCell.getCellPosition();
    const previousEditable = this.isCellEditable(previousPos);
    const nextEditable = this.isCellEditable(nextPos);
    const rowsMatch = nextPos && previousPos.rowIndex === nextPos.rowIndex && previousPos.rowPinned === nextPos.rowPinned;
    if (previousEditable) {
      previousCell.setFocusOutOnEditor();
    }
    if (!rowsMatch) {
      const pRow = previousCell.getRowCtrl();
      pRow.stopEditing();
      const nRow = nextCell.getRowCtrl();
      nRow.startRowEditing(void 0, void 0, event);
    }
    if (nextEditable) {
      nextCell.setFocusInOnEditor();
      nextCell.focusCell();
    } else {
      nextCell.focusCell(true);
    }
    return true;
  }
  // returns null if no navigation should be performed
  moveToNextCellNotEditing(previousCell, backwards) {
    const displayedColumns = this.columnModel.getAllDisplayedColumns();
    let cellPos;
    if (previousCell instanceof RowCtrl) {
      cellPos = __spreadProps(__spreadValues({}, previousCell.getRowPosition()), {
        column: backwards ? displayedColumns[0] : last(displayedColumns)
      });
    } else {
      cellPos = previousCell.getCellPosition();
    }
    const nextCell = this.findNextCellToFocusOn(cellPos, backwards, false);
    if (nextCell === false) {
      return null;
    }
    if (nextCell instanceof CellCtrl) {
      nextCell.focusCell(true);
    } else if (nextCell) {
      return this.tryToFocusFullWidthRow(nextCell.getRowPosition(), backwards);
    }
    return exists(nextCell);
  }
  /**
   * called by the cell, when tab is pressed while editing.
   * @return: RenderedCell when navigation successful, false if navigation should not be performed, otherwise null
   */
  findNextCellToFocusOn(previousPosition, backwards, startEditing) {
    var _a;
    let nextPosition = previousPosition;
    while (true) {
      if (previousPosition !== nextPosition) {
        previousPosition = nextPosition;
      }
      if (!backwards) {
        nextPosition = this.getLastCellOfColSpan(nextPosition);
      }
      nextPosition = this.cellNavigationService.getNextTabbedCell(nextPosition, backwards);
      const userFunc = this.gos.getCallback("tabToNextCell");
      if (exists(userFunc)) {
        const params = {
          backwards,
          editing: startEditing,
          previousCellPosition: previousPosition,
          nextCellPosition: nextPosition ? nextPosition : null
        };
        const userResult = userFunc(params);
        if (userResult === true || userResult === null) {
          if (userResult === null) {
            warnOnce("Returning `null` from tabToNextCell is deprecated. Return `true` to stay on the current cell, or `false` to let the browser handle the tab behaviour.");
          }
          nextPosition = previousPosition;
        } else if (userResult === false) {
          return false;
        } else {
          if (userResult.floating) {
            warnOnce(`tabToNextCellFunc return type should have attributes: rowIndex, rowPinned, column. However you had 'floating', maybe you meant 'rowPinned'?`);
            userResult.rowPinned = userResult.floating;
          }
          nextPosition = {
            rowIndex: userResult.rowIndex,
            column: userResult.column,
            rowPinned: userResult.rowPinned
          };
        }
      }
      if (!nextPosition) {
        return null;
      }
      if (nextPosition.rowIndex < 0) {
        const headerLen = this.headerNavigationService.getHeaderRowCount();
        this.focusService.focusHeaderPosition({
          headerPosition: {
            headerRowIndex: headerLen + nextPosition.rowIndex,
            column: nextPosition.column
          },
          fromCell: true
        });
        return null;
      }
      const fullRowEdit = this.gos.get("editType") === "fullRow";
      if (startEditing && !fullRowEdit) {
        const cellIsEditable = this.isCellEditable(nextPosition);
        if (!cellIsEditable) {
          continue;
        }
      }
      this.ensureCellVisible(nextPosition);
      const nextCell = this.getCellByPosition(nextPosition);
      if (!nextCell) {
        const row = this.rowRenderer.getRowByPosition(nextPosition);
        if (!row || !row.isFullWidth() || startEditing) {
          continue;
        }
        return row;
      }
      if (nextCell.isSuppressNavigable()) {
        continue;
      }
      (_a = this.rangeService) == null ? void 0 : _a.setRangeToCell(nextPosition);
      return nextCell;
    }
  }
  isCellEditable(cell) {
    const rowNode = this.lookupRowNodeForCell(cell);
    if (rowNode) {
      return cell.column.isCellEditable(rowNode);
    }
    return false;
  }
  getCellByPosition(cellPosition) {
    const rowCtrl = this.rowRenderer.getRowByPosition(cellPosition);
    if (!rowCtrl) {
      return null;
    }
    return rowCtrl.getCellCtrl(cellPosition.column);
  }
  lookupRowNodeForCell(cell) {
    if (cell.rowPinned === "top") {
      return this.pinnedRowModel.getPinnedTopRow(cell.rowIndex);
    }
    if (cell.rowPinned === "bottom") {
      return this.pinnedRowModel.getPinnedBottomRow(cell.rowIndex);
    }
    return this.paginationProxy.getRow(cell.rowIndex);
  }
  // we use index for rows, but column object for columns, as the next column (by index) might not
  // be visible (header grouping) so it's not reliable, so using the column object instead.
  navigateToNextCell(event, key, currentCell, allowUserOverride) {
    let nextCell = currentCell;
    let hitEdgeOfGrid = false;
    while (nextCell && (nextCell === currentCell || !this.isValidNavigateCell(nextCell))) {
      if (this.gos.get("enableRtl")) {
        if (key === KeyCode.LEFT) {
          nextCell = this.getLastCellOfColSpan(nextCell);
        }
      } else if (key === KeyCode.RIGHT) {
        nextCell = this.getLastCellOfColSpan(nextCell);
      }
      nextCell = this.cellNavigationService.getNextCellToFocus(key, nextCell);
      hitEdgeOfGrid = missing(nextCell);
    }
    if (hitEdgeOfGrid && event && event.key === KeyCode.UP) {
      nextCell = {
        rowIndex: -1,
        rowPinned: null,
        column: currentCell.column
      };
    }
    if (allowUserOverride) {
      const userFunc = this.gos.getCallback("navigateToNextCell");
      if (exists(userFunc)) {
        const params = {
          key,
          previousCellPosition: currentCell,
          nextCellPosition: nextCell ? nextCell : null,
          event
        };
        const userCell = userFunc(params);
        if (exists(userCell)) {
          if (userCell.floating) {
            warnOnce(`tabToNextCellFunc return type should have attributes: rowIndex, rowPinned, column. However you had 'floating', maybe you meant 'rowPinned'?`);
            userCell.rowPinned = userCell.floating;
          }
          nextCell = {
            rowPinned: userCell.rowPinned,
            rowIndex: userCell.rowIndex,
            column: userCell.column
          };
        } else {
          nextCell = null;
        }
      }
    }
    if (!nextCell) {
      return;
    }
    if (nextCell.rowIndex < 0) {
      const headerLen = this.headerNavigationService.getHeaderRowCount();
      this.focusService.focusHeaderPosition({
        headerPosition: { headerRowIndex: headerLen + nextCell.rowIndex, column: currentCell.column },
        event: event || void 0,
        fromCell: true
      });
      return;
    }
    const normalisedPosition = this.getNormalisedPosition(nextCell);
    if (normalisedPosition) {
      this.focusPosition(normalisedPosition);
    } else {
      this.tryToFocusFullWidthRow(nextCell);
    }
  }
  getNormalisedPosition(cellPosition) {
    this.ensureCellVisible(cellPosition);
    const cellCtrl = this.getCellByPosition(cellPosition);
    if (!cellCtrl) {
      return null;
    }
    cellPosition = cellCtrl.getCellPosition();
    this.ensureCellVisible(cellPosition);
    return cellPosition;
  }
  tryToFocusFullWidthRow(position, backwards = false) {
    const displayedColumns = this.columnModel.getAllDisplayedColumns();
    const rowComp = this.rowRenderer.getRowByPosition(position);
    if (!rowComp || !rowComp.isFullWidth()) {
      return false;
    }
    const currentCellFocused = this.focusService.getFocusedCell();
    const cellPosition = {
      rowIndex: position.rowIndex,
      rowPinned: position.rowPinned,
      column: position.column || (backwards ? last(displayedColumns) : displayedColumns[0])
    };
    this.focusPosition(cellPosition);
    const fromBelow = currentCellFocused != null ? this.rowPositionUtils.before(cellPosition, currentCellFocused) : false;
    const focusEvent = {
      type: Events.EVENT_FULL_WIDTH_ROW_FOCUSED,
      rowIndex: cellPosition.rowIndex,
      rowPinned: cellPosition.rowPinned,
      column: cellPosition.column,
      isFullWidthCell: true,
      floating: cellPosition.rowPinned,
      fromBelow
    };
    this.eventService.dispatchEvent(focusEvent);
    return true;
  }
  focusPosition(cellPosition) {
    var _a;
    this.focusService.setFocusedCell({
      rowIndex: cellPosition.rowIndex,
      column: cellPosition.column,
      rowPinned: cellPosition.rowPinned,
      forceBrowserFocus: true
    });
    (_a = this.rangeService) == null ? void 0 : _a.setRangeToCell(cellPosition);
  }
  isValidNavigateCell(cell) {
    const rowNode = this.rowPositionUtils.getRowNode(cell);
    return !!rowNode;
  }
  getLastCellOfColSpan(cell) {
    const cellCtrl = this.getCellByPosition(cell);
    if (!cellCtrl) {
      return cell;
    }
    const colSpanningList = cellCtrl.getColSpanningList();
    if (colSpanningList.length === 1) {
      return cell;
    }
    return {
      rowIndex: cell.rowIndex,
      column: last(colSpanningList),
      rowPinned: cell.rowPinned
    };
  }
  ensureCellVisible(gridCell) {
    const isGroupStickyEnabled = this.gos.isGroupRowsSticky();
    const rowNode = this.rowModel.getRow(gridCell.rowIndex);
    const skipScrollToRow = isGroupStickyEnabled && (rowNode == null ? void 0 : rowNode.sticky);
    if (!skipScrollToRow && missing(gridCell.rowPinned)) {
      this.gridBodyCon.getScrollFeature().ensureIndexVisible(gridCell.rowIndex);
    }
    if (!gridCell.column.isPinned()) {
      this.gridBodyCon.getScrollFeature().ensureColumnVisible(gridCell.column);
    }
  }
};
__decorateClass([
  Autowired("mouseEventService")
], NavigationService.prototype, "mouseEventService", 2);
__decorateClass([
  Autowired("paginationProxy")
], NavigationService.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("focusService")
], NavigationService.prototype, "focusService", 2);
__decorateClass([
  Autowired("columnModel")
], NavigationService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("rowModel")
], NavigationService.prototype, "rowModel", 2);
__decorateClass([
  Autowired("ctrlsService")
], NavigationService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("rowRenderer")
], NavigationService.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("headerNavigationService")
], NavigationService.prototype, "headerNavigationService", 2);
__decorateClass([
  Autowired("rowPositionUtils")
], NavigationService.prototype, "rowPositionUtils", 2);
__decorateClass([
  Autowired("cellNavigationService")
], NavigationService.prototype, "cellNavigationService", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], NavigationService.prototype, "pinnedRowModel", 2);
__decorateClass([
  Optional("rangeService")
], NavigationService.prototype, "rangeService", 2);
__decorateClass([
  PostConstruct
], NavigationService.prototype, "postConstruct", 1);
NavigationService = __decorateClass([
  Bean("navigationService")
], NavigationService);

// community-modules/core/src/rendering/cellEditors/popupEditorWrapper.ts
var _PopupEditorWrapper = class _PopupEditorWrapper extends PopupComponent {
  constructor(params) {
    super(
      /* html */
      `<div class="ag-popup-editor" tabindex="-1"/>`
    );
    this.params = params;
  }
  postConstruct() {
    this.gos.setDomData(this.getGui(), _PopupEditorWrapper.DOM_KEY_POPUP_EDITOR_WRAPPER, true);
    this.addKeyDownListener();
  }
  addKeyDownListener() {
    const eGui = this.getGui();
    const params = this.params;
    const listener = (event) => {
      if (!isUserSuppressingKeyboardEvent(this.gos, event, params.node, params.column, true)) {
        params.onKeyDown(event);
      }
    };
    this.addManagedListener(eGui, "keydown", listener);
  }
};
_PopupEditorWrapper.DOM_KEY_POPUP_EDITOR_WRAPPER = "popupEditorWrapper";
__decorateClass([
  PostConstruct
], _PopupEditorWrapper.prototype, "postConstruct", 1);
var PopupEditorWrapper = _PopupEditorWrapper;

// community-modules/core/src/rendering/cell/cellComp.ts
var CellComp = class extends Component {
  constructor(beans, cellCtrl, printLayout, eRow, editingRow) {
    super();
    // every time we go into edit mode, or back again, this gets incremented.
    // it's the components way of dealing with the async nature of framework components,
    // so if a framework component takes a while to be created, we know if the object
    // is still relevant when creating is finished. eg we could click edit / un-edit 20
    // times before the first React edit component comes back - we should discard
    // the first 19.
    this.rendererVersion = 0;
    this.editorVersion = 0;
    this.beans = beans;
    this.column = cellCtrl.getColumn();
    this.rowNode = cellCtrl.getRowNode();
    this.rowCtrl = cellCtrl.getRowCtrl();
    this.eRow = eRow;
    this.cellCtrl = cellCtrl;
    const cellDiv = document.createElement("div");
    cellDiv.setAttribute("comp-id", `${this.getCompId()}`);
    this.setTemplateFromElement(cellDiv);
    const eGui = this.getGui();
    this.forceWrapper = cellCtrl.isForceWrapper();
    this.refreshWrapper(false);
    const setAttribute = (name, value) => {
      if (value != null && value != "") {
        eGui.setAttribute(name, value);
      } else {
        eGui.removeAttribute(name);
      }
    };
    setAriaRole(eGui, cellCtrl.getCellAriaRole());
    setAttribute("col-id", cellCtrl.getColumnIdSanitised());
    const tabIndex = cellCtrl.getTabIndex();
    if (tabIndex !== void 0) {
      setAttribute("tabindex", tabIndex.toString());
    }
    const compProxy = {
      addOrRemoveCssClass: (cssClassName, on) => this.addOrRemoveCssClass(cssClassName, on),
      setUserStyles: (styles) => addStylesToElement(eGui, styles),
      getFocusableElement: () => this.getFocusableElement(),
      setIncludeSelection: (include) => this.includeSelection = include,
      setIncludeRowDrag: (include) => this.includeRowDrag = include,
      setIncludeDndSource: (include) => this.includeDndSource = include,
      setRenderDetails: (compDetails, valueToDisplay, force) => this.setRenderDetails(compDetails, valueToDisplay, force),
      setEditDetails: (compDetails, popup, position) => this.setEditDetails(compDetails, popup, position),
      getCellEditor: () => this.cellEditor || null,
      getCellRenderer: () => this.cellRenderer || null,
      getParentOfValue: () => this.getParentOfValue()
    };
    cellCtrl.setComp(compProxy, this.getGui(), this.eCellWrapper, printLayout, editingRow);
  }
  getParentOfValue() {
    if (this.eCellValue) {
      return this.eCellValue;
    }
    if (this.eCellWrapper) {
      return this.eCellWrapper;
    }
    return this.getGui();
  }
  setRenderDetails(compDetails, valueToDisplay, forceNewCellRendererInstance) {
    const isInlineEditing = this.cellEditor && !this.cellEditorPopupWrapper;
    if (isInlineEditing) {
      return;
    }
    this.firstRender = this.firstRender == null;
    const controlWrapperChanged = this.refreshWrapper(false);
    this.refreshEditStyles(false);
    if (compDetails) {
      const neverRefresh = forceNewCellRendererInstance || controlWrapperChanged;
      const cellRendererRefreshSuccessful = neverRefresh ? false : this.refreshCellRenderer(compDetails);
      if (!cellRendererRefreshSuccessful) {
        this.destroyRenderer();
        this.createCellRendererInstance(compDetails);
      }
    } else {
      this.destroyRenderer();
      this.insertValueWithoutCellRenderer(valueToDisplay);
    }
  }
  setEditDetails(compDetails, popup, position) {
    if (compDetails) {
      this.createCellEditorInstance(compDetails, popup, position);
    } else {
      this.destroyEditor();
    }
  }
  removeControls() {
    this.checkboxSelectionComp = this.beans.context.destroyBean(this.checkboxSelectionComp);
    this.dndSourceComp = this.beans.context.destroyBean(this.dndSourceComp);
    this.rowDraggingComp = this.beans.context.destroyBean(this.rowDraggingComp);
  }
  // returns true if wrapper was changed
  refreshWrapper(editing) {
    const providingControls = this.includeRowDrag || this.includeDndSource || this.includeSelection;
    const usingWrapper = providingControls || this.forceWrapper;
    const putWrapperIn = usingWrapper && this.eCellWrapper == null;
    if (putWrapperIn) {
      const wrapperDiv = document.createElement("div");
      wrapperDiv.setAttribute("role", "presentation");
      wrapperDiv.setAttribute("class", "ag-cell-wrapper");
      this.eCellWrapper = wrapperDiv;
      this.getGui().appendChild(this.eCellWrapper);
    }
    const takeWrapperOut = !usingWrapper && this.eCellWrapper != null;
    if (takeWrapperOut) {
      removeFromParent(this.eCellWrapper);
      this.eCellWrapper = void 0;
    }
    this.addOrRemoveCssClass("ag-cell-value", !usingWrapper);
    const usingCellValue = !editing && usingWrapper;
    const putCellValueIn = usingCellValue && this.eCellValue == null;
    if (putCellValueIn) {
      const cellSpan = document.createElement("span");
      cellSpan.setAttribute("role", "presentation");
      cellSpan.setAttribute("class", "ag-cell-value");
      this.eCellValue = cellSpan;
      this.eCellWrapper.appendChild(this.eCellValue);
    }
    const takeCellValueOut = !usingCellValue && this.eCellValue != null;
    if (takeCellValueOut) {
      removeFromParent(this.eCellValue);
      this.eCellValue = void 0;
    }
    const templateChanged = putWrapperIn || takeWrapperOut || putCellValueIn || takeCellValueOut;
    if (templateChanged) {
      this.removeControls();
    }
    if (!editing) {
      if (providingControls) {
        this.addControls();
      }
    }
    return templateChanged;
  }
  addControls() {
    if (this.includeRowDrag) {
      if (this.rowDraggingComp == null) {
        this.rowDraggingComp = this.cellCtrl.createRowDragComp();
        if (this.rowDraggingComp) {
          this.eCellWrapper.insertBefore(this.rowDraggingComp.getGui(), this.eCellValue);
        }
      }
    }
    if (this.includeDndSource) {
      if (this.dndSourceComp == null) {
        this.dndSourceComp = this.cellCtrl.createDndSource();
        this.eCellWrapper.insertBefore(this.dndSourceComp.getGui(), this.eCellValue);
      }
    }
    if (this.includeSelection) {
      if (this.checkboxSelectionComp == null) {
        this.checkboxSelectionComp = this.cellCtrl.createSelectionCheckbox();
        this.eCellWrapper.insertBefore(this.checkboxSelectionComp.getGui(), this.eCellValue);
      }
    }
  }
  createCellEditorInstance(compDetails, popup, position) {
    const versionCopy = this.editorVersion;
    const cellEditorPromise = compDetails.newAgStackInstance();
    if (!cellEditorPromise) {
      return;
    }
    const { params } = compDetails;
    cellEditorPromise.then((c) => this.afterCellEditorCreated(versionCopy, c, params, popup, position));
    const cellEditorAsync = missing(this.cellEditor);
    if (cellEditorAsync && params.cellStartedEdit) {
      this.cellCtrl.focusCell(true);
    }
  }
  insertValueWithoutCellRenderer(valueToDisplay) {
    const eParent = this.getParentOfValue();
    clearElement(eParent);
    const escapedValue = valueToDisplay != null ? escapeString(valueToDisplay, true) : null;
    if (escapedValue != null) {
      eParent.textContent = escapedValue;
    }
  }
  destroyEditorAndRenderer() {
    this.destroyRenderer();
    this.destroyEditor();
  }
  destroyRenderer() {
    const { context } = this.beans;
    this.cellRenderer = context.destroyBean(this.cellRenderer);
    removeFromParent(this.cellRendererGui);
    this.cellRendererGui = null;
    this.rendererVersion++;
  }
  destroyEditor() {
    const { context } = this.beans;
    if (this.hideEditorPopup) {
      this.hideEditorPopup();
    }
    this.hideEditorPopup = void 0;
    this.cellEditor = context.destroyBean(this.cellEditor);
    this.cellEditorPopupWrapper = context.destroyBean(this.cellEditorPopupWrapper);
    removeFromParent(this.cellEditorGui);
    this.cellEditorGui = null;
    this.editorVersion++;
  }
  refreshCellRenderer(compClassAndParams) {
    if (this.cellRenderer == null || this.cellRenderer.refresh == null) {
      return false;
    }
    if (this.cellRendererClass !== compClassAndParams.componentClass) {
      return false;
    }
    const result = this.cellRenderer.refresh(compClassAndParams.params);
    return result === true || result === void 0;
  }
  createCellRendererInstance(compDetails) {
    const suppressAnimationFrame = this.beans.gos.get("suppressAnimationFrame");
    const useTaskService = !suppressAnimationFrame;
    const displayComponentVersionCopy = this.rendererVersion;
    const { componentClass } = compDetails;
    const createCellRendererFunc = () => {
      const staleTask = this.rendererVersion !== displayComponentVersionCopy || !this.isAlive();
      if (staleTask) {
        return;
      }
      const componentPromise = compDetails.newAgStackInstance();
      const callback = this.afterCellRendererCreated.bind(this, displayComponentVersionCopy, componentClass);
      if (componentPromise) {
        componentPromise.then(callback);
      }
    };
    if (useTaskService && this.firstRender) {
      this.beans.animationFrameService.createTask(createCellRendererFunc, this.rowNode.rowIndex, "createTasksP2");
    } else {
      createCellRendererFunc();
    }
  }
  getCtrl() {
    return this.cellCtrl;
  }
  getRowCtrl() {
    return this.rowCtrl;
  }
  getCellRenderer() {
    return this.cellRenderer;
  }
  getCellEditor() {
    return this.cellEditor;
  }
  afterCellRendererCreated(cellRendererVersion, cellRendererClass, cellRenderer) {
    const staleTask = !this.isAlive() || cellRendererVersion !== this.rendererVersion;
    if (staleTask) {
      this.beans.context.destroyBean(cellRenderer);
      return;
    }
    this.cellRenderer = cellRenderer;
    this.cellRendererClass = cellRendererClass;
    this.cellRendererGui = this.cellRenderer.getGui();
    if (this.cellRendererGui != null) {
      const eParent = this.getParentOfValue();
      clearElement(eParent);
      eParent.appendChild(this.cellRendererGui);
    }
  }
  afterCellEditorCreated(requestVersion, cellEditor, params, popup, position) {
    const staleComp = requestVersion !== this.editorVersion;
    if (staleComp) {
      this.beans.context.destroyBean(cellEditor);
      return;
    }
    const editingCancelledByUserComp = cellEditor.isCancelBeforeStart && cellEditor.isCancelBeforeStart();
    if (editingCancelledByUserComp) {
      this.beans.context.destroyBean(cellEditor);
      this.cellCtrl.stopEditing(true);
      return;
    }
    if (!cellEditor.getGui) {
      console.warn(`AG Grid: cellEditor for column ${this.column.getId()} is missing getGui() method`);
      this.beans.context.destroyBean(cellEditor);
      return;
    }
    this.cellEditor = cellEditor;
    this.cellEditorGui = cellEditor.getGui();
    const cellEditorInPopup = popup || cellEditor.isPopup !== void 0 && cellEditor.isPopup();
    if (cellEditorInPopup) {
      this.addPopupCellEditor(params, position);
    } else {
      this.addInCellEditor();
    }
    this.refreshEditStyles(true, cellEditorInPopup);
    if (cellEditor.afterGuiAttached) {
      cellEditor.afterGuiAttached();
    }
  }
  refreshEditStyles(editing, isPopup) {
    var _a;
    this.addOrRemoveCssClass("ag-cell-inline-editing", editing && !isPopup);
    this.addOrRemoveCssClass("ag-cell-popup-editing", editing && !!isPopup);
    this.addOrRemoveCssClass("ag-cell-not-inline-editing", !editing || !!isPopup);
    (_a = this.rowCtrl) == null ? void 0 : _a.setInlineEditingCss(editing);
  }
  addInCellEditor() {
    const eGui = this.getGui();
    if (eGui.contains(this.beans.gos.getActiveDomElement())) {
      eGui.focus();
    }
    this.destroyRenderer();
    this.refreshWrapper(true);
    this.clearParentOfValue();
    if (this.cellEditorGui) {
      const eParent = this.getParentOfValue();
      eParent.appendChild(this.cellEditorGui);
    }
  }
  addPopupCellEditor(params, position) {
    if (this.beans.gos.get("editType") === "fullRow") {
      console.warn("AG Grid: popup cellEditor does not work with fullRowEdit - you cannot use them both - either turn off fullRowEdit, or stop using popup editors.");
    }
    const cellEditor = this.cellEditor;
    this.cellEditorPopupWrapper = this.beans.context.createBean(new PopupEditorWrapper(params));
    const ePopupGui = this.cellEditorPopupWrapper.getGui();
    if (this.cellEditorGui) {
      ePopupGui.appendChild(this.cellEditorGui);
    }
    const popupService = this.beans.popupService;
    const useModelPopup = this.beans.gos.get("stopEditingWhenCellsLoseFocus");
    const positionToUse = position != null ? position : cellEditor.getPopupPosition ? cellEditor.getPopupPosition() : "over";
    const isRtl = this.beans.gos.get("enableRtl");
    const positionParams = {
      ePopup: ePopupGui,
      column: this.column,
      rowNode: this.rowNode,
      type: "popupCellEditor",
      eventSource: this.getGui(),
      position: positionToUse,
      alignSide: isRtl ? "right" : "left",
      keepWithinBounds: true
    };
    const positionCallback = popupService.positionPopupByComponent.bind(popupService, positionParams);
    const translate = this.beans.localeService.getLocaleTextFunc();
    const addPopupRes = popupService.addPopup({
      modal: useModelPopup,
      eChild: ePopupGui,
      closeOnEsc: true,
      closedCallback: () => {
        this.cellCtrl.onPopupEditorClosed();
      },
      anchorToElement: this.getGui(),
      positionCallback,
      ariaLabel: translate("ariaLabelCellEditor", "Cell Editor")
    });
    if (addPopupRes) {
      this.hideEditorPopup = addPopupRes.hideFunc;
    }
  }
  detach() {
    this.eRow.removeChild(this.getGui());
  }
  // if the row is also getting destroyed, then we don't need to remove from dom,
  // as the row will also get removed, so no need to take out the cells from the row
  // if the row is going (removing is an expensive operation, so only need to remove
  // the top part)
  //
  // note - this is NOT called by context, as we don't wire / unwire the CellComp for performance reasons.
  destroy() {
    this.cellCtrl.stopEditing();
    this.destroyEditorAndRenderer();
    this.removeControls();
    super.destroy();
  }
  clearParentOfValue() {
    const eGui = this.getGui();
    if (eGui.contains(this.beans.gos.getActiveDomElement()) && browserSupportsPreventScroll()) {
      eGui.focus({ preventScroll: true });
    }
    clearElement(this.getParentOfValue());
  }
};

// community-modules/core/src/rendering/row/rowComp.ts
var RowComp = class extends Component {
  constructor(ctrl, beans, containerType) {
    super();
    this.cellComps = {};
    this.beans = beans;
    this.rowCtrl = ctrl;
    const rowDiv = document.createElement("div");
    rowDiv.setAttribute("comp-id", `${this.getCompId()}`);
    rowDiv.setAttribute("style", this.getInitialStyle(containerType));
    this.setTemplateFromElement(rowDiv);
    const eGui = this.getGui();
    const style = eGui.style;
    this.domOrder = this.rowCtrl.getDomOrder();
    setAriaRole(eGui, "row");
    const tabIndex = this.rowCtrl.getTabIndex();
    if (tabIndex != null) {
      eGui.setAttribute("tabindex", tabIndex.toString());
    }
    const compProxy = {
      setDomOrder: (domOrder) => this.domOrder = domOrder,
      setCellCtrls: (cellCtrls) => this.setCellCtrls(cellCtrls),
      showFullWidth: (compDetails) => this.showFullWidth(compDetails),
      getFullWidthCellRenderer: () => this.getFullWidthCellRenderer(),
      addOrRemoveCssClass: (name, on) => this.addOrRemoveCssClass(name, on),
      setUserStyles: (styles) => addStylesToElement(eGui, styles),
      setTop: (top) => style.top = top,
      setTransform: (transform) => style.transform = transform,
      setRowIndex: (rowIndex) => eGui.setAttribute("row-index", rowIndex),
      setRowId: (rowId) => eGui.setAttribute("row-id", rowId),
      setRowBusinessKey: (businessKey) => eGui.setAttribute("row-business-key", businessKey),
      refreshFullWidth: (getUpdatedParams) => this.refreshFullWidth(getUpdatedParams)
    };
    ctrl.setComp(compProxy, this.getGui(), containerType);
    this.addDestroyFunc(() => {
      ctrl.unsetComp(containerType);
    });
  }
  getInitialStyle(containerType) {
    const transform = this.rowCtrl.getInitialTransform(containerType);
    return transform ? `transform: ${transform}` : `top: ${this.rowCtrl.getInitialRowTop(containerType)}`;
  }
  showFullWidth(compDetails) {
    const callback = (cellRenderer) => {
      if (this.isAlive()) {
        const eGui = cellRenderer.getGui();
        this.getGui().appendChild(eGui);
        this.rowCtrl.setupDetailRowAutoHeight(eGui);
        this.setFullWidthRowComp(cellRenderer);
      } else {
        this.beans.context.destroyBean(cellRenderer);
      }
    };
    const res = compDetails.newAgStackInstance();
    if (!res) {
      return;
    }
    res.then(callback);
  }
  setCellCtrls(cellCtrls) {
    const cellsToRemove = Object.assign({}, this.cellComps);
    cellCtrls.forEach((cellCtrl) => {
      const key = cellCtrl.getInstanceId();
      const existingCellComp = this.cellComps[key];
      if (existingCellComp == null) {
        this.newCellComp(cellCtrl);
      } else {
        cellsToRemove[key] = null;
      }
    });
    const cellCompsToRemove = getAllValuesInObject(cellsToRemove).filter((cellComp) => cellComp != null);
    this.destroyCells(cellCompsToRemove);
    this.ensureDomOrder(cellCtrls);
  }
  ensureDomOrder(cellCtrls) {
    if (!this.domOrder) {
      return;
    }
    const elementsInOrder = [];
    cellCtrls.forEach((cellCtrl) => {
      const cellComp = this.cellComps[cellCtrl.getInstanceId()];
      if (cellComp) {
        elementsInOrder.push(cellComp.getGui());
      }
    });
    setDomChildOrder(this.getGui(), elementsInOrder);
  }
  newCellComp(cellCtrl) {
    const cellComp = new CellComp(
      this.beans,
      cellCtrl,
      this.rowCtrl.isPrintLayout(),
      this.getGui(),
      this.rowCtrl.isEditing()
    );
    this.cellComps[cellCtrl.getInstanceId()] = cellComp;
    this.getGui().appendChild(cellComp.getGui());
  }
  destroy() {
    super.destroy();
    this.destroyAllCells();
  }
  destroyAllCells() {
    const cellsToDestroy = getAllValuesInObject(this.cellComps).filter((cp) => cp != null);
    this.destroyCells(cellsToDestroy);
  }
  setFullWidthRowComp(fullWidthRowComponent) {
    if (this.fullWidthCellRenderer) {
      console.error("AG Grid - should not be setting fullWidthRowComponent twice");
    }
    this.fullWidthCellRenderer = fullWidthRowComponent;
    this.addDestroyFunc(() => {
      this.fullWidthCellRenderer = this.beans.context.destroyBean(this.fullWidthCellRenderer);
    });
  }
  getFullWidthCellRenderer() {
    return this.fullWidthCellRenderer;
  }
  destroyCells(cellComps) {
    cellComps.forEach((cellComp) => {
      if (!cellComp) {
        return;
      }
      const instanceId = cellComp.getCtrl().getInstanceId();
      if (this.cellComps[instanceId] !== cellComp) {
        return;
      }
      cellComp.detach();
      cellComp.destroy();
      this.cellComps[instanceId] = null;
    });
  }
  refreshFullWidth(getUpdatedParams) {
    const { fullWidthCellRenderer } = this;
    if (!fullWidthCellRenderer || !fullWidthCellRenderer.refresh) {
      return false;
    }
    const params = getUpdatedParams();
    return fullWidthCellRenderer.refresh(params);
  }
};

// community-modules/core/src/gridBodyComp/rowContainer/rowContainerComp.ts
function templateFactory() {
  const name = Component.elementGettingCreated.getAttribute("name");
  const cssClasses = RowContainerCtrl.getRowContainerCssClasses(name);
  let res;
  const centerTemplate = name === "center" /* CENTER */ || name === "topCenter" /* TOP_CENTER */ || name === "stickyTopCenter" /* STICKY_TOP_CENTER */ || name === "bottomCenter" /* BOTTOM_CENTER */ || name === "stickyBottomCenter" /* STICKY_BOTTOM_CENTER */;
  if (centerTemplate) {
    res = /* html */
    `<div class="${cssClasses.viewport}" ref="eViewport" role="presentation">
                <div class="${cssClasses.container}" ref="eContainer"></div>
            </div>`;
  } else {
    res = /* html */
    `<div class="${cssClasses.container}" ref="eContainer"></div>`;
  }
  return res;
}
var RowContainerComp = class extends Component {
  constructor() {
    super(templateFactory());
    this.rowComps = {};
    this.name = Component.elementGettingCreated.getAttribute("name");
    this.type = getRowContainerTypeForName(this.name);
  }
  postConstruct() {
    const compProxy = {
      setViewportHeight: (height) => this.eViewport.style.height = height,
      setRowCtrls: ({ rowCtrls }) => this.setRowCtrls(rowCtrls),
      setDomOrder: (domOrder) => {
        this.domOrder = domOrder;
      },
      setContainerWidth: (width) => this.eContainer.style.width = width
    };
    const ctrl = this.createManagedBean(new RowContainerCtrl(this.name));
    ctrl.setComp(compProxy, this.eContainer, this.eViewport);
  }
  preDestroy() {
    this.setRowCtrls([]);
  }
  setRowCtrls(rowCtrls) {
    const oldRows = __spreadValues({}, this.rowComps);
    this.rowComps = {};
    this.lastPlacedElement = null;
    const processRow = (rowCon) => {
      const instanceId = rowCon.getInstanceId();
      const existingRowComp = oldRows[instanceId];
      if (existingRowComp) {
        this.rowComps[instanceId] = existingRowComp;
        delete oldRows[instanceId];
        this.ensureDomOrder(existingRowComp.getGui());
      } else {
        if (!rowCon.getRowNode().displayed) {
          return;
        }
        const rowComp = new RowComp(rowCon, this.beans, this.type);
        this.rowComps[instanceId] = rowComp;
        this.appendRow(rowComp.getGui());
      }
    };
    rowCtrls.forEach(processRow);
    getAllValuesInObject(oldRows).forEach((oldRowComp) => {
      this.eContainer.removeChild(oldRowComp.getGui());
      oldRowComp.destroy();
    });
    setAriaRole(this.eContainer, "rowgroup");
  }
  appendRow(element) {
    if (this.domOrder) {
      insertWithDomOrder(this.eContainer, element, this.lastPlacedElement);
    } else {
      this.eContainer.appendChild(element);
    }
    this.lastPlacedElement = element;
  }
  ensureDomOrder(eRow) {
    if (this.domOrder) {
      ensureDomOrder(this.eContainer, eRow, this.lastPlacedElement);
      this.lastPlacedElement = eRow;
    }
  }
};
__decorateClass([
  Autowired("beans")
], RowContainerComp.prototype, "beans", 2);
__decorateClass([
  RefSelector("eViewport")
], RowContainerComp.prototype, "eViewport", 2);
__decorateClass([
  RefSelector("eContainer")
], RowContainerComp.prototype, "eContainer", 2);
__decorateClass([
  PostConstruct
], RowContainerComp.prototype, "postConstruct", 1);
__decorateClass([
  PreDestroy
], RowContainerComp.prototype, "preDestroy", 1);

// community-modules/core/src/headerRendering/columnDrag/bodyDropPivotTarget.ts
var BodyDropPivotTarget = class {
  constructor(pinned) {
    this.columnsToAggregate = [];
    this.columnsToGroup = [];
    this.columnsToPivot = [];
    this.pinned = pinned;
  }
  /** Callback for when drag enters */
  onDragEnter(draggingEvent) {
    this.clearColumnsList();
    if (this.gos.get("functionsReadOnly")) {
      return;
    }
    const dragColumns = draggingEvent.dragItem.columns;
    if (!dragColumns) {
      return;
    }
    dragColumns.forEach((column) => {
      if (!column.isPrimary()) {
        return;
      }
      if (column.isAnyFunctionActive()) {
        return;
      }
      if (column.isAllowValue()) {
        this.columnsToAggregate.push(column);
      } else if (column.isAllowRowGroup()) {
        this.columnsToGroup.push(column);
      } else if (column.isAllowPivot()) {
        this.columnsToPivot.push(column);
      }
    });
  }
  getIconName() {
    const totalColumns = this.columnsToAggregate.length + this.columnsToGroup.length + this.columnsToPivot.length;
    if (totalColumns > 0) {
      return this.pinned ? DragAndDropService.ICON_PINNED : DragAndDropService.ICON_MOVE;
    }
    return null;
  }
  /** Callback for when drag leaves */
  onDragLeave(draggingEvent) {
    this.clearColumnsList();
  }
  clearColumnsList() {
    this.columnsToAggregate.length = 0;
    this.columnsToGroup.length = 0;
    this.columnsToPivot.length = 0;
  }
  /** Callback for when dragging */
  onDragging(draggingEvent) {
  }
  /** Callback for when drag stops */
  onDragStop(draggingEvent) {
    if (this.columnsToAggregate.length > 0) {
      this.columnModel.addValueColumns(this.columnsToAggregate, "toolPanelDragAndDrop");
    }
    if (this.columnsToGroup.length > 0) {
      this.columnModel.addRowGroupColumns(this.columnsToGroup, "toolPanelDragAndDrop");
    }
    if (this.columnsToPivot.length > 0) {
      this.columnModel.addPivotColumns(this.columnsToPivot, "toolPanelDragAndDrop");
    }
  }
};
__decorateClass([
  Autowired("columnModel")
], BodyDropPivotTarget.prototype, "columnModel", 2);
__decorateClass([
  Autowired("gridOptionsService")
], BodyDropPivotTarget.prototype, "gos", 2);

// community-modules/core/src/headerRendering/columnMoveHelper.ts
var ColumnMoveHelper = class {
  static attemptMoveColumns(params) {
    const { isFromHeader, hDirection, xPosition, fromEnter, fakeEvent, pinned, gos, columnModel } = params;
    const draggingLeft = hDirection === 0 /* Left */;
    const draggingRight = hDirection === 1 /* Right */;
    let { allMovingColumns } = params;
    if (isFromHeader) {
      let newCols = [];
      allMovingColumns.forEach((col) => {
        var _a;
        let movingGroup = null;
        let parent = col.getParent();
        while (parent != null && parent.getDisplayedLeafColumns().length === 1) {
          movingGroup = parent;
          parent = parent.getParent();
        }
        if (movingGroup != null) {
          const isMarryChildren = !!((_a = movingGroup.getColGroupDef()) == null ? void 0 : _a.marryChildren);
          const columnsToMove = isMarryChildren ? movingGroup.getProvidedColumnGroup().getLeafColumns() : movingGroup.getLeafColumns();
          columnsToMove.forEach((newCol) => {
            if (!newCols.includes(newCol)) {
              newCols.push(newCol);
            }
          });
        } else if (!newCols.includes(col)) {
          newCols.push(col);
        }
      });
      allMovingColumns = newCols;
    }
    const allMovingColumnsOrdered = allMovingColumns.slice();
    columnModel.sortColumnsLikeGridColumns(allMovingColumnsOrdered);
    const validMoves = this.calculateValidMoves({
      movingCols: allMovingColumnsOrdered,
      draggingRight,
      xPosition,
      pinned,
      gos,
      columnModel
    });
    const oldIndex = this.calculateOldIndex(allMovingColumnsOrdered, columnModel);
    if (validMoves.length === 0) {
      return;
    }
    const firstValidMove = validMoves[0];
    let constrainDirection = oldIndex !== null && !fromEnter;
    if (isFromHeader) {
      constrainDirection = oldIndex !== null;
    }
    if (constrainDirection && !fakeEvent) {
      if (draggingLeft && firstValidMove >= oldIndex) {
        return;
      }
      if (draggingRight && firstValidMove <= oldIndex) {
        return;
      }
    }
    const displayedCols = columnModel.getAllDisplayedColumns();
    let potentialMoves = [];
    let targetOrder = null;
    for (let i = 0; i < validMoves.length; i++) {
      const move = validMoves[i];
      const order = columnModel.getProposedColumnOrder(allMovingColumnsOrdered, move);
      if (!columnModel.doesOrderPassRules(order)) {
        continue;
      }
      const displayedOrder = order.filter((col) => displayedCols.includes(col));
      if (targetOrder === null) {
        targetOrder = displayedOrder;
      } else if (!areEqual(displayedOrder, targetOrder)) {
        break;
      }
      const fragCount = this.groupFragCount(order);
      potentialMoves.push({ move, fragCount });
    }
    if (potentialMoves.length === 0) {
      return;
    }
    potentialMoves.sort((a, b) => a.fragCount - b.fragCount);
    return this.moveColumns(allMovingColumns, potentialMoves[0].move, "uiColumnMoved", false, columnModel);
  }
  static moveColumns(columns, toIndex, source, finished, columnModel) {
    columnModel.moveColumns(columns, toIndex, source, finished);
    return finished ? null : { columns, toIndex };
  }
  // returns the index of the first column in the list ONLY if the cols are all beside
  // each other. if the cols are not beside each other, then returns null
  static calculateOldIndex(movingCols, columnModel) {
    const gridCols = columnModel.getAllGridColumns();
    const indexes = sortNumerically(movingCols.map((col) => gridCols.indexOf(col)));
    const firstIndex = indexes[0];
    const lastIndex = last(indexes);
    const spread = lastIndex - firstIndex;
    const gapsExist = spread !== indexes.length - 1;
    return gapsExist ? null : firstIndex;
  }
  // A measure of how fragmented in terms of groups an order of columns is
  static groupFragCount(columns) {
    function parents(col) {
      let result = [];
      let parent = col.getOriginalParent();
      while (parent != null) {
        result.push(parent);
        parent = parent.getOriginalParent();
      }
      return result;
    }
    let count = 0;
    for (let i = 0; i < columns.length - 1; i++) {
      let a = parents(columns[i]);
      let b = parents(columns[i + 1]);
      [a, b] = a.length > b.length ? [a, b] : [b, a];
      a.forEach((parent) => {
        if (b.indexOf(parent) === -1) {
          count++;
        }
      });
    }
    return count;
  }
  static getDisplayedColumns(columnModel, type) {
    switch (type) {
      case "left":
        return columnModel.getDisplayedLeftColumns();
      case "right":
        return columnModel.getDisplayedRightColumns();
      default:
        return columnModel.getDisplayedCenterColumns();
    }
  }
  static calculateValidMoves(params) {
    const { movingCols, draggingRight, xPosition, pinned, gos, columnModel } = params;
    const isMoveBlocked = gos.get("suppressMovableColumns") || movingCols.some((col) => col.getColDef().suppressMovable);
    if (isMoveBlocked) {
      return [];
    }
    const allDisplayedCols = this.getDisplayedColumns(columnModel, pinned);
    const allGridCols = columnModel.getAllGridColumns();
    const movingDisplayedCols = allDisplayedCols.filter((col) => includes(movingCols, col));
    const otherDisplayedCols = allDisplayedCols.filter((col) => !includes(movingCols, col));
    const otherGridCols = allGridCols.filter((col) => !includes(movingCols, col));
    let displayIndex = 0;
    let availableWidth = xPosition;
    if (draggingRight) {
      let widthOfMovingDisplayedCols = 0;
      movingDisplayedCols.forEach((col) => widthOfMovingDisplayedCols += col.getActualWidth());
      availableWidth -= widthOfMovingDisplayedCols;
    }
    if (availableWidth > 0) {
      for (let i = 0; i < otherDisplayedCols.length; i++) {
        const col = otherDisplayedCols[i];
        availableWidth -= col.getActualWidth();
        if (availableWidth < 0) {
          break;
        }
        displayIndex++;
      }
      if (draggingRight) {
        displayIndex++;
      }
    }
    let firstValidMove;
    if (displayIndex > 0) {
      const leftColumn = otherDisplayedCols[displayIndex - 1];
      firstValidMove = otherGridCols.indexOf(leftColumn) + 1;
    } else {
      firstValidMove = otherGridCols.indexOf(otherDisplayedCols[0]);
      if (firstValidMove === -1) {
        firstValidMove = 0;
      }
    }
    const validMoves = [firstValidMove];
    const numberComparator = (a, b) => a - b;
    if (draggingRight) {
      let pointer = firstValidMove + 1;
      const lastIndex = allGridCols.length - 1;
      while (pointer <= lastIndex) {
        validMoves.push(pointer);
        pointer++;
      }
      validMoves.sort(numberComparator);
    } else {
      let pointer = firstValidMove;
      const lastIndex = allGridCols.length - 1;
      let displacedCol = allGridCols[pointer];
      while (pointer <= lastIndex && allDisplayedCols.indexOf(displacedCol) < 0) {
        pointer++;
        validMoves.push(pointer);
        displacedCol = allGridCols[pointer];
      }
      pointer = firstValidMove - 1;
      const firstDisplayIndex = 0;
      while (pointer >= firstDisplayIndex) {
        validMoves.push(pointer);
        pointer--;
      }
      validMoves.sort(numberComparator).reverse();
    }
    return validMoves;
  }
  static normaliseX(x, pinned, fromKeyboard, gos, ctrlsService) {
    const eViewport = ctrlsService.getHeaderRowContainerCtrl(pinned).getViewport();
    if (fromKeyboard) {
      x -= eViewport.getBoundingClientRect().left;
    }
    if (gos.get("enableRtl")) {
      const clientWidth = eViewport.clientWidth;
      x = clientWidth - x;
    }
    if (pinned == null) {
      x += ctrlsService.get("center").getCenterViewportScrollLeft();
    }
    return x;
  }
};

// community-modules/core/src/headerRendering/columnDrag/moveColumnFeature.ts
var MoveColumnFeature = class {
  constructor(pinned) {
    this.needToMoveLeft = false;
    this.needToMoveRight = false;
    this.lastMovedInfo = null;
    this.pinned = pinned;
    this.isCenterContainer = !exists(pinned);
  }
  init() {
    this.ctrlsService.whenReady((p) => {
      this.gridBodyCon = p.gridBodyCtrl;
    });
  }
  getIconName() {
    return this.pinned ? DragAndDropService.ICON_PINNED : DragAndDropService.ICON_MOVE;
  }
  onDragEnter(draggingEvent) {
    const columns = draggingEvent.dragItem.columns;
    const dragCameFromToolPanel = draggingEvent.dragSource.type === 0 /* ToolPanel */;
    if (dragCameFromToolPanel) {
      this.setColumnsVisible(columns, true, "uiColumnDragged");
    } else {
      const visibleState = draggingEvent.dragItem.visibleState;
      const visibleColumns = (columns || []).filter((column) => visibleState[column.getId()]);
      this.setColumnsVisible(visibleColumns, true, "uiColumnDragged");
    }
    this.setColumnsPinned(columns, this.pinned, "uiColumnDragged");
    this.onDragging(draggingEvent, true, true);
  }
  onDragLeave() {
    this.ensureIntervalCleared();
    this.lastMovedInfo = null;
  }
  setColumnsVisible(columns, visible, source) {
    if (columns) {
      const allowedCols = columns.filter((c) => !c.getColDef().lockVisible);
      this.columnModel.setColumnsVisible(allowedCols, visible, source);
    }
  }
  setColumnsPinned(columns, pinned, source) {
    if (columns) {
      const allowedCols = columns.filter((c) => !c.getColDef().lockPinned);
      this.columnModel.setColumnsPinned(allowedCols, pinned, source);
    }
  }
  onDragStop() {
    this.onDragging(this.lastDraggingEvent, false, true, true);
    this.ensureIntervalCleared();
    this.lastMovedInfo = null;
  }
  checkCenterForScrolling(xAdjustedForScroll) {
    if (this.isCenterContainer) {
      const centerCtrl = this.ctrlsService.get("center");
      const firstVisiblePixel = centerCtrl.getCenterViewportScrollLeft();
      const lastVisiblePixel = firstVisiblePixel + centerCtrl.getCenterWidth();
      if (this.gos.get("enableRtl")) {
        this.needToMoveRight = xAdjustedForScroll < firstVisiblePixel + 50;
        this.needToMoveLeft = xAdjustedForScroll > lastVisiblePixel - 50;
      } else {
        this.needToMoveLeft = xAdjustedForScroll < firstVisiblePixel + 50;
        this.needToMoveRight = xAdjustedForScroll > lastVisiblePixel - 50;
      }
      if (this.needToMoveLeft || this.needToMoveRight) {
        this.ensureIntervalStarted();
      } else {
        this.ensureIntervalCleared();
      }
    }
  }
  onDragging(draggingEvent = this.lastDraggingEvent, fromEnter = false, fakeEvent = false, finished = false) {
    var _a;
    if (finished) {
      if (this.lastMovedInfo) {
        const { columns, toIndex } = this.lastMovedInfo;
        ColumnMoveHelper.moveColumns(columns, toIndex, "uiColumnMoved", true, this.columnModel);
      }
      return;
    }
    this.lastDraggingEvent = draggingEvent;
    if (missing(draggingEvent.hDirection)) {
      return;
    }
    const mouseX = ColumnMoveHelper.normaliseX(
      draggingEvent.x,
      this.pinned,
      false,
      this.gos,
      this.ctrlsService
    );
    if (!fromEnter) {
      this.checkCenterForScrolling(mouseX);
    }
    const hDirection = this.normaliseDirection(draggingEvent.hDirection);
    const dragSourceType = draggingEvent.dragSource.type;
    const allMovingColumns = ((_a = draggingEvent.dragSource.getDragItem().columns) == null ? void 0 : _a.filter((col) => {
      if (col.getColDef().lockPinned) {
        return col.getPinned() == this.pinned;
      }
      return true;
    })) || [];
    const lastMovedInfo = ColumnMoveHelper.attemptMoveColumns({
      allMovingColumns,
      isFromHeader: dragSourceType === 1 /* HeaderCell */,
      hDirection,
      xPosition: mouseX,
      pinned: this.pinned,
      fromEnter,
      fakeEvent,
      gos: this.gos,
      columnModel: this.columnModel
    });
    if (lastMovedInfo) {
      this.lastMovedInfo = lastMovedInfo;
    }
  }
  normaliseDirection(hDirection) {
    if (this.gos.get("enableRtl")) {
      switch (hDirection) {
        case 0 /* Left */:
          return 1 /* Right */;
        case 1 /* Right */:
          return 0 /* Left */;
        default:
          console.error(`AG Grid: Unknown direction ${hDirection}`);
      }
    } else {
      return hDirection;
    }
  }
  ensureIntervalStarted() {
    if (!this.movingIntervalId) {
      this.intervalCount = 0;
      this.failedMoveAttempts = 0;
      this.movingIntervalId = window.setInterval(this.moveInterval.bind(this), 100);
      if (this.needToMoveLeft) {
        this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_LEFT, true);
      } else {
        this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_RIGHT, true);
      }
    }
  }
  ensureIntervalCleared() {
    if (this.movingIntervalId) {
      window.clearInterval(this.movingIntervalId);
      this.movingIntervalId = null;
      this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_MOVE);
    }
  }
  moveInterval() {
    let pixelsToMove;
    this.intervalCount++;
    pixelsToMove = 10 + this.intervalCount * 5;
    if (pixelsToMove > 100) {
      pixelsToMove = 100;
    }
    let pixelsMoved = null;
    const scrollFeature = this.gridBodyCon.getScrollFeature();
    if (this.needToMoveLeft) {
      pixelsMoved = scrollFeature.scrollHorizontally(-pixelsToMove);
    } else if (this.needToMoveRight) {
      pixelsMoved = scrollFeature.scrollHorizontally(pixelsToMove);
    }
    if (pixelsMoved !== 0) {
      this.onDragging(this.lastDraggingEvent);
      this.failedMoveAttempts = 0;
    } else {
      this.failedMoveAttempts++;
      const columns = this.lastDraggingEvent.dragItem.columns;
      const columnsThatCanPin = columns.filter((c) => !c.getColDef().lockPinned);
      if (columnsThatCanPin.length > 0) {
        this.dragAndDropService.setGhostIcon(DragAndDropService.ICON_PINNED);
        if (this.failedMoveAttempts > 7) {
          const pinType = this.needToMoveLeft ? "left" : "right";
          this.setColumnsPinned(columnsThatCanPin, pinType, "uiColumnDragged");
          this.dragAndDropService.nudge();
        }
      }
    }
  }
};
__decorateClass([
  Autowired("columnModel")
], MoveColumnFeature.prototype, "columnModel", 2);
__decorateClass([
  Autowired("dragAndDropService")
], MoveColumnFeature.prototype, "dragAndDropService", 2);
__decorateClass([
  Autowired("gridOptionsService")
], MoveColumnFeature.prototype, "gos", 2);
__decorateClass([
  Autowired("ctrlsService")
], MoveColumnFeature.prototype, "ctrlsService", 2);
__decorateClass([
  PostConstruct
], MoveColumnFeature.prototype, "init", 1);

// community-modules/core/src/headerRendering/columnDrag/bodyDropTarget.ts
var BodyDropTarget = class extends BeanStub {
  constructor(pinned, eContainer) {
    super();
    this.pinned = pinned;
    this.eContainer = eContainer;
  }
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      switch (this.pinned) {
        case "left":
          this.eSecondaryContainers = [
            [p.gridBodyCtrl.getBodyViewportElement(), p.left.getContainerElement()],
            [p.bottomLeft.getContainerElement()],
            [p.topLeft.getContainerElement()]
          ];
          break;
        case "right":
          this.eSecondaryContainers = [
            [p.gridBodyCtrl.getBodyViewportElement(), p.right.getContainerElement()],
            [p.bottomRight.getContainerElement()],
            [p.topRight.getContainerElement()]
          ];
          break;
        default:
          this.eSecondaryContainers = [
            [p.gridBodyCtrl.getBodyViewportElement(), p.center.getViewportElement()],
            [p.bottomCenter.getViewportElement()],
            [p.topCenter.getViewportElement()]
          ];
          break;
      }
    });
  }
  isInterestedIn(type) {
    return type === 1 /* HeaderCell */ || type === 0 /* ToolPanel */ && this.gos.get("allowDragFromColumnsToolPanel");
  }
  getSecondaryContainers() {
    return this.eSecondaryContainers;
  }
  getContainer() {
    return this.eContainer;
  }
  init() {
    this.moveColumnFeature = this.createManagedBean(new MoveColumnFeature(this.pinned));
    this.bodyDropPivotTarget = this.createManagedBean(new BodyDropPivotTarget(this.pinned));
    this.dragAndDropService.addDropTarget(this);
  }
  getIconName() {
    return this.currentDropListener.getIconName();
  }
  // we want to use the bodyPivotTarget if the user is dragging columns in from the toolPanel
  // and we are in pivot mode, as it has to logic to set pivot/value/group on the columns when
  // dropped into the grid's body.
  isDropColumnInPivotMode(draggingEvent) {
    return this.columnModel.isPivotMode() && draggingEvent.dragSource.type === 0 /* ToolPanel */;
  }
  onDragEnter(draggingEvent) {
    this.currentDropListener = this.isDropColumnInPivotMode(draggingEvent) ? this.bodyDropPivotTarget : this.moveColumnFeature;
    this.currentDropListener.onDragEnter(draggingEvent);
  }
  onDragLeave(params) {
    this.currentDropListener.onDragLeave(params);
  }
  onDragging(params) {
    this.currentDropListener.onDragging(params);
  }
  onDragStop(params) {
    this.currentDropListener.onDragStop(params);
  }
};
__decorateClass([
  Autowired("dragAndDropService")
], BodyDropTarget.prototype, "dragAndDropService", 2);
__decorateClass([
  Autowired("columnModel")
], BodyDropTarget.prototype, "columnModel", 2);
__decorateClass([
  Autowired("ctrlsService")
], BodyDropTarget.prototype, "ctrlsService", 2);
__decorateClass([
  PostConstruct
], BodyDropTarget.prototype, "postConstruct", 1);
__decorateClass([
  PostConstruct
], BodyDropTarget.prototype, "init", 1);

// community-modules/core/src/headerRendering/cells/column/headerCellComp.ts
var _HeaderCellComp = class _HeaderCellComp extends AbstractHeaderCellComp {
  constructor(ctrl) {
    super(_HeaderCellComp.TEMPLATE, ctrl);
    this.headerCompVersion = 0;
    this.column = ctrl.getColumnGroupChild();
    this.pinned = ctrl.getPinned();
  }
  postConstruct() {
    const eGui = this.getGui();
    const setAttribute = (name, value) => {
      if (value != null && value != "") {
        eGui.setAttribute(name, value);
      } else {
        eGui.removeAttribute(name);
      }
    };
    setAttribute("col-id", this.column.getColId());
    const compProxy = {
      setWidth: (width) => eGui.style.width = width,
      addOrRemoveCssClass: (cssClassName, on) => this.addOrRemoveCssClass(cssClassName, on),
      setAriaSort: (sort) => sort ? setAriaSort(eGui, sort) : removeAriaSort(eGui),
      setUserCompDetails: (compDetails) => this.setUserCompDetails(compDetails),
      getUserCompInstance: () => this.headerComp
    };
    this.ctrl.setComp(compProxy, this.getGui(), this.eResize, this.eHeaderCompWrapper);
    const selectAllGui = this.ctrl.getSelectAllGui();
    this.eResize.insertAdjacentElement("afterend", selectAllGui);
  }
  destroyHeaderComp() {
    if (this.headerComp) {
      this.eHeaderCompWrapper.removeChild(this.headerCompGui);
      this.headerComp = this.destroyBean(this.headerComp);
      this.headerCompGui = void 0;
    }
  }
  setUserCompDetails(compDetails) {
    this.headerCompVersion++;
    const versionCopy = this.headerCompVersion;
    compDetails.newAgStackInstance().then((comp) => this.afterCompCreated(versionCopy, comp));
  }
  afterCompCreated(version, headerComp) {
    if (version != this.headerCompVersion || !this.isAlive()) {
      this.destroyBean(headerComp);
      return;
    }
    this.destroyHeaderComp();
    this.headerComp = headerComp;
    this.headerCompGui = headerComp.getGui();
    this.eHeaderCompWrapper.appendChild(this.headerCompGui);
    this.ctrl.setDragSource(this.getGui());
  }
};
_HeaderCellComp.TEMPLATE = /* html */
`<div class="ag-header-cell" role="columnheader">
            <div ref="eResize" class="ag-header-cell-resize" role="presentation"></div>
            <div ref="eHeaderCompWrapper" class="ag-header-cell-comp-wrapper" role="presentation"></div>
        </div>`;
__decorateClass([
  RefSelector("eResize")
], _HeaderCellComp.prototype, "eResize", 2);
__decorateClass([
  RefSelector("eHeaderCompWrapper")
], _HeaderCellComp.prototype, "eHeaderCompWrapper", 2);
__decorateClass([
  PostConstruct
], _HeaderCellComp.prototype, "postConstruct", 1);
__decorateClass([
  PreDestroy
], _HeaderCellComp.prototype, "destroyHeaderComp", 1);
var HeaderCellComp = _HeaderCellComp;

// community-modules/core/src/headerRendering/cells/columnGroup/headerGroupCellComp.ts
var _HeaderGroupCellComp = class _HeaderGroupCellComp extends AbstractHeaderCellComp {
  constructor(ctrl) {
    super(_HeaderGroupCellComp.TEMPLATE, ctrl);
  }
  postConstruct() {
    const eGui = this.getGui();
    const setAttribute = (key, value) => value != void 0 ? eGui.setAttribute(key, value) : eGui.removeAttribute(key);
    eGui.setAttribute("col-id", this.ctrl.getColId());
    const compProxy = {
      addOrRemoveCssClass: (cssClassName, on) => this.addOrRemoveCssClass(cssClassName, on),
      setResizableDisplayed: (displayed) => setDisplayed(this.eResize, displayed),
      setWidth: (width) => eGui.style.width = width,
      setAriaExpanded: (expanded) => setAttribute("aria-expanded", expanded),
      setUserCompDetails: (details) => this.setUserCompDetails(details),
      getUserCompInstance: () => this.headerGroupComp
    };
    this.ctrl.setComp(compProxy, eGui, this.eResize);
  }
  setUserCompDetails(details) {
    details.newAgStackInstance().then((comp) => this.afterHeaderCompCreated(comp));
  }
  afterHeaderCompCreated(headerGroupComp) {
    const destroyFunc = () => this.destroyBean(headerGroupComp);
    if (!this.isAlive()) {
      destroyFunc();
      return;
    }
    const eGui = this.getGui();
    const eHeaderGroupGui = headerGroupComp.getGui();
    eGui.appendChild(eHeaderGroupGui);
    this.addDestroyFunc(destroyFunc);
    this.headerGroupComp = headerGroupComp;
    this.ctrl.setDragSource(eGui);
  }
};
_HeaderGroupCellComp.TEMPLATE = /* html */
`<div class="ag-header-group-cell" role="columnheader">
            <div ref="eResize" class="ag-header-cell-resize" role="presentation"></div>
        </div>`;
__decorateClass([
  RefSelector("eResize")
], _HeaderGroupCellComp.prototype, "eResize", 2);
__decorateClass([
  PostConstruct
], _HeaderGroupCellComp.prototype, "postConstruct", 1);
var HeaderGroupCellComp = _HeaderGroupCellComp;

// community-modules/core/src/headerRendering/row/headerRowComp.ts
var HeaderRowType = /* @__PURE__ */ ((HeaderRowType2) => {
  HeaderRowType2["COLUMN_GROUP"] = "group";
  HeaderRowType2["COLUMN"] = "column";
  HeaderRowType2["FLOATING_FILTER"] = "filter";
  return HeaderRowType2;
})(HeaderRowType || {});
var HeaderRowComp = class extends Component {
  constructor(ctrl) {
    super();
    this.headerComps = {};
    this.ctrl = ctrl;
    this.setTemplate(
      /* html */
      `<div class="${this.ctrl.getHeaderRowClass()}" role="row"></div>`
    );
  }
  init() {
    setAriaRowIndex(this.getGui(), this.ctrl.getAriaRowIndex());
    const compProxy = {
      setHeight: (height) => this.getGui().style.height = height,
      setTop: (top) => this.getGui().style.top = top,
      setHeaderCtrls: (ctrls, forceOrder) => this.setHeaderCtrls(ctrls, forceOrder),
      setWidth: (width) => this.getGui().style.width = width
    };
    this.ctrl.setComp(compProxy);
  }
  destroyHeaderCtrls() {
    this.setHeaderCtrls([], false);
  }
  setHeaderCtrls(ctrls, forceOrder) {
    if (!this.isAlive()) {
      return;
    }
    const oldComps = this.headerComps;
    this.headerComps = {};
    ctrls.forEach((ctrl) => {
      const id = ctrl.getInstanceId();
      let comp = oldComps[id];
      delete oldComps[id];
      if (comp == null) {
        comp = this.createHeaderComp(ctrl);
        this.getGui().appendChild(comp.getGui());
      }
      this.headerComps[id] = comp;
    });
    iterateObject(oldComps, (id, comp) => {
      this.getGui().removeChild(comp.getGui());
      this.destroyBean(comp);
    });
    if (forceOrder) {
      const comps = getAllValuesInObject(this.headerComps);
      comps.sort((a, b) => {
        const leftA = a.getCtrl().getColumnGroupChild().getLeft();
        const leftB = b.getCtrl().getColumnGroupChild().getLeft();
        return leftA - leftB;
      });
      const elementsInOrder = comps.map((c) => c.getGui());
      setDomChildOrder(this.getGui(), elementsInOrder);
    }
  }
  createHeaderComp(headerCtrl) {
    let result;
    switch (this.ctrl.getType()) {
      case "group" /* COLUMN_GROUP */:
        result = new HeaderGroupCellComp(headerCtrl);
        break;
      case "filter" /* FLOATING_FILTER */:
        result = new HeaderFilterCellComp(headerCtrl);
        break;
      default:
        result = new HeaderCellComp(headerCtrl);
        break;
    }
    this.createBean(result);
    result.setParentComponent(this);
    return result;
  }
};
__decorateClass([
  PostConstruct
], HeaderRowComp.prototype, "init", 1);
__decorateClass([
  PreDestroy
], HeaderRowComp.prototype, "destroyHeaderCtrls", 1);

// community-modules/core/src/headerRendering/cells/abstractCell/abstractHeaderCellCtrl.ts
var instanceIdSequence4 = 0;
var _AbstractHeaderCellCtrl = class _AbstractHeaderCellCtrl extends BeanStub {
  constructor(columnGroupChild, beans, parentRowCtrl) {
    super();
    this.resizeToggleTimeout = 0;
    this.resizeMultiplier = 1;
    this.resizeFeature = null;
    this.lastFocusEvent = null;
    this.dragSource = null;
    this.columnGroupChild = columnGroupChild;
    this.parentRowCtrl = parentRowCtrl;
    this.beans = beans;
    this.instanceId = columnGroupChild.getUniqueId() + "-" + instanceIdSequence4++;
  }
  postConstruct() {
    this.addManagedPropertyListeners(["suppressHeaderFocus"], () => this.refreshTabIndex());
  }
  shouldStopEventPropagation(e) {
    const { headerRowIndex, column } = this.focusService.getFocusedHeader();
    return isUserSuppressingHeaderKeyboardEvent(
      this.gos,
      e,
      headerRowIndex,
      column
    );
  }
  getWrapperHasFocus() {
    const activeEl = this.gos.getActiveDomElement();
    return activeEl === this.eGui;
  }
  setGui(eGui) {
    this.eGui = eGui;
    this.addDomData();
    this.addManagedListener(this.beans.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.onDisplayedColumnsChanged();
    this.refreshTabIndex();
  }
  onDisplayedColumnsChanged() {
    if (!this.comp || !this.column) {
      return;
    }
    this.refreshFirstAndLastStyles();
    this.refreshAriaColIndex();
  }
  refreshFirstAndLastStyles() {
    const { comp, column, beans } = this;
    CssClassApplier.refreshFirstAndLastStyles(comp, column, beans.columnModel);
  }
  refreshAriaColIndex() {
    const { beans, column } = this;
    const colIdx = beans.columnModel.getAriaColumnIndex(column);
    setAriaColIndex(this.eGui, colIdx);
  }
  addResizeAndMoveKeyboardListeners() {
    if (!this.resizeFeature) {
      return;
    }
    this.addManagedListener(this.eGui, "keydown", this.onGuiKeyDown.bind(this));
    this.addManagedListener(this.eGui, "keyup", this.onGuiKeyUp.bind(this));
  }
  refreshTabIndex() {
    const suppressHeaderFocus = this.gos.get("suppressHeaderFocus");
    if (suppressHeaderFocus) {
      this.eGui.removeAttribute("tabindex");
    } else {
      this.eGui.setAttribute("tabindex", "-1");
    }
  }
  onGuiKeyDown(e) {
    var _a;
    const activeEl = this.gos.getActiveDomElement();
    const isLeftOrRight = e.key === KeyCode.LEFT || e.key === KeyCode.RIGHT;
    if (this.isResizing) {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
    if (
      // if elements within the header are focused, we don't process the event
      activeEl !== this.eGui || // if shiftKey and altKey are not pressed, it's cell navigation so we don't process the event
      !e.shiftKey && !e.altKey
    ) {
      return;
    }
    if (this.isResizing || isLeftOrRight) {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
    if (!isLeftOrRight) {
      return;
    }
    const isLeft = e.key === KeyCode.LEFT !== this.gos.get("enableRtl");
    const direction = HorizontalDirection[isLeft ? "Left" : "Right"];
    if (e.altKey) {
      this.isResizing = true;
      this.resizeMultiplier += 1;
      const diff = this.getViewportAdjustedResizeDiff(e);
      this.resizeHeader(diff, e.shiftKey);
      (_a = this.resizeFeature) == null ? void 0 : _a.toggleColumnResizing(true);
    } else {
      this.moveHeader(direction);
    }
  }
  getViewportAdjustedResizeDiff(e) {
    let diff = this.getResizeDiff(e);
    const pinned = this.column.getPinned();
    if (pinned) {
      const leftWidth = this.pinnedWidthService.getPinnedLeftWidth();
      const rightWidth = this.pinnedWidthService.getPinnedRightWidth();
      const bodyWidth = getInnerWidth(this.ctrlsService.getGridBodyCtrl().getBodyViewportElement()) - 50;
      if (leftWidth + rightWidth + diff > bodyWidth) {
        if (bodyWidth > leftWidth + rightWidth) {
          diff = bodyWidth - leftWidth - rightWidth;
        } else {
          return 0;
        }
      }
    }
    return diff;
  }
  getResizeDiff(e) {
    let isLeft = e.key === KeyCode.LEFT !== this.gos.get("enableRtl");
    const pinned = this.column.getPinned();
    const isRtl = this.gos.get("enableRtl");
    if (pinned) {
      if (isRtl !== (pinned === "right")) {
        isLeft = !isLeft;
      }
    }
    return (isLeft ? -1 : 1) * this.resizeMultiplier;
  }
  onGuiKeyUp() {
    if (!this.isResizing) {
      return;
    }
    if (this.resizeToggleTimeout) {
      window.clearTimeout(this.resizeToggleTimeout);
      this.resizeToggleTimeout = 0;
    }
    this.isResizing = false;
    this.resizeMultiplier = 1;
    this.resizeToggleTimeout = setTimeout(() => {
      var _a;
      (_a = this.resizeFeature) == null ? void 0 : _a.toggleColumnResizing(false);
    }, 150);
  }
  handleKeyDown(e) {
    const wrapperHasFocus = this.getWrapperHasFocus();
    switch (e.key) {
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        if (wrapperHasFocus) {
          e.preventDefault();
        }
    }
  }
  addDomData() {
    const key = _AbstractHeaderCellCtrl.DOM_DATA_KEY_HEADER_CTRL;
    this.gos.setDomData(this.eGui, key, this);
    this.addDestroyFunc(() => this.gos.setDomData(this.eGui, key, null));
  }
  getGui() {
    return this.eGui;
  }
  focus(event) {
    if (!this.eGui) {
      return false;
    }
    this.lastFocusEvent = event || null;
    this.eGui.focus();
    return true;
  }
  getRowIndex() {
    return this.parentRowCtrl.getRowIndex();
  }
  getParentRowCtrl() {
    return this.parentRowCtrl;
  }
  getPinned() {
    return this.parentRowCtrl.getPinned();
  }
  getInstanceId() {
    return this.instanceId;
  }
  getColumnGroupChild() {
    return this.columnGroupChild;
  }
  removeDragSource() {
    if (this.dragSource) {
      this.dragAndDropService.removeDragSource(this.dragSource);
      this.dragSource = null;
    }
  }
  handleContextMenuMouseEvent(mouseEvent, touchEvent, column) {
    const event = mouseEvent != null ? mouseEvent : touchEvent;
    if (this.gos.get("preventDefaultOnContextMenu")) {
      event.preventDefault();
    }
    const columnToUse = column instanceof Column ? column : void 0;
    if (this.menuService.isHeaderContextMenuEnabled(columnToUse)) {
      this.menuService.showHeaderContextMenu(columnToUse, mouseEvent, touchEvent);
    }
    this.dispatchColumnMouseEvent(Events.EVENT_COLUMN_HEADER_CONTEXT_MENU, column);
  }
  dispatchColumnMouseEvent(eventType, column) {
    const event = {
      type: eventType,
      column
    };
    this.eventService.dispatchEvent(event);
  }
  destroy() {
    super.destroy();
    this.removeDragSource();
    this.comp = null;
    this.column = null;
    this.resizeFeature = null;
    this.lastFocusEvent = null;
    this.columnGroupChild = null;
    this.parentRowCtrl = null;
    this.eGui = null;
  }
};
_AbstractHeaderCellCtrl.DOM_DATA_KEY_HEADER_CTRL = "headerCtrl";
__decorateClass([
  Autowired("pinnedWidthService")
], _AbstractHeaderCellCtrl.prototype, "pinnedWidthService", 2);
__decorateClass([
  Autowired("focusService")
], _AbstractHeaderCellCtrl.prototype, "focusService", 2);
__decorateClass([
  Autowired("userComponentFactory")
], _AbstractHeaderCellCtrl.prototype, "userComponentFactory", 2);
__decorateClass([
  Autowired("ctrlsService")
], _AbstractHeaderCellCtrl.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("dragAndDropService")
], _AbstractHeaderCellCtrl.prototype, "dragAndDropService", 2);
__decorateClass([
  Autowired("menuService")
], _AbstractHeaderCellCtrl.prototype, "menuService", 2);
__decorateClass([
  PostConstruct
], _AbstractHeaderCellCtrl.prototype, "postConstruct", 1);
var AbstractHeaderCellCtrl = _AbstractHeaderCellCtrl;

// community-modules/core/src/rendering/features/setLeftFeature.ts
var SetLeftFeature = class extends BeanStub {
  constructor(columnOrGroup, eCell, beans, colsSpanning) {
    super();
    this.columnOrGroup = columnOrGroup;
    this.eCell = eCell;
    this.ariaEl = this.eCell.querySelector("[role=columnheader]") || this.eCell;
    this.colsSpanning = colsSpanning;
    this.beans = beans;
  }
  setColsSpanning(colsSpanning) {
    this.colsSpanning = colsSpanning;
    this.onLeftChanged();
  }
  getColumnOrGroup() {
    if (this.beans.gos.get("enableRtl") && this.colsSpanning) {
      return last(this.colsSpanning);
    }
    return this.columnOrGroup;
  }
  postConstruct() {
    this.addManagedListener(this.columnOrGroup, Column.EVENT_LEFT_CHANGED, this.onLeftChanged.bind(this));
    this.setLeftFirstTime();
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, this.onLeftChanged.bind(this));
    this.addManagedPropertyListener("domLayout", this.onLeftChanged.bind(this));
  }
  setLeftFirstTime() {
    const suppressMoveAnimation = this.beans.gos.get("suppressColumnMoveAnimation");
    const oldLeftExists = exists(this.columnOrGroup.getOldLeft());
    const animateColumnMove = this.beans.columnAnimationService.isActive() && oldLeftExists && !suppressMoveAnimation;
    if (animateColumnMove) {
      this.animateInLeft();
    } else {
      this.onLeftChanged();
    }
  }
  animateInLeft() {
    const colOrGroup = this.getColumnOrGroup();
    const left = colOrGroup.getLeft();
    const oldLeft = colOrGroup.getOldLeft();
    const oldActualLeft = this.modifyLeftForPrintLayout(colOrGroup, oldLeft);
    const actualLeft = this.modifyLeftForPrintLayout(colOrGroup, left);
    this.setLeft(oldActualLeft);
    this.actualLeft = actualLeft;
    this.beans.columnAnimationService.executeNextVMTurn(() => {
      if (this.actualLeft === actualLeft) {
        this.setLeft(actualLeft);
      }
    });
  }
  onLeftChanged() {
    const colOrGroup = this.getColumnOrGroup();
    const left = colOrGroup.getLeft();
    this.actualLeft = this.modifyLeftForPrintLayout(colOrGroup, left);
    this.setLeft(this.actualLeft);
  }
  modifyLeftForPrintLayout(colOrGroup, leftPosition) {
    const printLayout = this.beans.gos.isDomLayout("print");
    if (!printLayout) {
      return leftPosition;
    }
    if (colOrGroup.getPinned() === "left") {
      return leftPosition;
    }
    const leftWidth = this.beans.columnModel.getDisplayedColumnsLeftWidth();
    if (colOrGroup.getPinned() === "right") {
      const bodyWidth = this.beans.columnModel.getBodyContainerWidth();
      return leftWidth + bodyWidth + leftPosition;
    }
    return leftWidth + leftPosition;
  }
  setLeft(value) {
    if (exists(value)) {
      this.eCell.style.left = `${value}px`;
    }
    let indexColumn;
    if (this.columnOrGroup instanceof Column) {
      indexColumn = this.columnOrGroup;
    } else {
      const columnGroup = this.columnOrGroup;
      const children = columnGroup.getLeafColumns();
      if (!children.length) {
        return;
      }
      if (children.length > 1) {
        setAriaColSpan(this.ariaEl, children.length);
      }
      indexColumn = children[0];
    }
  }
};
__decorateClass([
  PostConstruct
], SetLeftFeature.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/cells/hoverFeature.ts
var HoverFeature = class extends BeanStub {
  constructor(columns, element) {
    super();
    this.columns = columns;
    this.element = element;
  }
  postConstruct() {
    if (this.gos.get("columnHoverHighlight")) {
      this.addMouseHoverListeners();
    }
  }
  addMouseHoverListeners() {
    this.addManagedListener(this.element, "mouseout", this.onMouseOut.bind(this));
    this.addManagedListener(this.element, "mouseover", this.onMouseOver.bind(this));
  }
  onMouseOut() {
    this.columnHoverService.clearMouseOver();
  }
  onMouseOver() {
    this.columnHoverService.setMouseOver(this.columns);
  }
};
__decorateClass([
  Autowired("columnHoverService")
], HoverFeature.prototype, "columnHoverService", 2);
__decorateClass([
  PostConstruct
], HoverFeature.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/cells/floatingFilter/headerFilterCellCtrl.ts
var HeaderFilterCellCtrl = class extends AbstractHeaderCellCtrl {
  constructor(column, beans, parentRowCtrl) {
    super(column, beans, parentRowCtrl);
    this.iconCreated = false;
    this.column = column;
  }
  setComp(comp, eGui, eButtonShowMainFilter, eFloatingFilterBody) {
    this.comp = comp;
    this.eButtonShowMainFilter = eButtonShowMainFilter;
    this.eFloatingFilterBody = eFloatingFilterBody;
    this.setGui(eGui);
    this.setupActive();
    this.setupWidth();
    this.setupLeft();
    this.setupHover();
    this.setupFocus();
    this.setupAria();
    this.setupFilterButton();
    this.setupUserComp();
    this.setupSyncWithFilter();
    this.setupUi();
    this.addManagedListener(this.eButtonShowMainFilter, "click", this.showParentFilter.bind(this));
    this.setupFilterChangedListener();
    this.addManagedListener(this.column, Column.EVENT_COL_DEF_CHANGED, this.onColDefChanged.bind(this));
  }
  // empty abstract method
  resizeHeader() {
  }
  // empty abstract method
  moveHeader() {
  }
  setupActive() {
    const colDef = this.column.getColDef();
    const filterExists = !!colDef.filter;
    const floatingFilterExists = !!colDef.floatingFilter;
    this.active = filterExists && floatingFilterExists;
  }
  setupUi() {
    this.comp.setButtonWrapperDisplayed(!this.suppressFilterButton && this.active);
    this.comp.addOrRemoveBodyCssClass("ag-floating-filter-full-body", this.suppressFilterButton);
    this.comp.addOrRemoveBodyCssClass("ag-floating-filter-body", !this.suppressFilterButton);
    if (!this.active || this.iconCreated) {
      return;
    }
    const eMenuIcon = createIconNoSpan("filter", this.gos, this.column);
    if (eMenuIcon) {
      this.iconCreated = true;
      this.eButtonShowMainFilter.appendChild(eMenuIcon);
    }
  }
  setupFocus() {
    this.createManagedBean(new ManagedFocusFeature(
      this.eGui,
      {
        shouldStopEventPropagation: this.shouldStopEventPropagation.bind(this),
        onTabKeyDown: this.onTabKeyDown.bind(this),
        handleKeyDown: this.handleKeyDown.bind(this),
        onFocusIn: this.onFocusIn.bind(this)
      }
    ));
  }
  setupAria() {
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    setAriaLabel(this.eButtonShowMainFilter, localeTextFunc("ariaFilterMenuOpen", "Open Filter Menu"));
  }
  onTabKeyDown(e) {
    const activeEl = this.gos.getActiveDomElement();
    const wrapperHasFocus = activeEl === this.eGui;
    if (wrapperHasFocus) {
      return;
    }
    const nextFocusableEl = this.focusService.findNextFocusableElement(this.eGui, null, e.shiftKey);
    if (nextFocusableEl) {
      this.beans.headerNavigationService.scrollToColumn(this.column);
      e.preventDefault();
      nextFocusableEl.focus();
      return;
    }
    const nextFocusableColumn = this.findNextColumnWithFloatingFilter(e.shiftKey);
    if (!nextFocusableColumn) {
      return;
    }
    if (this.focusService.focusHeaderPosition({
      headerPosition: {
        headerRowIndex: this.getParentRowCtrl().getRowIndex(),
        column: nextFocusableColumn
      },
      event: e
    })) {
      e.preventDefault();
    }
  }
  findNextColumnWithFloatingFilter(backwards) {
    const columnModel = this.beans.columnModel;
    let nextCol = this.column;
    do {
      nextCol = backwards ? columnModel.getDisplayedColBefore(nextCol) : columnModel.getDisplayedColAfter(nextCol);
      if (!nextCol) {
        break;
      }
    } while (!nextCol.getColDef().filter || !nextCol.getColDef().floatingFilter);
    return nextCol;
  }
  handleKeyDown(e) {
    super.handleKeyDown(e);
    const wrapperHasFocus = this.getWrapperHasFocus();
    switch (e.key) {
      case KeyCode.UP:
      case KeyCode.DOWN:
        if (!wrapperHasFocus) {
          e.preventDefault();
        }
      case KeyCode.LEFT:
      case KeyCode.RIGHT:
        if (wrapperHasFocus) {
          return;
        }
        e.stopPropagation();
      case KeyCode.ENTER:
        if (wrapperHasFocus) {
          if (this.focusService.focusInto(this.eGui)) {
            e.preventDefault();
          }
        }
        break;
      case KeyCode.ESCAPE:
        if (!wrapperHasFocus) {
          this.eGui.focus();
        }
    }
  }
  onFocusIn(e) {
    const isRelatedWithin = this.eGui.contains(e.relatedTarget);
    if (isRelatedWithin) {
      return;
    }
    const notFromHeaderWrapper = !!e.relatedTarget && !e.relatedTarget.classList.contains("ag-floating-filter");
    const fromWithinHeader = !!e.relatedTarget && isElementChildOfClass(e.relatedTarget, "ag-floating-filter");
    if (notFromHeaderWrapper && fromWithinHeader && e.target === this.eGui) {
      const lastFocusEvent = this.lastFocusEvent;
      const fromTab = !!(lastFocusEvent && lastFocusEvent.key === KeyCode.TAB);
      if (lastFocusEvent && fromTab) {
        const shouldFocusLast = lastFocusEvent.shiftKey;
        this.focusService.focusInto(this.eGui, shouldFocusLast);
      }
    }
    const rowIndex = this.getRowIndex();
    this.beans.focusService.setFocusedHeader(rowIndex, this.column);
  }
  setupHover() {
    this.createManagedBean(new HoverFeature([this.column], this.eGui));
    const listener = () => {
      if (!this.gos.get("columnHoverHighlight")) {
        return;
      }
      const hovered = this.beans.columnHoverService.isHovered(this.column);
      this.comp.addOrRemoveCssClass("ag-column-hover", hovered);
    };
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_HOVER_CHANGED, listener);
    listener();
  }
  setupLeft() {
    const setLeftFeature = new SetLeftFeature(this.column, this.eGui, this.beans);
    this.createManagedBean(setLeftFeature);
  }
  setupFilterButton() {
    this.suppressFilterButton = !this.menuService.isFloatingFilterButtonEnabled(this.column);
    this.highlightFilterButtonWhenActive = !this.menuService.isLegacyMenuEnabled();
  }
  setupUserComp() {
    if (!this.active) {
      return;
    }
    const compDetails = this.beans.filterManager.getFloatingFilterCompDetails(
      this.column,
      () => this.showParentFilter()
    );
    if (compDetails) {
      this.setCompDetails(compDetails);
    }
  }
  setCompDetails(compDetails) {
    this.userCompDetails = compDetails;
    this.comp.setCompDetails(compDetails);
  }
  showParentFilter() {
    const eventSource = this.suppressFilterButton ? this.eFloatingFilterBody : this.eButtonShowMainFilter;
    this.menuService.showFilterMenu({
      column: this.column,
      buttonElement: eventSource,
      containerType: "floatingFilter",
      positionBy: "button"
    });
  }
  setupSyncWithFilter() {
    if (!this.active) {
      return;
    }
    const { filterManager } = this.beans;
    const syncWithFilter = (event) => {
      if ((event == null ? void 0 : event.source) === "filterDestroyed" && this.context.isDestroyed()) {
        return;
      }
      const compPromise = this.comp.getFloatingFilterComp();
      if (!compPromise) {
        return;
      }
      compPromise.then((comp) => {
        var _a;
        if (comp) {
          const parentModel = filterManager.getCurrentFloatingFilterParentModel(this.column);
          comp.onParentModelChanged(parentModel, event ? this.gos.addGridCommonParams({
            columns: (_a = event.columns) != null ? _a : [],
            type: Events.EVENT_FILTER_CHANGED,
            source: event.source === "api" ? "api" : "columnFilter"
          }) : null);
        }
      });
    };
    this.destroySyncListener = this.addManagedListener(this.column, Column.EVENT_FILTER_CHANGED, syncWithFilter);
    if (filterManager.isFilterActive(this.column)) {
      syncWithFilter(null);
    }
  }
  setupWidth() {
    const listener = () => {
      const width = `${this.column.getActualWidth()}px`;
      this.comp.setWidth(width);
    };
    this.addManagedListener(this.column, Column.EVENT_WIDTH_CHANGED, listener);
    listener();
  }
  setupFilterChangedListener() {
    if (this.active) {
      this.destroyFilterChangedListener = this.addManagedListener(this.column, Column.EVENT_FILTER_CHANGED, this.updateFilterButton.bind(this));
      this.updateFilterButton();
    }
  }
  updateFilterButton() {
    if (!this.suppressFilterButton && this.comp) {
      const isFilterAllowed = this.beans.filterManager.isFilterAllowed(this.column);
      this.comp.setButtonWrapperDisplayed(isFilterAllowed);
      if (this.highlightFilterButtonWhenActive && isFilterAllowed) {
        this.eButtonShowMainFilter.classList.toggle("ag-filter-active", this.column.isFilterActive());
      }
    }
  }
  onColDefChanged() {
    var _a, _b;
    const wasActive = this.active;
    this.setupActive();
    const becomeActive = !wasActive && this.active;
    if (wasActive && !this.active) {
      (_a = this.destroySyncListener) == null ? void 0 : _a.call(this);
      (_b = this.destroyFilterChangedListener) == null ? void 0 : _b.call(this);
    }
    const newCompDetails = this.active ? this.beans.filterManager.getFloatingFilterCompDetails(
      this.column,
      () => this.showParentFilter()
    ) : null;
    const compPromise = this.comp.getFloatingFilterComp();
    if (!compPromise || !newCompDetails) {
      this.updateCompDetails(newCompDetails, becomeActive);
    } else {
      compPromise.then((compInstance) => {
        var _a2;
        if (!compInstance || this.beans.filterManager.areFilterCompsDifferent((_a2 = this.userCompDetails) != null ? _a2 : null, newCompDetails)) {
          this.updateCompDetails(newCompDetails, becomeActive);
        } else {
          this.updateFloatingFilterParams(newCompDetails);
        }
      });
    }
  }
  updateCompDetails(compDetails, becomeActive) {
    if (!this.isAlive()) {
      return;
    }
    this.setCompDetails(compDetails);
    this.setupFilterButton();
    this.setupUi();
    if (becomeActive) {
      this.setupSyncWithFilter();
      this.setupFilterChangedListener();
    }
  }
  updateFloatingFilterParams(userCompDetails) {
    var _a;
    if (!userCompDetails) {
      return;
    }
    const params = userCompDetails.params;
    (_a = this.comp.getFloatingFilterComp()) == null ? void 0 : _a.then((floatingFilter) => {
      let hasRefreshed = false;
      if ((floatingFilter == null ? void 0 : floatingFilter.refresh) && typeof floatingFilter.refresh === "function") {
        const result = floatingFilter.refresh(params);
        if (result !== null) {
          hasRefreshed = true;
        }
      }
      if (!hasRefreshed && (floatingFilter == null ? void 0 : floatingFilter.onParamsUpdated) && typeof floatingFilter.onParamsUpdated === "function") {
        const result = floatingFilter.onParamsUpdated(params);
        if (result !== null) {
          warnOnce(`Custom floating filter method 'onParamsUpdated' is deprecated. Use 'refresh' instead.`);
        }
      }
    });
  }
  destroy() {
    super.destroy();
    this.eButtonShowMainFilter = null;
    this.eFloatingFilterBody = null;
    this.userCompDetails = null;
    this.destroySyncListener = null;
    this.destroyFilterChangedListener = null;
  }
};

// community-modules/core/src/headerRendering/cells/column/resizeFeature.ts
var ResizeFeature = class extends BeanStub {
  constructor(pinned, column, eResize, comp, ctrl) {
    super();
    this.pinned = pinned;
    this.column = column;
    this.eResize = eResize;
    this.comp = comp;
    this.ctrl = ctrl;
  }
  postConstruct() {
    const destroyResizeFuncs = [];
    let canResize;
    let canAutosize;
    const addResize = () => {
      setDisplayed(this.eResize, canResize);
      if (!canResize) {
        return;
      }
      const finishedWithResizeFunc = this.horizontalResizeService.addResizeBar({
        eResizeBar: this.eResize,
        onResizeStart: this.onResizeStart.bind(this),
        onResizing: this.onResizing.bind(this, false),
        onResizeEnd: this.onResizing.bind(this, true)
      });
      destroyResizeFuncs.push(finishedWithResizeFunc);
      if (canAutosize) {
        const skipHeaderOnAutoSize = this.gos.get("skipHeaderOnAutoSize");
        const autoSizeColListener = () => {
          this.columnModel.autoSizeColumn(this.column, "uiColumnResized", skipHeaderOnAutoSize);
        };
        this.eResize.addEventListener("dblclick", autoSizeColListener);
        const touchListener = new TouchListener(this.eResize);
        touchListener.addEventListener(TouchListener.EVENT_DOUBLE_TAP, autoSizeColListener);
        destroyResizeFuncs.push(() => {
          this.eResize.removeEventListener("dblclick", autoSizeColListener);
          touchListener.removeEventListener(TouchListener.EVENT_DOUBLE_TAP, autoSizeColListener);
          touchListener.destroy();
        });
      }
    };
    const removeResize = () => {
      destroyResizeFuncs.forEach((f) => f());
      destroyResizeFuncs.length = 0;
    };
    const refresh = () => {
      const resize = this.column.isResizable();
      const autoSize = !this.gos.get("suppressAutoSize") && !this.column.getColDef().suppressAutoSize;
      const propertyChange = resize !== canResize || autoSize !== canAutosize;
      if (propertyChange) {
        canResize = resize;
        canAutosize = autoSize;
        removeResize();
        addResize();
      }
    };
    refresh();
    this.addDestroyFunc(removeResize);
    this.ctrl.addRefreshFunction(refresh);
  }
  onResizing(finished, resizeAmount) {
    const { column: key, lastResizeAmount, resizeStartWidth } = this;
    const resizeAmountNormalised = this.normaliseResizeAmount(resizeAmount);
    const newWidth = resizeStartWidth + resizeAmountNormalised;
    const columnWidths = [{ key, newWidth }];
    if (this.column.getPinned()) {
      const leftWidth = this.pinnedWidthService.getPinnedLeftWidth();
      const rightWidth = this.pinnedWidthService.getPinnedRightWidth();
      const bodyWidth = getInnerWidth(this.ctrlsService.getGridBodyCtrl().getBodyViewportElement()) - 50;
      if (leftWidth + rightWidth + (resizeAmountNormalised - lastResizeAmount) > bodyWidth) {
        return;
      }
    }
    this.lastResizeAmount = resizeAmountNormalised;
    this.columnModel.setColumnWidths(columnWidths, this.resizeWithShiftKey, finished, "uiColumnResized");
    if (finished) {
      this.toggleColumnResizing(false);
    }
  }
  onResizeStart(shiftKey) {
    this.resizeStartWidth = this.column.getActualWidth();
    this.lastResizeAmount = 0;
    this.resizeWithShiftKey = shiftKey;
    this.toggleColumnResizing(true);
  }
  toggleColumnResizing(resizing) {
    this.comp.addOrRemoveCssClass("ag-column-resizing", resizing);
  }
  // optionally inverts the drag, depending on pinned and RTL
  // note - this method is duplicated in RenderedHeaderGroupCell - should refactor out?
  normaliseResizeAmount(dragChange) {
    let result = dragChange;
    const notPinningLeft = this.pinned !== "left";
    const pinningRight = this.pinned === "right";
    if (this.gos.get("enableRtl")) {
      if (notPinningLeft) {
        result *= -1;
      }
    } else {
      if (pinningRight) {
        result *= -1;
      }
    }
    return result;
  }
};
__decorateClass([
  Autowired("horizontalResizeService")
], ResizeFeature.prototype, "horizontalResizeService", 2);
__decorateClass([
  Autowired("pinnedWidthService")
], ResizeFeature.prototype, "pinnedWidthService", 2);
__decorateClass([
  Autowired("ctrlsService")
], ResizeFeature.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("columnModel")
], ResizeFeature.prototype, "columnModel", 2);
__decorateClass([
  PostConstruct
], ResizeFeature.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/cells/column/selectAllFeature.ts
var SelectAllFeature = class extends BeanStub {
  constructor(column) {
    super();
    this.cbSelectAllVisible = false;
    this.processingEventFromCheckbox = false;
    this.column = column;
  }
  onSpaceKeyDown(e) {
    const checkbox = this.cbSelectAll;
    if (checkbox.isDisplayed() && !checkbox.getGui().contains(this.gos.getActiveDomElement())) {
      e.preventDefault();
      checkbox.setValue(!checkbox.getValue());
    }
  }
  getCheckboxGui() {
    return this.cbSelectAll.getGui();
  }
  setComp(ctrl) {
    this.headerCellCtrl = ctrl;
    this.cbSelectAll = this.createManagedBean(new AgCheckbox());
    this.cbSelectAll.addCssClass("ag-header-select-all");
    setAriaRole(this.cbSelectAll.getGui(), "presentation");
    this.showOrHideSelectAll();
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, this.onNewColumnsLoaded.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_SELECTION_CHANGED, this.onSelectionChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_PAGINATION_CHANGED, this.onSelectionChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_MODEL_UPDATED, this.onModelChanged.bind(this));
    this.addManagedListener(this.cbSelectAll, Events.EVENT_FIELD_VALUE_CHANGED, this.onCbSelectAll.bind(this));
    setAriaHidden(this.cbSelectAll.getGui(), true);
    this.cbSelectAll.getInputElement().setAttribute("tabindex", "-1");
    this.refreshSelectAllLabel();
  }
  onNewColumnsLoaded() {
    this.showOrHideSelectAll();
  }
  onDisplayedColumnsChanged() {
    if (!this.isAlive()) {
      return;
    }
    this.showOrHideSelectAll();
  }
  showOrHideSelectAll() {
    this.cbSelectAllVisible = this.isCheckboxSelection();
    this.cbSelectAll.setDisplayed(this.cbSelectAllVisible, { skipAriaHidden: true });
    if (this.cbSelectAllVisible) {
      this.checkRightRowModelType("selectAllCheckbox");
      this.checkSelectionType("selectAllCheckbox");
      this.updateStateOfCheckbox();
    }
    this.refreshSelectAllLabel();
  }
  onModelChanged() {
    if (!this.cbSelectAllVisible) {
      return;
    }
    this.updateStateOfCheckbox();
  }
  onSelectionChanged() {
    if (!this.cbSelectAllVisible) {
      return;
    }
    this.updateStateOfCheckbox();
  }
  updateStateOfCheckbox() {
    if (this.processingEventFromCheckbox) {
      return;
    }
    this.processingEventFromCheckbox = true;
    const allSelected = this.selectionService.getSelectAllState(
      this.isFilteredOnly(),
      this.isCurrentPageOnly()
    );
    this.cbSelectAll.setValue(allSelected);
    const hasNodesToSelect = this.selectionService.hasNodesToSelect(this.isFilteredOnly(), this.isCurrentPageOnly());
    this.cbSelectAll.setDisabled(!hasNodesToSelect);
    this.refreshSelectAllLabel();
    this.processingEventFromCheckbox = false;
  }
  refreshSelectAllLabel() {
    const translate = this.localeService.getLocaleTextFunc();
    const checked = this.cbSelectAll.getValue();
    const ariaStatus = checked ? translate("ariaChecked", "checked") : translate("ariaUnchecked", "unchecked");
    const ariaLabel = translate("ariaRowSelectAll", "Press Space to toggle all rows selection");
    if (!this.cbSelectAllVisible) {
      this.headerCellCtrl.setAriaDescriptionProperty("selectAll", null);
    } else {
      this.headerCellCtrl.setAriaDescriptionProperty("selectAll", `${ariaLabel} (${ariaStatus})`);
    }
    this.cbSelectAll.setInputAriaLabel(`${ariaLabel} (${ariaStatus})`);
    this.headerCellCtrl.announceAriaDescription();
  }
  checkSelectionType(feature) {
    const isMultiSelect = this.gos.get("rowSelection") === "multiple";
    if (!isMultiSelect) {
      console.warn(`AG Grid: ${feature} is only available if using 'multiple' rowSelection.`);
      return false;
    }
    return true;
  }
  checkRightRowModelType(feature) {
    const rowModelType = this.rowModel.getType();
    const rowModelMatches = rowModelType === "clientSide" || rowModelType === "serverSide";
    if (!rowModelMatches) {
      console.warn(`AG Grid: ${feature} is only available if using 'clientSide' or 'serverSide' rowModelType, you are using ${rowModelType}.`);
      return false;
    }
    return true;
  }
  onCbSelectAll() {
    if (this.processingEventFromCheckbox) {
      return;
    }
    if (!this.cbSelectAllVisible) {
      return;
    }
    const value = this.cbSelectAll.getValue();
    const justFiltered = this.isFilteredOnly();
    const justCurrentPage = this.isCurrentPageOnly();
    let source = "uiSelectAll";
    if (justCurrentPage) {
      source = "uiSelectAllCurrentPage";
    } else if (justFiltered) {
      source = "uiSelectAllFiltered";
    }
    const params = {
      source,
      justFiltered,
      justCurrentPage
    };
    if (value) {
      this.selectionService.selectAllRowNodes(params);
    } else {
      this.selectionService.deselectAllRowNodes(params);
    }
  }
  isCheckboxSelection() {
    let result = this.column.getColDef().headerCheckboxSelection;
    if (typeof result === "function") {
      const func = result;
      const params = this.gos.addGridCommonParams({
        column: this.column,
        colDef: this.column.getColDef()
      });
      result = func(params);
    }
    if (result) {
      return this.checkRightRowModelType("headerCheckboxSelection") && this.checkSelectionType("headerCheckboxSelection");
    }
    return false;
  }
  isFilteredOnly() {
    return !!this.column.getColDef().headerCheckboxSelectionFilteredOnly;
  }
  isCurrentPageOnly() {
    return !!this.column.getColDef().headerCheckboxSelectionCurrentPageOnly;
  }
};
__decorateClass([
  Autowired("rowModel")
], SelectAllFeature.prototype, "rowModel", 2);
__decorateClass([
  Autowired("selectionService")
], SelectAllFeature.prototype, "selectionService", 2);

// community-modules/core/src/headerRendering/cells/column/headerCellCtrl.ts
var HeaderCellCtrl = class extends AbstractHeaderCellCtrl {
  constructor(column, beans, parentRowCtrl) {
    super(column, beans, parentRowCtrl);
    this.refreshFunctions = [];
    this.userHeaderClasses = /* @__PURE__ */ new Set();
    this.ariaDescriptionProperties = /* @__PURE__ */ new Map();
    this.column = column;
  }
  setComp(comp, eGui, eResize, eHeaderCompWrapper) {
    this.comp = comp;
    this.setGui(eGui);
    this.updateState();
    this.setupWidth();
    this.setupMovingCss();
    this.setupMenuClass();
    this.setupSortableClass();
    this.setupWrapTextClass();
    this.refreshSpanHeaderHeight();
    this.setupAutoHeight(eHeaderCompWrapper);
    this.addColumnHoverListener();
    this.setupFilterClass();
    this.setupClassesFromColDef();
    this.setupTooltip();
    this.addActiveHeaderMouseListeners();
    this.setupSelectAll();
    this.setupUserComp();
    this.refreshAria();
    this.resizeFeature = this.createManagedBean(new ResizeFeature(this.getPinned(), this.column, eResize, comp, this));
    this.createManagedBean(new HoverFeature([this.column], eGui));
    this.createManagedBean(new SetLeftFeature(this.column, eGui, this.beans));
    this.createManagedBean(new ManagedFocusFeature(
      eGui,
      {
        shouldStopEventPropagation: (e) => this.shouldStopEventPropagation(e),
        onTabKeyDown: () => null,
        handleKeyDown: this.handleKeyDown.bind(this),
        onFocusIn: this.onFocusIn.bind(this),
        onFocusOut: this.onFocusOut.bind(this)
      }
    ));
    this.addResizeAndMoveKeyboardListeners();
    this.addManagedPropertyListeners(["suppressMovableColumns", "suppressMenuHide", "suppressAggFuncInHeader"], this.refresh.bind(this));
    this.addManagedListener(this.column, Column.EVENT_COL_DEF_CHANGED, this.refresh.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VALUE_CHANGED, this.onColumnValueChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.onColumnRowGroupChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_CHANGED, this.onColumnPivotChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_HEADER_HEIGHT_CHANGED, this.onHeaderHeightChanged.bind(this));
  }
  resizeHeader(delta, shiftKey) {
    var _a, _b;
    if (!this.column.isResizable()) {
      return;
    }
    const actualWidth = this.column.getActualWidth();
    const minWidth = (_a = this.column.getMinWidth()) != null ? _a : 0;
    const maxWidth = (_b = this.column.getMaxWidth()) != null ? _b : Number.MAX_SAFE_INTEGER;
    const newWidth = Math.min(Math.max(actualWidth + delta, minWidth), maxWidth);
    this.beans.columnModel.setColumnWidths([{ key: this.column, newWidth }], shiftKey, true, "uiColumnResized");
  }
  moveHeader(hDirection) {
    const { eGui, column, gos, ctrlsService } = this;
    const pinned = this.getPinned();
    const left = eGui.getBoundingClientRect().left;
    const width = column.getActualWidth();
    const isRtl = gos.get("enableRtl");
    const isLeft = hDirection === 0 /* Left */ !== isRtl;
    const xPosition = ColumnMoveHelper.normaliseX(
      isLeft ? left - 20 : left + width + 20,
      pinned,
      true,
      gos,
      ctrlsService
    );
    ColumnMoveHelper.attemptMoveColumns({
      allMovingColumns: [column],
      isFromHeader: true,
      hDirection,
      xPosition,
      pinned,
      fromEnter: false,
      fakeEvent: false,
      gos,
      columnModel: this.beans.columnModel
    });
    ctrlsService.getGridBodyCtrl().getScrollFeature().ensureColumnVisible(column, "auto");
  }
  setupUserComp() {
    const compDetails = this.lookupUserCompDetails();
    this.setCompDetails(compDetails);
  }
  setCompDetails(compDetails) {
    this.userCompDetails = compDetails;
    this.comp.setUserCompDetails(compDetails);
  }
  lookupUserCompDetails() {
    const params = this.createParams();
    const colDef = this.column.getColDef();
    return this.userComponentFactory.getHeaderCompDetails(colDef, params);
  }
  createParams() {
    const params = this.gos.addGridCommonParams({
      column: this.column,
      displayName: this.displayName,
      enableSorting: this.column.isSortable(),
      enableMenu: this.menuEnabled,
      enableFilterButton: this.openFilterEnabled && this.menuService.isHeaderFilterButtonEnabled(this.column),
      enableFilterIcon: !this.openFilterEnabled || this.menuService.isLegacyMenuEnabled(),
      showColumnMenu: (buttonElement) => {
        this.menuService.showColumnMenu({
          column: this.column,
          buttonElement,
          positionBy: "button"
        });
      },
      showColumnMenuAfterMouseClick: (mouseEvent) => {
        this.menuService.showColumnMenu({
          column: this.column,
          mouseEvent,
          positionBy: "mouse"
        });
      },
      showFilter: (buttonElement) => {
        this.menuService.showFilterMenu({
          column: this.column,
          buttonElement,
          containerType: "columnFilter",
          positionBy: "button"
        });
      },
      progressSort: (multiSort) => {
        this.beans.sortController.progressSort(this.column, !!multiSort, "uiColumnSorted");
      },
      setSort: (sort, multiSort) => {
        this.beans.sortController.setSortForColumn(this.column, sort, !!multiSort, "uiColumnSorted");
      },
      eGridHeader: this.getGui(),
      setTooltip: (value, shouldDisplayTooltip) => {
        this.setupTooltip(value, shouldDisplayTooltip);
      }
    });
    return params;
  }
  setupSelectAll() {
    this.selectAllFeature = this.createManagedBean(new SelectAllFeature(this.column));
    this.selectAllFeature.setComp(this);
  }
  getSelectAllGui() {
    return this.selectAllFeature.getCheckboxGui();
  }
  handleKeyDown(e) {
    super.handleKeyDown(e);
    if (e.key === KeyCode.SPACE) {
      this.selectAllFeature.onSpaceKeyDown(e);
    }
    if (e.key === KeyCode.ENTER) {
      this.onEnterKeyDown(e);
    }
    if (e.key === KeyCode.DOWN && e.altKey) {
      this.showMenuOnKeyPress(e, false);
    }
  }
  onEnterKeyDown(e) {
    if (e.ctrlKey || e.metaKey) {
      this.showMenuOnKeyPress(e, true);
    } else if (this.sortable) {
      const multiSort = e.shiftKey;
      this.beans.sortController.progressSort(this.column, multiSort, "uiColumnSorted");
    }
  }
  showMenuOnKeyPress(e, isFilterShortcut) {
    const headerComp = this.comp.getUserCompInstance();
    if (!headerComp || !(headerComp instanceof HeaderComp)) {
      return;
    }
    if (headerComp.onMenuKeyboardShortcut(isFilterShortcut)) {
      e.preventDefault();
    }
  }
  onFocusIn(e) {
    if (!this.getGui().contains(e.relatedTarget)) {
      const rowIndex = this.getRowIndex();
      this.focusService.setFocusedHeader(rowIndex, this.column);
      this.announceAriaDescription();
    }
    if (this.focusService.isKeyboardMode()) {
      this.setActiveHeader(true);
    }
  }
  onFocusOut(e) {
    if (this.getGui().contains(e.relatedTarget)) {
      return;
    }
    this.setActiveHeader(false);
  }
  setupTooltip(value, shouldDisplayTooltip) {
    if (this.tooltipFeature) {
      this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    }
    const isTooltipWhenTruncated = this.gos.get("tooltipShowMode") === "whenTruncated";
    const eGui = this.eGui;
    const colDef = this.column.getColDef();
    if (!shouldDisplayTooltip && isTooltipWhenTruncated && !colDef.headerComponent) {
      shouldDisplayTooltip = () => {
        const textEl = eGui.querySelector(".ag-header-cell-text");
        if (!textEl) {
          return true;
        }
        return textEl.scrollWidth > textEl.clientWidth;
      };
    }
    const tooltipCtrl = {
      getColumn: () => this.column,
      getColDef: () => this.column.getColDef(),
      getGui: () => eGui,
      getLocation: () => "header",
      getTooltipValue: () => {
        if (value != null) {
          return value;
        }
        const res = this.column.getColDef().headerTooltip;
        return res;
      },
      shouldDisplayTooltip
    };
    const tooltipFeature = this.createManagedBean(new TooltipFeature(tooltipCtrl));
    this.refreshFunctions.push(() => tooltipFeature.refreshToolTip());
  }
  setupClassesFromColDef() {
    const refreshHeaderClasses = () => {
      const colDef = this.column.getColDef();
      const classes = CssClassApplier.getHeaderClassesFromColDef(colDef, this.gos, this.column, null);
      const oldClasses = this.userHeaderClasses;
      this.userHeaderClasses = new Set(classes);
      classes.forEach((c) => {
        if (oldClasses.has(c)) {
          oldClasses.delete(c);
        } else {
          this.comp.addOrRemoveCssClass(c, true);
        }
      });
      oldClasses.forEach((c) => this.comp.addOrRemoveCssClass(c, false));
    };
    this.refreshFunctions.push(refreshHeaderClasses);
    refreshHeaderClasses();
  }
  setDragSource(eSource) {
    this.dragSourceElement = eSource;
    this.removeDragSource();
    if (!eSource || !this.draggable) {
      return;
    }
    const { column, beans, displayName, dragAndDropService, gos } = this;
    const { columnModel } = beans;
    let hideColumnOnExit = !this.gos.get("suppressDragLeaveHidesColumns");
    const dragSource = this.dragSource = {
      type: 1 /* HeaderCell */,
      eElement: eSource,
      getDefaultIconName: () => hideColumnOnExit ? DragAndDropService.ICON_HIDE : DragAndDropService.ICON_NOT_ALLOWED,
      getDragItem: () => this.createDragItem(column),
      dragItemName: displayName,
      onDragStarted: () => {
        hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
        column.setMoving(true, "uiColumnMoved");
      },
      onDragStopped: () => column.setMoving(false, "uiColumnMoved"),
      onGridEnter: (dragItem) => {
        var _a;
        if (hideColumnOnExit) {
          const unlockedColumns = ((_a = dragItem == null ? void 0 : dragItem.columns) == null ? void 0 : _a.filter((col) => !col.getColDef().lockVisible)) || [];
          columnModel.setColumnsVisible(unlockedColumns, true, "uiColumnMoved");
        }
      },
      onGridExit: (dragItem) => {
        var _a;
        if (hideColumnOnExit) {
          const unlockedColumns = ((_a = dragItem == null ? void 0 : dragItem.columns) == null ? void 0 : _a.filter((col) => !col.getColDef().lockVisible)) || [];
          columnModel.setColumnsVisible(unlockedColumns, false, "uiColumnMoved");
        }
      }
    };
    dragAndDropService.addDragSource(dragSource, true);
  }
  createDragItem(column) {
    const visibleState = {};
    visibleState[column.getId()] = column.isVisible();
    return {
      columns: [column],
      visibleState
    };
  }
  updateState() {
    this.menuEnabled = this.menuService.isColumnMenuInHeaderEnabled(this.column);
    this.openFilterEnabled = this.menuService.isFilterMenuInHeaderEnabled(this.column);
    this.sortable = this.column.isSortable();
    this.displayName = this.calculateDisplayName();
    this.draggable = this.workOutDraggable();
  }
  addRefreshFunction(func) {
    this.refreshFunctions.push(func);
  }
  refresh() {
    this.updateState();
    this.refreshHeaderComp();
    this.refreshAria();
    this.refreshFunctions.forEach((f) => f());
  }
  refreshHeaderComp() {
    const newCompDetails = this.lookupUserCompDetails();
    const compInstance = this.comp.getUserCompInstance();
    const attemptRefresh = compInstance != null && this.userCompDetails.componentClass == newCompDetails.componentClass;
    const headerCompRefreshed = attemptRefresh ? this.attemptHeaderCompRefresh(newCompDetails.params) : false;
    if (headerCompRefreshed) {
      this.setDragSource(this.dragSourceElement);
    } else {
      this.setCompDetails(newCompDetails);
    }
  }
  attemptHeaderCompRefresh(params) {
    const headerComp = this.comp.getUserCompInstance();
    if (!headerComp) {
      return false;
    }
    if (!headerComp.refresh) {
      return false;
    }
    const res = headerComp.refresh(params);
    return res;
  }
  calculateDisplayName() {
    return this.beans.columnModel.getDisplayNameForColumn(this.column, "header", true);
  }
  checkDisplayName() {
    if (this.displayName !== this.calculateDisplayName()) {
      this.refresh();
    }
  }
  workOutDraggable() {
    const colDef = this.column.getColDef();
    const isSuppressMovableColumns = this.gos.get("suppressMovableColumns");
    const colCanMove = !isSuppressMovableColumns && !colDef.suppressMovable && !colDef.lockPosition;
    return !!colCanMove || !!colDef.enableRowGroup || !!colDef.enablePivot;
  }
  onColumnRowGroupChanged() {
    this.checkDisplayName();
  }
  onColumnPivotChanged() {
    this.checkDisplayName();
  }
  onColumnValueChanged() {
    this.checkDisplayName();
  }
  setupWidth() {
    const listener = () => {
      const columnWidth = this.column.getActualWidth();
      this.comp.setWidth(`${columnWidth}px`);
    };
    this.addManagedListener(this.column, Column.EVENT_WIDTH_CHANGED, listener);
    listener();
  }
  setupMovingCss() {
    const listener = () => {
      this.comp.addOrRemoveCssClass("ag-header-cell-moving", this.column.isMoving());
    };
    this.addManagedListener(this.column, Column.EVENT_MOVING_CHANGED, listener);
    listener();
  }
  setupMenuClass() {
    const listener = () => {
      this.comp.addOrRemoveCssClass("ag-column-menu-visible", this.column.isMenuVisible());
    };
    this.addManagedListener(this.column, Column.EVENT_MENU_VISIBLE_CHANGED, listener);
    listener();
  }
  setupSortableClass() {
    const updateSortableCssClass = () => {
      this.comp.addOrRemoveCssClass("ag-header-cell-sortable", !!this.sortable);
    };
    updateSortableCssClass();
    this.addRefreshFunction(updateSortableCssClass);
    this.addManagedListener(this.eventService, Column.EVENT_SORT_CHANGED, this.refreshAriaSort.bind(this));
  }
  setupFilterClass() {
    const listener = () => {
      const isFilterActive = this.column.isFilterActive();
      this.comp.addOrRemoveCssClass("ag-header-cell-filtered", isFilterActive);
      this.refreshAria();
    };
    this.addManagedListener(this.column, Column.EVENT_FILTER_ACTIVE_CHANGED, listener);
    listener();
  }
  setupWrapTextClass() {
    const listener = () => {
      const wrapText = !!this.column.getColDef().wrapHeaderText;
      this.comp.addOrRemoveCssClass("ag-header-cell-wrap-text", wrapText);
    };
    listener();
    this.addRefreshFunction(listener);
  }
  onDisplayedColumnsChanged() {
    super.onDisplayedColumnsChanged();
    if (!this.isAlive()) {
      return;
    }
    this.onHeaderHeightChanged();
  }
  onHeaderHeightChanged() {
    this.refreshSpanHeaderHeight();
  }
  refreshSpanHeaderHeight() {
    const { eGui, column, comp, beans } = this;
    if (!column.isSpanHeaderHeight()) {
      eGui.style.removeProperty("top");
      eGui.style.removeProperty("height");
      comp.addOrRemoveCssClass("ag-header-span-height", false);
      comp.addOrRemoveCssClass("ag-header-span-total", false);
      return;
    }
    const { numberOfParents, isSpanningTotal } = this.column.getColumnGroupPaddingInfo();
    comp.addOrRemoveCssClass("ag-header-span-height", numberOfParents > 0);
    const { columnModel } = beans;
    const headerHeight = columnModel.getColumnHeaderRowHeight();
    if (numberOfParents === 0) {
      comp.addOrRemoveCssClass("ag-header-span-total", false);
      eGui.style.setProperty("top", `0px`);
      eGui.style.setProperty("height", `${headerHeight}px`);
      return;
    }
    comp.addOrRemoveCssClass("ag-header-span-total", isSpanningTotal);
    const pivotMode = columnModel.isPivotMode();
    const groupHeaderHeight = pivotMode ? columnModel.getPivotGroupHeaderHeight() : columnModel.getGroupHeaderHeight();
    const extraHeight = numberOfParents * groupHeaderHeight;
    eGui.style.setProperty("top", `${-extraHeight}px`);
    eGui.style.setProperty("height", `${headerHeight + extraHeight}px`);
  }
  setupAutoHeight(wrapperElement) {
    const { columnModel, resizeObserverService } = this.beans;
    const measureHeight = (timesCalled) => {
      if (!this.isAlive()) {
        return;
      }
      const { paddingTop, paddingBottom, borderBottomWidth, borderTopWidth } = getElementSize(this.getGui());
      const extraHeight = paddingTop + paddingBottom + borderBottomWidth + borderTopWidth;
      const wrapperHeight = wrapperElement.offsetHeight;
      const autoHeight = wrapperHeight + extraHeight;
      if (timesCalled < 5) {
        const doc = this.beans.gos.getDocument();
        const notYetInDom = !doc || !doc.contains(wrapperElement);
        const possiblyNoContentYet = autoHeight == 0;
        if (notYetInDom || possiblyNoContentYet) {
          window.setTimeout(() => measureHeight(timesCalled + 1), 0);
          return;
        }
      }
      columnModel.setColumnHeaderHeight(this.column, autoHeight);
    };
    let isMeasuring = false;
    let stopResizeObserver;
    const checkMeasuring = () => {
      const newValue = this.column.isAutoHeaderHeight();
      if (newValue && !isMeasuring) {
        startMeasuring();
      }
      if (!newValue && isMeasuring) {
        stopMeasuring();
      }
    };
    const startMeasuring = () => {
      isMeasuring = true;
      measureHeight(0);
      this.comp.addOrRemoveCssClass("ag-header-cell-auto-height", true);
      stopResizeObserver = resizeObserverService.observeResize(wrapperElement, () => measureHeight(0));
    };
    const stopMeasuring = () => {
      isMeasuring = false;
      if (stopResizeObserver) {
        stopResizeObserver();
      }
      this.comp.addOrRemoveCssClass("ag-header-cell-auto-height", false);
      stopResizeObserver = void 0;
    };
    checkMeasuring();
    this.addDestroyFunc(() => stopMeasuring());
    this.addManagedListener(this.column, Column.EVENT_WIDTH_CHANGED, () => isMeasuring && measureHeight(0));
    this.addManagedListener(this.eventService, Column.EVENT_SORT_CHANGED, () => {
      if (isMeasuring) {
        window.setTimeout(() => measureHeight(0));
      }
    });
    this.addRefreshFunction(checkMeasuring);
  }
  refreshAriaSort() {
    if (this.sortable) {
      const translate = this.localeService.getLocaleTextFunc();
      const sort = this.beans.sortController.getDisplaySortForColumn(this.column) || null;
      this.comp.setAriaSort(getAriaSortState(sort));
      this.setAriaDescriptionProperty("sort", translate("ariaSortableColumn", "Press ENTER to sort"));
    } else {
      this.comp.setAriaSort();
      this.setAriaDescriptionProperty("sort", null);
    }
  }
  refreshAriaMenu() {
    if (this.menuEnabled) {
      const translate = this.localeService.getLocaleTextFunc();
      this.setAriaDescriptionProperty("menu", translate("ariaMenuColumn", "Press ALT DOWN to open column menu"));
    } else {
      this.setAriaDescriptionProperty("menu", null);
    }
  }
  refreshAriaFilterButton() {
    if (this.openFilterEnabled && !this.menuService.isLegacyMenuEnabled()) {
      const translate = this.localeService.getLocaleTextFunc();
      this.setAriaDescriptionProperty("filterButton", translate("ariaFilterColumn", "Press CTRL ENTER to open filter"));
    } else {
      this.setAriaDescriptionProperty("filterButton", null);
    }
  }
  refreshAriaFiltered() {
    const translate = this.localeService.getLocaleTextFunc();
    const isFilterActive = this.column.isFilterActive();
    if (isFilterActive) {
      this.setAriaDescriptionProperty("filter", translate("ariaColumnFiltered", "Column Filtered"));
    } else {
      this.setAriaDescriptionProperty("filter", null);
    }
  }
  setAriaDescriptionProperty(property, value) {
    if (value != null) {
      this.ariaDescriptionProperties.set(property, value);
    } else {
      this.ariaDescriptionProperties.delete(property);
    }
  }
  announceAriaDescription() {
    if (!this.eGui.contains(this.beans.gos.getActiveDomElement())) {
      return;
    }
    const ariaDescription = Array.from(this.ariaDescriptionProperties.keys()).sort((a, b) => a === "filter" ? -1 : b.charCodeAt(0) - a.charCodeAt(0)).map((key) => this.ariaDescriptionProperties.get(key)).join(". ");
    this.beans.ariaAnnouncementService.announceValue(ariaDescription);
  }
  refreshAria() {
    this.refreshAriaSort();
    this.refreshAriaMenu();
    this.refreshAriaFilterButton();
    this.refreshAriaFiltered();
  }
  addColumnHoverListener() {
    const listener = () => {
      if (!this.gos.get("columnHoverHighlight")) {
        return;
      }
      const isHovered = this.beans.columnHoverService.isHovered(this.column);
      this.comp.addOrRemoveCssClass("ag-column-hover", isHovered);
    };
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_HOVER_CHANGED, listener);
    listener();
  }
  getColId() {
    return this.column.getColId();
  }
  addActiveHeaderMouseListeners() {
    const listener = (e) => this.handleMouseOverChange(e.type === "mouseenter");
    const clickListener = () => this.dispatchColumnMouseEvent(Events.EVENT_COLUMN_HEADER_CLICKED, this.column);
    const contextMenuListener = (event) => this.handleContextMenuMouseEvent(event, void 0, this.column);
    this.addManagedListener(this.getGui(), "mouseenter", listener);
    this.addManagedListener(this.getGui(), "mouseleave", listener);
    this.addManagedListener(this.getGui(), "click", clickListener);
    this.addManagedListener(this.getGui(), "contextmenu", contextMenuListener);
  }
  handleMouseOverChange(isMouseOver) {
    this.setActiveHeader(isMouseOver);
    const eventType = isMouseOver ? Events.EVENT_COLUMN_HEADER_MOUSE_OVER : Events.EVENT_COLUMN_HEADER_MOUSE_LEAVE;
    const event = {
      type: eventType,
      column: this.column
    };
    this.eventService.dispatchEvent(event);
  }
  setActiveHeader(active) {
    this.comp.addOrRemoveCssClass("ag-header-active", active);
  }
  getAnchorElementForMenu(isFilter) {
    const headerComp = this.comp.getUserCompInstance();
    if (headerComp instanceof HeaderComp) {
      return headerComp.getAnchorElementForMenu(isFilter);
    }
    return this.getGui();
  }
  destroy() {
    super.destroy();
    this.refreshFunctions = null;
    this.selectAllFeature = null;
    this.dragSourceElement = null;
    this.userCompDetails = null;
    this.userHeaderClasses = null;
    this.ariaDescriptionProperties = null;
  }
};

// community-modules/core/src/headerRendering/cells/columnGroup/groupResizeFeature.ts
var GroupResizeFeature = class extends BeanStub {
  constructor(comp, eResize, pinned, columnGroup) {
    super();
    this.eResize = eResize;
    this.comp = comp;
    this.pinned = pinned;
    this.columnGroup = columnGroup;
  }
  postConstruct() {
    if (!this.columnGroup.isResizable()) {
      this.comp.setResizableDisplayed(false);
      return;
    }
    const finishedWithResizeFunc = this.horizontalResizeService.addResizeBar({
      eResizeBar: this.eResize,
      onResizeStart: this.onResizeStart.bind(this),
      onResizing: this.onResizing.bind(this, false),
      onResizeEnd: this.onResizing.bind(this, true)
    });
    this.addDestroyFunc(finishedWithResizeFunc);
    if (!this.gos.get("suppressAutoSize")) {
      const skipHeaderOnAutoSize = this.gos.get("skipHeaderOnAutoSize");
      this.eResize.addEventListener("dblclick", () => {
        const keys2 = [];
        const leafCols = this.columnGroup.getDisplayedLeafColumns();
        leafCols.forEach((column) => {
          if (!column.getColDef().suppressAutoSize) {
            keys2.push(column.getColId());
          }
        });
        if (keys2.length > 0) {
          this.columnModel.autoSizeColumns({
            columns: keys2,
            skipHeader: skipHeaderOnAutoSize,
            stopAtGroup: this.columnGroup,
            source: "uiColumnResized"
          });
        }
        this.resizeLeafColumnsToFit("uiColumnResized");
      });
    }
  }
  onResizeStart(shiftKey) {
    const initialValues = this.getInitialValues(shiftKey);
    this.storeLocalValues(initialValues);
    this.toggleColumnResizing(true);
  }
  onResizing(finished, resizeAmount, source = "uiColumnResized") {
    const resizeAmountNormalised = this.normaliseDragChange(resizeAmount);
    const width = this.resizeStartWidth + resizeAmountNormalised;
    this.resizeColumnsFromLocalValues(width, source, finished);
  }
  getInitialValues(shiftKey) {
    const columnsToResize = this.getColumnsToResize();
    const resizeStartWidth = this.getInitialSizeOfColumns(columnsToResize);
    const resizeRatios = this.getSizeRatiosOfColumns(columnsToResize, resizeStartWidth);
    const columnSizeAndRatios = {
      columnsToResize,
      resizeStartWidth,
      resizeRatios
    };
    let groupAfter = null;
    if (shiftKey) {
      groupAfter = this.columnModel.getDisplayedGroupAtDirection(this.columnGroup, "After");
    }
    if (groupAfter) {
      const takeFromLeafCols = groupAfter.getDisplayedLeafColumns();
      const groupAfterColumns = columnSizeAndRatios.groupAfterColumns = takeFromLeafCols.filter((col) => col.isResizable());
      const groupAfterStartWidth = columnSizeAndRatios.groupAfterStartWidth = this.getInitialSizeOfColumns(groupAfterColumns);
      columnSizeAndRatios.groupAfterRatios = this.getSizeRatiosOfColumns(groupAfterColumns, groupAfterStartWidth);
    } else {
      columnSizeAndRatios.groupAfterColumns = void 0;
      columnSizeAndRatios.groupAfterStartWidth = void 0;
      columnSizeAndRatios.groupAfterRatios = void 0;
    }
    return columnSizeAndRatios;
  }
  storeLocalValues(initialValues) {
    const {
      columnsToResize,
      resizeStartWidth,
      resizeRatios,
      groupAfterColumns,
      groupAfterStartWidth,
      groupAfterRatios
    } = initialValues;
    this.resizeCols = columnsToResize;
    this.resizeStartWidth = resizeStartWidth;
    this.resizeRatios = resizeRatios;
    this.resizeTakeFromCols = groupAfterColumns;
    this.resizeTakeFromStartWidth = groupAfterStartWidth;
    this.resizeTakeFromRatios = groupAfterRatios;
  }
  clearLocalValues() {
    this.resizeCols = void 0;
    this.resizeRatios = void 0;
    this.resizeTakeFromCols = void 0;
    this.resizeTakeFromRatios = void 0;
  }
  resizeLeafColumnsToFit(source) {
    const preferredSize = this.autoWidthCalculator.getPreferredWidthForColumnGroup(this.columnGroup);
    const initialValues = this.getInitialValues();
    if (preferredSize > initialValues.resizeStartWidth) {
      this.resizeColumns(initialValues, preferredSize, source, true);
    }
  }
  resizeColumnsFromLocalValues(totalWidth, source, finished = true) {
    var _a, _b, _c;
    if (!this.resizeCols || !this.resizeRatios) {
      return;
    }
    const initialValues = {
      columnsToResize: this.resizeCols,
      resizeStartWidth: this.resizeStartWidth,
      resizeRatios: this.resizeRatios,
      groupAfterColumns: (_a = this.resizeTakeFromCols) != null ? _a : void 0,
      groupAfterStartWidth: (_b = this.resizeTakeFromStartWidth) != null ? _b : void 0,
      groupAfterRatios: (_c = this.resizeTakeFromRatios) != null ? _c : void 0
    };
    this.resizeColumns(initialValues, totalWidth, source, finished);
  }
  resizeColumns(initialValues, totalWidth, source, finished = true) {
    const {
      columnsToResize,
      resizeStartWidth,
      resizeRatios,
      groupAfterColumns,
      groupAfterStartWidth,
      groupAfterRatios
    } = initialValues;
    const resizeSets = [];
    resizeSets.push({
      columns: columnsToResize,
      ratios: resizeRatios,
      width: totalWidth
    });
    if (groupAfterColumns) {
      const diff = totalWidth - resizeStartWidth;
      resizeSets.push({
        columns: groupAfterColumns,
        ratios: groupAfterRatios,
        width: groupAfterStartWidth - diff
      });
    }
    this.columnModel.resizeColumnSets({
      resizeSets,
      finished,
      source
    });
    if (finished) {
      this.toggleColumnResizing(false);
    }
  }
  toggleColumnResizing(resizing) {
    this.comp.addOrRemoveCssClass("ag-column-resizing", resizing);
  }
  getColumnsToResize() {
    const leafCols = this.columnGroup.getDisplayedLeafColumns();
    return leafCols.filter((col) => col.isResizable());
  }
  getInitialSizeOfColumns(columns) {
    return columns.reduce(
      (totalWidth, column) => totalWidth + column.getActualWidth(),
      0
    );
  }
  getSizeRatiosOfColumns(columns, initialSizeOfColumns) {
    return columns.map((column) => column.getActualWidth() / initialSizeOfColumns);
  }
  // optionally inverts the drag, depending on pinned and RTL
  // note - this method is duplicated in RenderedHeaderCell - should refactor out?
  normaliseDragChange(dragChange) {
    let result = dragChange;
    if (this.gos.get("enableRtl")) {
      if (this.pinned !== "left") {
        result *= -1;
      }
    } else if (this.pinned === "right") {
      result *= -1;
    }
    return result;
  }
  destroy() {
    super.destroy();
    this.clearLocalValues();
  }
};
__decorateClass([
  Autowired("horizontalResizeService")
], GroupResizeFeature.prototype, "horizontalResizeService", 2);
__decorateClass([
  Autowired("autoWidthCalculator")
], GroupResizeFeature.prototype, "autoWidthCalculator", 2);
__decorateClass([
  Autowired("columnModel")
], GroupResizeFeature.prototype, "columnModel", 2);
__decorateClass([
  PostConstruct
], GroupResizeFeature.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/cells/columnGroup/groupWidthFeature.ts
var GroupWidthFeature = class extends BeanStub {
  constructor(comp, columnGroup) {
    super();
    // the children can change, we keep destroy functions related to listening to the children here
    this.removeChildListenersFuncs = [];
    this.columnGroup = columnGroup;
    this.comp = comp;
  }
  postConstruct() {
    this.addListenersToChildrenColumns();
    this.addManagedListener(this.columnGroup, ColumnGroup.EVENT_DISPLAYED_CHILDREN_CHANGED, this.onDisplayedChildrenChanged.bind(this));
    this.onWidthChanged();
    this.addDestroyFunc(this.removeListenersOnChildrenColumns.bind(this));
  }
  addListenersToChildrenColumns() {
    this.removeListenersOnChildrenColumns();
    const widthChangedListener = this.onWidthChanged.bind(this);
    this.columnGroup.getLeafColumns().forEach((column) => {
      column.addEventListener("widthChanged", widthChangedListener);
      column.addEventListener("visibleChanged", widthChangedListener);
      this.removeChildListenersFuncs.push(() => {
        column.removeEventListener("widthChanged", widthChangedListener);
        column.removeEventListener("visibleChanged", widthChangedListener);
      });
    });
  }
  removeListenersOnChildrenColumns() {
    this.removeChildListenersFuncs.forEach((func) => func());
    this.removeChildListenersFuncs = [];
  }
  onDisplayedChildrenChanged() {
    this.addListenersToChildrenColumns();
    this.onWidthChanged();
  }
  onWidthChanged() {
    const columnWidth = this.columnGroup.getActualWidth();
    this.comp.setWidth(`${columnWidth}px`);
    this.comp.addOrRemoveCssClass("ag-hidden", columnWidth === 0);
  }
};
__decorateClass([
  PostConstruct
], GroupWidthFeature.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/cells/columnGroup/headerGroupCellCtrl.ts
var HeaderGroupCellCtrl = class extends AbstractHeaderCellCtrl {
  constructor(columnGroup, beans, parentRowCtrl) {
    super(columnGroup, beans, parentRowCtrl);
    this.onSuppressColMoveChange = () => {
      if (!this.isAlive() || this.isSuppressMoving()) {
        this.removeDragSource();
      } else {
        if (!this.dragSource) {
          const eGui = this.getGui();
          this.setDragSource(eGui);
        }
      }
    };
    this.column = columnGroup;
  }
  setComp(comp, eGui, eResize) {
    this.comp = comp;
    this.setGui(eGui);
    this.displayName = this.beans.columnModel.getDisplayNameForColumnGroup(this.column, "header");
    this.addClasses();
    this.setupMovingCss();
    this.setupExpandable();
    this.setupTooltip();
    this.addDestroyFunc(() => {
      if (this.tooltipFeature) {
        this.tooltipFeature = this.destroyBean(this.tooltipFeature);
      }
    });
    this.setupUserComp();
    this.addHeaderMouseListeners();
    const pinned = this.getParentRowCtrl().getPinned();
    const leafCols = this.column.getProvidedColumnGroup().getLeafColumns();
    this.createManagedBean(new HoverFeature(leafCols, eGui));
    this.createManagedBean(new SetLeftFeature(this.column, eGui, this.beans));
    this.createManagedBean(new GroupWidthFeature(comp, this.column));
    this.resizeFeature = this.createManagedBean(new GroupResizeFeature(comp, eResize, pinned, this.column));
    this.createManagedBean(new ManagedFocusFeature(
      eGui,
      {
        shouldStopEventPropagation: this.shouldStopEventPropagation.bind(this),
        onTabKeyDown: () => void 0,
        handleKeyDown: this.handleKeyDown.bind(this),
        onFocusIn: this.onFocusIn.bind(this)
      }
    ));
    this.addManagedPropertyListener(Events.EVENT_SUPPRESS_COLUMN_MOVE_CHANGED, this.onSuppressColMoveChange);
    this.addResizeAndMoveKeyboardListeners();
  }
  resizeHeader(delta, shiftKey) {
    if (!this.resizeFeature) {
      return;
    }
    const initialValues = this.resizeFeature.getInitialValues(shiftKey);
    this.resizeFeature.resizeColumns(initialValues, initialValues.resizeStartWidth + delta, "uiColumnResized", true);
  }
  moveHeader(hDirection) {
    const { beans, eGui, column, gos, ctrlsService } = this;
    const isRtl = gos.get("enableRtl");
    const isLeft = hDirection === 0 /* Left */;
    const pinned = this.getPinned();
    const rect = eGui.getBoundingClientRect();
    const left = rect.left;
    const width = rect.width;
    const xPosition = ColumnMoveHelper.normaliseX(
      isLeft !== isRtl ? left - 20 : left + width + 20,
      pinned,
      true,
      gos,
      ctrlsService
    );
    const id = column.getGroupId();
    const headerPosition = this.focusService.getFocusedHeader();
    ColumnMoveHelper.attemptMoveColumns({
      allMovingColumns: this.column.getLeafColumns(),
      isFromHeader: true,
      hDirection,
      xPosition,
      pinned,
      fromEnter: false,
      fakeEvent: false,
      gos,
      columnModel: beans.columnModel
    });
    const displayedLeafColumns = column.getDisplayedLeafColumns();
    const targetColumn = isLeft ? displayedLeafColumns[0] : last(displayedLeafColumns);
    this.ctrlsService.getGridBodyCtrl().getScrollFeature().ensureColumnVisible(targetColumn, "auto");
    if (!this.isAlive() && headerPosition) {
      this.restoreFocus(id, column, headerPosition);
    }
  }
  restoreFocus(groupId, previousColumnGroup, previousPosition) {
    const leafCols = previousColumnGroup.getLeafColumns();
    if (!leafCols.length) {
      return;
    }
    const parent = leafCols[0].getParent();
    if (!parent) {
      return;
    }
    const newColumnGroup = this.findGroupWidthId(parent, groupId);
    if (newColumnGroup) {
      this.focusService.focusHeaderPosition({
        headerPosition: __spreadProps(__spreadValues({}, previousPosition), {
          column: newColumnGroup
        })
      });
    }
  }
  findGroupWidthId(columnGroup, id) {
    while (columnGroup) {
      if (columnGroup.getGroupId() === id) {
        return columnGroup;
      }
      columnGroup = columnGroup.getParent();
    }
    return null;
  }
  resizeLeafColumnsToFit(source) {
    if (!this.resizeFeature) {
      return;
    }
    this.resizeFeature.resizeLeafColumnsToFit(source);
  }
  setupUserComp() {
    const params = this.gos.addGridCommonParams({
      displayName: this.displayName,
      columnGroup: this.column,
      setExpanded: (expanded) => {
        this.beans.columnModel.setColumnGroupOpened(this.column.getProvidedColumnGroup(), expanded, "gridInitializing");
      },
      setTooltip: (value, shouldDisplayTooltip) => {
        this.setupTooltip(value, shouldDisplayTooltip);
      }
    });
    const compDetails = this.userComponentFactory.getHeaderGroupCompDetails(params);
    this.comp.setUserCompDetails(compDetails);
  }
  addHeaderMouseListeners() {
    const listener = (e) => this.handleMouseOverChange(e.type === "mouseenter");
    const clickListener = () => this.dispatchColumnMouseEvent(Events.EVENT_COLUMN_HEADER_CLICKED, this.column.getProvidedColumnGroup());
    const contextMenuListener = (event) => this.handleContextMenuMouseEvent(event, void 0, this.column.getProvidedColumnGroup());
    this.addManagedListener(this.getGui(), "mouseenter", listener);
    this.addManagedListener(this.getGui(), "mouseleave", listener);
    this.addManagedListener(this.getGui(), "click", clickListener);
    this.addManagedListener(this.getGui(), "contextmenu", contextMenuListener);
  }
  handleMouseOverChange(isMouseOver) {
    const eventType = isMouseOver ? Events.EVENT_COLUMN_HEADER_MOUSE_OVER : Events.EVENT_COLUMN_HEADER_MOUSE_LEAVE;
    const event = {
      type: eventType,
      column: this.column.getProvidedColumnGroup()
    };
    this.eventService.dispatchEvent(event);
  }
  setupTooltip(value, shouldDisplayTooltip) {
    if (this.tooltipFeature) {
      this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    }
    const colGroupDef = this.column.getColGroupDef();
    const isTooltipWhenTruncated = this.gos.get("tooltipShowMode") === "whenTruncated";
    const eGui = this.eGui;
    if (!shouldDisplayTooltip && isTooltipWhenTruncated && !(colGroupDef == null ? void 0 : colGroupDef.headerGroupComponent)) {
      shouldDisplayTooltip = () => {
        const textEl = eGui.querySelector(".ag-header-group-text");
        if (!textEl) {
          return true;
        }
        return textEl.scrollWidth > textEl.clientWidth;
      };
    }
    const tooltipCtrl = {
      getColumn: () => this.column,
      getGui: () => eGui,
      getLocation: () => "headerGroup",
      getTooltipValue: () => value != null ? value : colGroupDef && colGroupDef.headerTooltip,
      shouldDisplayTooltip
    };
    if (colGroupDef) {
      tooltipCtrl.getColDef = () => colGroupDef;
    }
    this.createBean(new TooltipFeature(tooltipCtrl));
  }
  setupExpandable() {
    const providedColGroup = this.column.getProvidedColumnGroup();
    this.refreshExpanded();
    this.addManagedListener(providedColGroup, ProvidedColumnGroup.EVENT_EXPANDABLE_CHANGED, this.refreshExpanded.bind(this));
    this.addManagedListener(providedColGroup, ProvidedColumnGroup.EVENT_EXPANDED_CHANGED, this.refreshExpanded.bind(this));
  }
  refreshExpanded() {
    const column = this.column;
    this.expandable = column.isExpandable();
    const expanded = column.isExpanded();
    if (this.expandable) {
      this.comp.setAriaExpanded(expanded ? "true" : "false");
    } else {
      this.comp.setAriaExpanded(void 0);
    }
  }
  getColId() {
    return this.column.getUniqueId();
  }
  addClasses() {
    const colGroupDef = this.column.getColGroupDef();
    const classes = CssClassApplier.getHeaderClassesFromColDef(colGroupDef, this.gos, null, this.column);
    if (this.column.isPadding()) {
      classes.push("ag-header-group-cell-no-group");
      const leafCols = this.column.getLeafColumns();
      if (leafCols.every((col) => col.isSpanHeaderHeight())) {
        classes.push("ag-header-span-height");
      }
    } else {
      classes.push("ag-header-group-cell-with-group");
    }
    classes.forEach((c) => this.comp.addOrRemoveCssClass(c, true));
  }
  setupMovingCss() {
    const providedColumnGroup = this.column.getProvidedColumnGroup();
    const leafColumns = providedColumnGroup.getLeafColumns();
    const listener = () => this.comp.addOrRemoveCssClass("ag-header-cell-moving", this.column.isMoving());
    leafColumns.forEach((col) => {
      this.addManagedListener(col, Column.EVENT_MOVING_CHANGED, listener);
    });
    listener();
  }
  onFocusIn(e) {
    if (!this.eGui.contains(e.relatedTarget)) {
      const rowIndex = this.getRowIndex();
      this.beans.focusService.setFocusedHeader(rowIndex, this.column);
    }
  }
  handleKeyDown(e) {
    super.handleKeyDown(e);
    const wrapperHasFocus = this.getWrapperHasFocus();
    if (!this.expandable || !wrapperHasFocus) {
      return;
    }
    if (e.key === KeyCode.ENTER) {
      const column = this.column;
      const newExpandedValue = !column.isExpanded();
      this.beans.columnModel.setColumnGroupOpened(column.getProvidedColumnGroup(), newExpandedValue, "uiColumnExpanded");
    }
  }
  // unlike columns, this will only get called once, as we don't react on props on column groups
  // (we will always destroy and recreate this comp if something changes)
  setDragSource(eHeaderGroup) {
    if (!this.isAlive() || this.isSuppressMoving()) {
      return;
    }
    this.removeDragSource();
    if (!eHeaderGroup) {
      return;
    }
    const { beans, column, displayName, gos, dragAndDropService } = this;
    const { columnModel } = beans;
    const allLeafColumns = column.getProvidedColumnGroup().getLeafColumns();
    let hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
    const dragSource = this.dragSource = {
      type: 1 /* HeaderCell */,
      eElement: eHeaderGroup,
      getDefaultIconName: () => hideColumnOnExit ? DragAndDropService.ICON_HIDE : DragAndDropService.ICON_NOT_ALLOWED,
      dragItemName: displayName,
      // we add in the original group leaf columns, so we move both visible and non-visible items
      getDragItem: () => this.getDragItemForGroup(column),
      onDragStarted: () => {
        hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
        allLeafColumns.forEach((col) => col.setMoving(true, "uiColumnDragged"));
      },
      onDragStopped: () => allLeafColumns.forEach((col) => col.setMoving(false, "uiColumnDragged")),
      onGridEnter: (dragItem) => {
        var _a;
        if (hideColumnOnExit) {
          const unlockedColumns = ((_a = dragItem == null ? void 0 : dragItem.columns) == null ? void 0 : _a.filter((col) => !col.getColDef().lockVisible)) || [];
          columnModel.setColumnsVisible(unlockedColumns, true, "uiColumnMoved");
        }
      },
      onGridExit: (dragItem) => {
        var _a;
        if (hideColumnOnExit) {
          const unlockedColumns = ((_a = dragItem == null ? void 0 : dragItem.columns) == null ? void 0 : _a.filter((col) => !col.getColDef().lockVisible)) || [];
          columnModel.setColumnsVisible(unlockedColumns, false, "uiColumnMoved");
        }
      }
    };
    dragAndDropService.addDragSource(dragSource, true);
  }
  // when moving the columns, we want to move all the columns (contained within the DragItem) in this group in one go,
  // and in the order they are currently in the screen.
  getDragItemForGroup(columnGroup) {
    const allColumnsOriginalOrder = columnGroup.getProvidedColumnGroup().getLeafColumns();
    const visibleState = {};
    allColumnsOriginalOrder.forEach((column) => visibleState[column.getId()] = column.isVisible());
    const allColumnsCurrentOrder = [];
    this.beans.columnModel.getAllDisplayedColumns().forEach((column) => {
      if (allColumnsOriginalOrder.indexOf(column) >= 0) {
        allColumnsCurrentOrder.push(column);
        removeFromArray(allColumnsOriginalOrder, column);
      }
    });
    allColumnsOriginalOrder.forEach((column) => allColumnsCurrentOrder.push(column));
    return {
      columns: allColumnsCurrentOrder,
      visibleState
    };
  }
  isSuppressMoving() {
    let childSuppressesMoving = false;
    this.column.getLeafColumns().forEach((column) => {
      if (column.getColDef().suppressMovable || column.getColDef().lockPosition) {
        childSuppressesMoving = true;
      }
    });
    const result = childSuppressesMoving || this.gos.get("suppressMovableColumns");
    return result;
  }
};

// community-modules/core/src/headerRendering/row/headerRowCtrl.ts
var instanceIdSequence5 = 0;
var HeaderRowCtrl = class extends BeanStub {
  constructor(rowIndex, pinned, type) {
    super();
    this.instanceId = instanceIdSequence5++;
    this.rowIndex = rowIndex;
    this.pinned = pinned;
    this.type = type;
    const typeClass = type == "group" /* COLUMN_GROUP */ ? `ag-header-row-column-group` : type == "filter" /* FLOATING_FILTER */ ? `ag-header-row-column-filter` : `ag-header-row-column`;
    this.headerRowClass = `ag-header-row ${typeClass}`;
  }
  postConstruct() {
    this.isPrintLayout = this.gos.isDomLayout("print");
    this.isEnsureDomOrder = this.gos.get("ensureDomOrder");
  }
  getInstanceId() {
    return this.instanceId;
  }
  /**
   * 
   * @param comp Proxy to the actual component
   * @param initCompState Should the component be initialised with the current state of the controller. Default: true
   */
  setComp(comp, initCompState = true) {
    this.comp = comp;
    if (initCompState) {
      this.onRowHeightChanged();
      this.onVirtualColumnsChanged();
    }
    this.setWidth();
    this.addEventListeners();
  }
  getHeaderRowClass() {
    return this.headerRowClass;
  }
  getAriaRowIndex() {
    return this.rowIndex + 1;
  }
  addEventListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_RESIZED, this.onColumnResized.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_VIRTUAL_COLUMNS_CHANGED, (params) => this.onVirtualColumnsChanged(params.afterScroll));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_HEADER_HEIGHT_CHANGED, this.onRowHeightChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_GRID_STYLES_CHANGED, this.onRowHeightChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_ADVANCED_FILTER_ENABLED_CHANGED, this.onRowHeightChanged.bind(this));
    this.addManagedPropertyListener("domLayout", this.onDisplayedColumnsChanged.bind(this));
    this.addManagedPropertyListener("ensureDomOrder", (e) => this.isEnsureDomOrder = e.currentValue);
    this.addManagedPropertyListener("headerHeight", this.onRowHeightChanged.bind(this));
    this.addManagedPropertyListener("pivotHeaderHeight", this.onRowHeightChanged.bind(this));
    this.addManagedPropertyListener("groupHeaderHeight", this.onRowHeightChanged.bind(this));
    this.addManagedPropertyListener("pivotGroupHeaderHeight", this.onRowHeightChanged.bind(this));
    this.addManagedPropertyListener("floatingFiltersHeight", this.onRowHeightChanged.bind(this));
  }
  getHeaderCellCtrl(column) {
    if (!this.headerCellCtrls) {
      return;
    }
    return values(this.headerCellCtrls).find((cellCtrl) => cellCtrl.getColumnGroupChild() === column);
  }
  onDisplayedColumnsChanged() {
    this.isPrintLayout = this.gos.isDomLayout("print");
    this.onVirtualColumnsChanged();
    this.setWidth();
    this.onRowHeightChanged();
  }
  getType() {
    return this.type;
  }
  onColumnResized() {
    this.setWidth();
  }
  setWidth() {
    const width = this.getWidthForRow();
    this.comp.setWidth(`${width}px`);
  }
  getWidthForRow() {
    const { columnModel } = this.beans;
    if (this.isPrintLayout) {
      const pinned = this.pinned != null;
      if (pinned) {
        return 0;
      }
      return columnModel.getContainerWidth("right") + columnModel.getContainerWidth("left") + columnModel.getContainerWidth(null);
    }
    return columnModel.getContainerWidth(this.pinned);
  }
  onRowHeightChanged() {
    var { topOffset, rowHeight } = this.getTopAndHeight();
    this.comp.setTop(topOffset + "px");
    this.comp.setHeight(rowHeight + "px");
  }
  getTopAndHeight() {
    const { columnModel, filterManager } = this.beans;
    let headerRowCount = columnModel.getHeaderRowCount();
    const sizes = [];
    let numberOfFloating = 0;
    if (filterManager.hasFloatingFilters()) {
      headerRowCount++;
      numberOfFloating = 1;
    }
    const groupHeight = columnModel.getColumnGroupHeaderRowHeight();
    const headerHeight = columnModel.getColumnHeaderRowHeight();
    const numberOfNonGroups = 1 + numberOfFloating;
    const numberOfGroups = headerRowCount - numberOfNonGroups;
    for (let i = 0; i < numberOfGroups; i++) {
      sizes.push(groupHeight);
    }
    sizes.push(headerHeight);
    for (let i = 0; i < numberOfFloating; i++) {
      sizes.push(columnModel.getFloatingFiltersHeight());
    }
    let topOffset = 0;
    for (let i = 0; i < this.rowIndex; i++) {
      topOffset += sizes[i];
    }
    const rowHeight = sizes[this.rowIndex];
    return { topOffset, rowHeight };
  }
  getPinned() {
    return this.pinned;
  }
  getRowIndex() {
    return this.rowIndex;
  }
  onVirtualColumnsChanged(afterScroll = false) {
    const ctrlsToDisplay = this.getHeaderCtrls();
    const forceOrder = this.isEnsureDomOrder || this.isPrintLayout;
    this.comp.setHeaderCtrls(ctrlsToDisplay, forceOrder, afterScroll);
  }
  getHeaderCtrls() {
    const oldCtrls = this.headerCellCtrls;
    this.headerCellCtrls = /* @__PURE__ */ new Map();
    const columns = this.getColumnsInViewport();
    for (const child of columns) {
      this.recycleAndCreateHeaderCtrls(child, oldCtrls);
    }
    const isFocusedAndDisplayed = (ctrl) => {
      const { focusService, columnModel } = this.beans;
      const isFocused = focusService.isHeaderWrapperFocused(ctrl);
      if (!isFocused) {
        return false;
      }
      const isDisplayed = columnModel.isDisplayed(ctrl.getColumnGroupChild());
      return isDisplayed;
    };
    if (oldCtrls) {
      for (const [id, oldCtrl] of oldCtrls) {
        const keepCtrl = isFocusedAndDisplayed(oldCtrl);
        if (keepCtrl) {
          this.headerCellCtrls.set(id, oldCtrl);
        } else {
          this.destroyBean(oldCtrl);
        }
      }
    }
    const ctrlsToDisplay = Array.from(this.headerCellCtrls.values());
    return ctrlsToDisplay;
  }
  recycleAndCreateHeaderCtrls(headerColumn, oldCtrls) {
    if (!this.headerCellCtrls) {
      return;
    }
    if (headerColumn.isEmptyGroup()) {
      return;
    }
    const idOfChild = headerColumn.getUniqueId();
    let headerCtrl;
    if (oldCtrls) {
      headerCtrl = oldCtrls.get(idOfChild);
      oldCtrls.delete(idOfChild);
    }
    const forOldColumn = headerCtrl && headerCtrl.getColumnGroupChild() != headerColumn;
    if (forOldColumn) {
      this.destroyBean(headerCtrl);
      headerCtrl = void 0;
    }
    if (headerCtrl == null) {
      switch (this.type) {
        case "filter" /* FLOATING_FILTER */:
          headerCtrl = this.createBean(new HeaderFilterCellCtrl(headerColumn, this.beans, this));
          break;
        case "group" /* COLUMN_GROUP */:
          headerCtrl = this.createBean(new HeaderGroupCellCtrl(headerColumn, this.beans, this));
          break;
        default:
          headerCtrl = this.createBean(new HeaderCellCtrl(headerColumn, this.beans, this));
          break;
      }
    }
    this.headerCellCtrls.set(idOfChild, headerCtrl);
  }
  getColumnsInViewport() {
    return this.isPrintLayout ? this.getColumnsInViewportPrintLayout() : this.getColumnsInViewportNormalLayout();
  }
  getColumnsInViewportPrintLayout() {
    if (this.pinned != null) {
      return [];
    }
    let viewportColumns = [];
    const actualDepth = this.getActualDepth();
    const { columnModel } = this.beans;
    ["left", null, "right"].forEach((pinned) => {
      const items = columnModel.getVirtualHeaderGroupRow(pinned, actualDepth);
      viewportColumns = viewportColumns.concat(items);
    });
    return viewportColumns;
  }
  getActualDepth() {
    return this.type == "filter" /* FLOATING_FILTER */ ? this.rowIndex - 1 : this.rowIndex;
  }
  getColumnsInViewportNormalLayout() {
    return this.beans.columnModel.getVirtualHeaderGroupRow(this.pinned, this.getActualDepth());
  }
  focusHeader(column, event) {
    if (!this.headerCellCtrls) {
      return false;
    }
    const allCtrls = Array.from(this.headerCellCtrls.values());
    const ctrl = allCtrls.find((ctrl2) => ctrl2.getColumnGroupChild() == column);
    if (!ctrl) {
      return false;
    }
    return ctrl.focus(event);
  }
  destroy() {
    if (this.headerCellCtrls) {
      this.headerCellCtrls.forEach((ctrl) => {
        this.destroyBean(ctrl);
      });
    }
    this.headerCellCtrls = void 0;
    super.destroy();
  }
};
__decorateClass([
  Autowired("beans")
], HeaderRowCtrl.prototype, "beans", 2);
__decorateClass([
  PostConstruct
], HeaderRowCtrl.prototype, "postConstruct", 1);

// community-modules/core/src/headerRendering/rowContainer/headerRowContainerCtrl.ts
var HeaderRowContainerCtrl = class extends BeanStub {
  constructor(pinned) {
    super();
    this.hidden = false;
    this.includeFloatingFilter = false;
    this.groupsRowCtrls = [];
    this.pinned = pinned;
  }
  setComp(comp, eGui) {
    this.comp = comp;
    this.eViewport = eGui;
    this.setupCenterWidth();
    this.setupPinnedWidth();
    this.setupDragAndDrop(this.eViewport);
    this.addManagedListener(this.eventService, Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_ADVANCED_FILTER_ENABLED_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.ctrlsService.registerHeaderContainer(this, this.pinned);
    if (this.columnModel.isReady()) {
      this.refresh();
    }
  }
  setupDragAndDrop(dropContainer) {
    const bodyDropTarget = new BodyDropTarget(this.pinned, dropContainer);
    this.createManagedBean(bodyDropTarget);
  }
  refresh(keepColumns = false) {
    const sequence = new NumberSequence();
    const focusedHeaderPosition = this.focusService.getFocusHeaderToUseAfterRefresh();
    const refreshColumnGroups = () => {
      const groupRowCount = this.columnModel.getHeaderRowCount() - 1;
      this.groupsRowCtrls = this.destroyBeans(this.groupsRowCtrls);
      for (let i = 0; i < groupRowCount; i++) {
        const ctrl = this.createBean(new HeaderRowCtrl(sequence.next(), this.pinned, "group" /* COLUMN_GROUP */));
        this.groupsRowCtrls.push(ctrl);
      }
    };
    const refreshColumns = () => {
      const rowIndex = sequence.next();
      const needNewInstance = !this.hidden && (this.columnsRowCtrl == null || !keepColumns || this.columnsRowCtrl.getRowIndex() !== rowIndex);
      const shouldDestroyInstance = needNewInstance || this.hidden;
      if (shouldDestroyInstance) {
        this.columnsRowCtrl = this.destroyBean(this.columnsRowCtrl);
      }
      if (needNewInstance) {
        this.columnsRowCtrl = this.createBean(new HeaderRowCtrl(rowIndex, this.pinned, "column" /* COLUMN */));
      }
    };
    const refreshFilters = () => {
      this.includeFloatingFilter = this.filterManager.hasFloatingFilters() && !this.hidden;
      const destroyPreviousComp = () => {
        this.filtersRowCtrl = this.destroyBean(this.filtersRowCtrl);
      };
      if (!this.includeFloatingFilter) {
        destroyPreviousComp();
        return;
      }
      const rowIndex = sequence.next();
      if (this.filtersRowCtrl) {
        const rowIndexMismatch = this.filtersRowCtrl.getRowIndex() !== rowIndex;
        if (!keepColumns || rowIndexMismatch) {
          destroyPreviousComp();
        }
      }
      if (!this.filtersRowCtrl) {
        this.filtersRowCtrl = this.createBean(new HeaderRowCtrl(rowIndex, this.pinned, "filter" /* FLOATING_FILTER */));
      }
    };
    refreshColumnGroups();
    refreshColumns();
    refreshFilters();
    const allCtrls = this.getAllCtrls();
    this.comp.setCtrls(allCtrls);
    this.restoreFocusOnHeader(focusedHeaderPosition);
  }
  restoreFocusOnHeader(position) {
    if (position == null || position.column.getPinned() != this.pinned) {
      return;
    }
    this.focusService.focusHeaderPosition({ headerPosition: position });
  }
  getAllCtrls() {
    const res = [...this.groupsRowCtrls];
    if (this.columnsRowCtrl) {
      res.push(this.columnsRowCtrl);
    }
    if (this.filtersRowCtrl) {
      res.push(this.filtersRowCtrl);
    }
    return res;
  }
  // grid cols have changed - this also means the number of rows in the header can have
  // changed. so we remove all the old rows and insert new ones for a complete refresh
  onGridColumnsChanged() {
    this.refresh(true);
  }
  onDisplayedColumnsChanged() {
    const includeFloatingFilter = this.filterManager.hasFloatingFilters() && !this.hidden;
    if (this.includeFloatingFilter !== includeFloatingFilter) {
      this.refresh(true);
    }
  }
  setupCenterWidth() {
    if (this.pinned != null) {
      return;
    }
    this.createManagedBean(new CenterWidthFeature((width) => this.comp.setCenterWidth(`${width}px`), true));
  }
  setHorizontalScroll(offset) {
    this.comp.setViewportScrollLeft(offset);
  }
  setupPinnedWidth() {
    if (this.pinned == null) {
      return;
    }
    const pinningLeft = this.pinned === "left";
    const pinningRight = this.pinned === "right";
    this.hidden = true;
    const listener = () => {
      const width = pinningLeft ? this.pinnedWidthService.getPinnedLeftWidth() : this.pinnedWidthService.getPinnedRightWidth();
      if (width == null) {
        return;
      }
      const hidden = width == 0;
      const hiddenChanged = this.hidden !== hidden;
      const isRtl = this.gos.get("enableRtl");
      const scrollbarWidth = this.gos.getScrollbarWidth();
      const addPaddingForScrollbar = this.scrollVisibleService.isVerticalScrollShowing() && (isRtl && pinningLeft || !isRtl && pinningRight);
      const widthWithPadding = addPaddingForScrollbar ? width + scrollbarWidth : width;
      this.comp.setPinnedContainerWidth(`${widthWithPadding}px`);
      this.comp.setDisplayed(!hidden);
      if (hiddenChanged) {
        this.hidden = hidden;
        this.refresh();
      }
    };
    this.addManagedListener(this.eventService, Events.EVENT_LEFT_PINNED_WIDTH_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_RIGHT_PINNED_WIDTH_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_SCROLL_VISIBILITY_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_SCROLLBAR_WIDTH_CHANGED, listener);
  }
  getHeaderCtrlForColumn(column) {
    if (column instanceof Column) {
      if (!this.columnsRowCtrl) {
        return;
      }
      return this.columnsRowCtrl.getHeaderCellCtrl(column);
    }
    if (this.groupsRowCtrls.length === 0) {
      return;
    }
    for (let i = 0; i < this.groupsRowCtrls.length; i++) {
      const ctrl = this.groupsRowCtrls[i].getHeaderCellCtrl(column);
      if (ctrl) {
        return ctrl;
      }
    }
  }
  getHtmlElementForColumnHeader(column) {
    const cellCtrl = this.getHeaderCtrlForColumn(column);
    if (!cellCtrl) {
      return null;
    }
    return cellCtrl.getGui();
  }
  getRowType(rowIndex) {
    const allCtrls = this.getAllCtrls();
    const ctrl = allCtrls[rowIndex];
    return ctrl ? ctrl.getType() : void 0;
  }
  focusHeader(rowIndex, column, event) {
    const allCtrls = this.getAllCtrls();
    const ctrl = allCtrls[rowIndex];
    if (!ctrl) {
      return false;
    }
    return ctrl.focusHeader(column, event);
  }
  getViewport() {
    return this.eViewport;
  }
  getRowCount() {
    return this.groupsRowCtrls.length + (this.columnsRowCtrl ? 1 : 0) + (this.filtersRowCtrl ? 1 : 0);
  }
  destroy() {
    if (this.filtersRowCtrl) {
      this.filtersRowCtrl = this.destroyBean(this.filtersRowCtrl);
    }
    if (this.columnsRowCtrl) {
      this.columnsRowCtrl = this.destroyBean(this.columnsRowCtrl);
    }
    if (this.groupsRowCtrls && this.groupsRowCtrls.length) {
      this.groupsRowCtrls = this.destroyBeans(this.groupsRowCtrls);
    }
    super.destroy();
  }
};
__decorateClass([
  Autowired("ctrlsService")
], HeaderRowContainerCtrl.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("scrollVisibleService")
], HeaderRowContainerCtrl.prototype, "scrollVisibleService", 2);
__decorateClass([
  Autowired("pinnedWidthService")
], HeaderRowContainerCtrl.prototype, "pinnedWidthService", 2);
__decorateClass([
  Autowired("columnModel")
], HeaderRowContainerCtrl.prototype, "columnModel", 2);
__decorateClass([
  Autowired("focusService")
], HeaderRowContainerCtrl.prototype, "focusService", 2);
__decorateClass([
  Autowired("filterManager")
], HeaderRowContainerCtrl.prototype, "filterManager", 2);

// community-modules/core/src/headerRendering/rowContainer/headerRowContainerComp.ts
var _HeaderRowContainerComp = class _HeaderRowContainerComp extends Component {
  constructor(pinned) {
    super();
    this.headerRowComps = {};
    this.rowCompsList = [];
    this.pinned = pinned;
  }
  init() {
    this.selectAndSetTemplate();
    const compProxy = {
      setDisplayed: (displayed) => this.setDisplayed(displayed),
      setCtrls: (ctrls) => this.setCtrls(ctrls),
      // only gets called for center section
      setCenterWidth: (width) => this.eCenterContainer.style.width = width,
      setViewportScrollLeft: (left) => this.getGui().scrollLeft = left,
      // only gets called for pinned sections
      setPinnedContainerWidth: (width) => {
        const eGui = this.getGui();
        eGui.style.width = width;
        eGui.style.maxWidth = width;
        eGui.style.minWidth = width;
      }
    };
    const ctrl = this.createManagedBean(new HeaderRowContainerCtrl(this.pinned));
    ctrl.setComp(compProxy, this.getGui());
  }
  selectAndSetTemplate() {
    const pinnedLeft = this.pinned == "left";
    const pinnedRight = this.pinned == "right";
    const template = pinnedLeft ? _HeaderRowContainerComp.PINNED_LEFT_TEMPLATE : pinnedRight ? _HeaderRowContainerComp.PINNED_RIGHT_TEMPLATE : _HeaderRowContainerComp.CENTER_TEMPLATE;
    this.setTemplate(template);
    this.eRowContainer = this.eCenterContainer ? this.eCenterContainer : this.getGui();
  }
  destroyRowComps() {
    this.setCtrls([]);
  }
  destroyRowComp(rowComp) {
    this.destroyBean(rowComp);
    this.eRowContainer.removeChild(rowComp.getGui());
  }
  setCtrls(ctrls) {
    const oldRowComps = this.headerRowComps;
    this.headerRowComps = {};
    this.rowCompsList = [];
    let prevGui;
    const appendEnsuringDomOrder = (rowComp) => {
      const eGui = rowComp.getGui();
      const notAlreadyIn = eGui.parentElement != this.eRowContainer;
      if (notAlreadyIn) {
        this.eRowContainer.appendChild(eGui);
      }
      if (prevGui) {
        ensureDomOrder(this.eRowContainer, eGui, prevGui);
      }
      prevGui = eGui;
    };
    ctrls.forEach((ctrl) => {
      const ctrlId = ctrl.getInstanceId();
      const existingComp = oldRowComps[ctrlId];
      delete oldRowComps[ctrlId];
      const rowComp = existingComp ? existingComp : this.createBean(new HeaderRowComp(ctrl));
      this.headerRowComps[ctrlId] = rowComp;
      this.rowCompsList.push(rowComp);
      appendEnsuringDomOrder(rowComp);
    });
    getAllValuesInObject(oldRowComps).forEach((c) => this.destroyRowComp(c));
  }
};
_HeaderRowContainerComp.PINNED_LEFT_TEMPLATE = /* html */
`<div class="ag-pinned-left-header" role="rowgroup"></div>`;
_HeaderRowContainerComp.PINNED_RIGHT_TEMPLATE = /* html */
`<div class="ag-pinned-right-header" role="rowgroup"></div>`;
_HeaderRowContainerComp.CENTER_TEMPLATE = /* html */
`<div class="ag-header-viewport" role="presentation">
            <div class="ag-header-container" ref="eCenterContainer" role="rowgroup"></div>
        </div>`;
__decorateClass([
  RefSelector("eCenterContainer")
], _HeaderRowContainerComp.prototype, "eCenterContainer", 2);
__decorateClass([
  PostConstruct
], _HeaderRowContainerComp.prototype, "init", 1);
__decorateClass([
  PreDestroy
], _HeaderRowContainerComp.prototype, "destroyRowComps", 1);
var HeaderRowContainerComp = _HeaderRowContainerComp;

// community-modules/core/src/headerRendering/common/headerNavigationService.ts
var HeaderNavigationDirection = /* @__PURE__ */ ((HeaderNavigationDirection2) => {
  HeaderNavigationDirection2[HeaderNavigationDirection2["UP"] = 0] = "UP";
  HeaderNavigationDirection2[HeaderNavigationDirection2["DOWN"] = 1] = "DOWN";
  HeaderNavigationDirection2[HeaderNavigationDirection2["LEFT"] = 2] = "LEFT";
  HeaderNavigationDirection2[HeaderNavigationDirection2["RIGHT"] = 3] = "RIGHT";
  return HeaderNavigationDirection2;
})(HeaderNavigationDirection || {});
var HeaderNavigationService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.currentHeaderRowWithoutSpan = -1;
  }
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      this.gridBodyCon = p.gridBodyCtrl;
    });
    const eDocument = this.gos.getDocument();
    this.addManagedListener(eDocument, "mousedown", () => this.setCurrentHeaderRowWithoutSpan(-1));
  }
  getHeaderRowCount() {
    const centerHeaderContainer = this.ctrlsService.getHeaderRowContainerCtrl();
    return centerHeaderContainer ? centerHeaderContainer.getRowCount() : 0;
  }
  /*
   * This method navigates grid header vertically
   * @return {boolean} true to preventDefault on the event that caused this navigation.
   */
  navigateVertically(direction, fromHeader, event) {
    if (!fromHeader) {
      fromHeader = this.focusService.getFocusedHeader();
    }
    if (!fromHeader) {
      return false;
    }
    const { headerRowIndex, column } = fromHeader;
    const rowLen = this.getHeaderRowCount();
    const isUp = direction === 0 /* UP */;
    let { headerRowIndex: nextRow, column: nextFocusColumn, headerRowIndexWithoutSpan } = isUp ? this.headerPositionUtils.getColumnVisibleParent(column, headerRowIndex) : this.headerPositionUtils.getColumnVisibleChild(column, headerRowIndex);
    let skipColumn = false;
    if (nextRow < 0) {
      nextRow = 0;
      nextFocusColumn = column;
      skipColumn = true;
    }
    if (nextRow >= rowLen) {
      nextRow = -1;
      this.setCurrentHeaderRowWithoutSpan(-1);
    } else if (headerRowIndexWithoutSpan !== void 0) {
      this.currentHeaderRowWithoutSpan = headerRowIndexWithoutSpan;
    }
    if (!skipColumn && !nextFocusColumn) {
      return false;
    }
    return this.focusService.focusHeaderPosition({
      headerPosition: { headerRowIndex: nextRow, column: nextFocusColumn },
      allowUserOverride: true,
      event
    });
  }
  setCurrentHeaderRowWithoutSpan(row) {
    this.currentHeaderRowWithoutSpan = row;
  }
  /*
   * This method navigates grid header horizontally
   * @return {boolean} true to preventDefault on the event that caused this navigation.
   */
  navigateHorizontally(direction, fromTab = false, event) {
    const focusedHeader = this.focusService.getFocusedHeader();
    const isLeft = direction === 2 /* LEFT */;
    const isRtl = this.gos.get("enableRtl");
    let nextHeader;
    let normalisedDirection;
    if (this.currentHeaderRowWithoutSpan !== -1) {
      focusedHeader.headerRowIndex = this.currentHeaderRowWithoutSpan;
    } else {
      this.currentHeaderRowWithoutSpan = focusedHeader.headerRowIndex;
    }
    if (isLeft !== isRtl) {
      normalisedDirection = "Before";
      nextHeader = this.headerPositionUtils.findHeader(focusedHeader, normalisedDirection);
    } else {
      normalisedDirection = "After";
      nextHeader = this.headerPositionUtils.findHeader(focusedHeader, normalisedDirection);
    }
    if (nextHeader || !fromTab) {
      return this.focusService.focusHeaderPosition({
        headerPosition: nextHeader,
        direction: normalisedDirection,
        fromTab,
        allowUserOverride: true,
        event
      });
    } else if (fromTab) {
      const userFunc = this.gos.getCallback("tabToNextHeader");
      if (userFunc) {
        return this.focusService.focusHeaderPositionFromUserFunc({
          userFunc,
          headerPosition: nextHeader,
          direction: normalisedDirection
        });
      }
    }
    return this.focusNextHeaderRow(focusedHeader, normalisedDirection, event);
  }
  focusNextHeaderRow(focusedHeader, direction, event) {
    const currentIndex = focusedHeader.headerRowIndex;
    let nextPosition = null;
    let nextRowIndex;
    if (direction === "Before") {
      if (currentIndex > 0) {
        nextRowIndex = currentIndex - 1;
        this.currentHeaderRowWithoutSpan -= 1;
        nextPosition = this.headerPositionUtils.findColAtEdgeForHeaderRow(nextRowIndex, "end");
      }
    } else {
      nextRowIndex = currentIndex + 1;
      if (this.currentHeaderRowWithoutSpan < this.getHeaderRowCount()) {
        this.currentHeaderRowWithoutSpan += 1;
      } else {
        this.setCurrentHeaderRowWithoutSpan(-1);
      }
      nextPosition = this.headerPositionUtils.findColAtEdgeForHeaderRow(nextRowIndex, "start");
    }
    if (!nextPosition) {
      return false;
    }
    const { column, headerRowIndex } = this.headerPositionUtils.getHeaderIndexToFocus(nextPosition.column, nextPosition == null ? void 0 : nextPosition.headerRowIndex);
    return this.focusService.focusHeaderPosition({
      headerPosition: { column, headerRowIndex },
      direction,
      fromTab: true,
      allowUserOverride: true,
      event
    });
  }
  scrollToColumn(column, direction = "After") {
    if (column.getPinned()) {
      return;
    }
    let columnToScrollTo;
    if (column instanceof ColumnGroup) {
      const columns = column.getDisplayedLeafColumns();
      columnToScrollTo = direction === "Before" ? last(columns) : columns[0];
    } else {
      columnToScrollTo = column;
    }
    this.gridBodyCon.getScrollFeature().ensureColumnVisible(columnToScrollTo);
  }
};
__decorateClass([
  Autowired("focusService")
], HeaderNavigationService.prototype, "focusService", 2);
__decorateClass([
  Autowired("headerPositionUtils")
], HeaderNavigationService.prototype, "headerPositionUtils", 2);
__decorateClass([
  Autowired("ctrlsService")
], HeaderNavigationService.prototype, "ctrlsService", 2);
__decorateClass([
  PostConstruct
], HeaderNavigationService.prototype, "postConstruct", 1);
HeaderNavigationService = __decorateClass([
  Bean("headerNavigationService")
], HeaderNavigationService);

// community-modules/core/src/headerRendering/gridHeaderCtrl.ts
var GridHeaderCtrl = class extends BeanStub {
  setComp(comp, eGui, eFocusableElement) {
    this.comp = comp;
    this.eGui = eGui;
    this.createManagedBean(new ManagedFocusFeature(
      eFocusableElement,
      {
        onTabKeyDown: this.onTabKeyDown.bind(this),
        handleKeyDown: this.handleKeyDown.bind(this),
        onFocusOut: this.onFocusOut.bind(this)
      }
    ));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, this.onPivotModeChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.onPivotModeChanged();
    this.setupHeaderHeight();
    const listener = this.onHeaderContextMenu.bind(this);
    this.addManagedListener(this.eGui, "contextmenu", listener);
    this.mockContextMenuForIPad(listener);
    this.ctrlsService.register("gridHeaderCtrl", this);
  }
  setupHeaderHeight() {
    const listener = this.setHeaderHeight.bind(this);
    listener();
    this.addManagedPropertyListener("headerHeight", listener);
    this.addManagedPropertyListener("pivotHeaderHeight", listener);
    this.addManagedPropertyListener("groupHeaderHeight", listener);
    this.addManagedPropertyListener("pivotGroupHeaderHeight", listener);
    this.addManagedPropertyListener("floatingFiltersHeight", listener);
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_HEADER_HEIGHT_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_GRID_STYLES_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_ADVANCED_FILTER_ENABLED_CHANGED, listener);
  }
  getHeaderHeight() {
    return this.headerHeight;
  }
  setHeaderHeight() {
    const { columnModel } = this;
    let numberOfFloating = 0;
    let headerRowCount = columnModel.getHeaderRowCount();
    let totalHeaderHeight;
    const hasFloatingFilters = this.filterManager.hasFloatingFilters();
    if (hasFloatingFilters) {
      headerRowCount++;
      numberOfFloating = 1;
    }
    const groupHeight = this.columnModel.getColumnGroupHeaderRowHeight();
    const headerHeight = this.columnModel.getColumnHeaderRowHeight();
    const numberOfNonGroups = 1 + numberOfFloating;
    const numberOfGroups = headerRowCount - numberOfNonGroups;
    totalHeaderHeight = numberOfFloating * columnModel.getFloatingFiltersHeight();
    totalHeaderHeight += numberOfGroups * groupHeight;
    totalHeaderHeight += headerHeight;
    if (this.headerHeight === totalHeaderHeight) {
      return;
    }
    this.headerHeight = totalHeaderHeight;
    const px = `${totalHeaderHeight + 1}px`;
    this.comp.setHeightAndMinHeight(px);
    this.eventService.dispatchEvent({
      type: Events.EVENT_HEADER_HEIGHT_CHANGED
    });
  }
  onPivotModeChanged() {
    const pivotMode = this.columnModel.isPivotMode();
    this.comp.addOrRemoveCssClass("ag-pivot-on", pivotMode);
    this.comp.addOrRemoveCssClass("ag-pivot-off", !pivotMode);
  }
  onDisplayedColumnsChanged() {
    const columns = this.columnModel.getAllDisplayedColumns();
    const shouldAllowOverflow = columns.some((col) => col.isSpanHeaderHeight());
    this.comp.addOrRemoveCssClass("ag-header-allow-overflow", shouldAllowOverflow);
  }
  onTabKeyDown(e) {
    const isRtl = this.gos.get("enableRtl");
    const direction = e.shiftKey !== isRtl ? 2 /* LEFT */ : 3 /* RIGHT */;
    if (this.headerNavigationService.navigateHorizontally(direction, true, e) || this.focusService.focusNextGridCoreContainer(e.shiftKey)) {
      e.preventDefault();
    }
  }
  handleKeyDown(e) {
    let direction = null;
    switch (e.key) {
      case KeyCode.LEFT:
        direction = 2 /* LEFT */;
      case KeyCode.RIGHT:
        if (!exists(direction)) {
          direction = 3 /* RIGHT */;
        }
        this.headerNavigationService.navigateHorizontally(direction, false, e);
        break;
      case KeyCode.UP:
        direction = 0 /* UP */;
      case KeyCode.DOWN:
        if (!exists(direction)) {
          direction = 1 /* DOWN */;
        }
        if (this.headerNavigationService.navigateVertically(direction, null, e)) {
          e.preventDefault();
        }
        break;
      default:
        return;
    }
  }
  onFocusOut(e) {
    const { relatedTarget } = e;
    if (!relatedTarget && this.eGui.contains(this.gos.getActiveDomElement())) {
      return;
    }
    if (!this.eGui.contains(relatedTarget)) {
      this.focusService.clearFocusedHeader();
    }
  }
  onHeaderContextMenu(mouseEvent, touch, touchEvent) {
    if (!mouseEvent && !touchEvent || !this.menuService.isHeaderContextMenuEnabled()) {
      return;
    }
    const { target } = mouseEvent != null ? mouseEvent : touch;
    if (target === this.eGui || target === this.ctrlsService.getHeaderRowContainerCtrl().getViewport()) {
      this.menuService.showHeaderContextMenu(void 0, mouseEvent, touchEvent);
    }
  }
  mockContextMenuForIPad(listener) {
    if (!isIOSUserAgent()) {
      return;
    }
    const touchListener = new TouchListener(this.eGui);
    const longTapListener = (event) => {
      listener(void 0, event.touchStart, event.touchEvent);
    };
    this.addManagedListener(touchListener, TouchListener.EVENT_LONG_TAP, longTapListener);
    this.addDestroyFunc(() => touchListener.destroy());
  }
};
__decorateClass([
  Autowired("headerNavigationService")
], GridHeaderCtrl.prototype, "headerNavigationService", 2);
__decorateClass([
  Autowired("focusService")
], GridHeaderCtrl.prototype, "focusService", 2);
__decorateClass([
  Autowired("columnModel")
], GridHeaderCtrl.prototype, "columnModel", 2);
__decorateClass([
  Autowired("ctrlsService")
], GridHeaderCtrl.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("filterManager")
], GridHeaderCtrl.prototype, "filterManager", 2);
__decorateClass([
  Autowired("menuService")
], GridHeaderCtrl.prototype, "menuService", 2);

// community-modules/core/src/headerRendering/gridHeaderComp.ts
var _GridHeaderComp = class _GridHeaderComp extends Component {
  constructor() {
    super(_GridHeaderComp.TEMPLATE);
  }
  postConstruct() {
    const compProxy = {
      addOrRemoveCssClass: (cssClassName, on) => this.addOrRemoveCssClass(cssClassName, on),
      setHeightAndMinHeight: (height) => {
        this.getGui().style.height = height;
        this.getGui().style.minHeight = height;
      }
    };
    const ctrl = this.createManagedBean(new GridHeaderCtrl());
    ctrl.setComp(compProxy, this.getGui(), this.getFocusableElement());
    const addContainer = (container) => {
      this.createManagedBean(container);
      this.appendChild(container);
    };
    addContainer(new HeaderRowContainerComp("left"));
    addContainer(new HeaderRowContainerComp(null));
    addContainer(new HeaderRowContainerComp("right"));
  }
};
_GridHeaderComp.TEMPLATE = /* html */
`<div class="ag-header" role="presentation"/>`;
__decorateClass([
  PostConstruct
], _GridHeaderComp.prototype, "postConstruct", 1);
var GridHeaderComp = _GridHeaderComp;

// community-modules/core/src/headerRendering/common/horizontalResizeService.ts
var HorizontalResizeService = class extends BeanStub {
  addResizeBar(params) {
    const dragSource = {
      dragStartPixels: params.dragStartPixels || 0,
      eElement: params.eResizeBar,
      onDragStart: this.onDragStart.bind(this, params),
      onDragStop: this.onDragStop.bind(this, params),
      onDragging: this.onDragging.bind(this, params),
      includeTouch: true,
      stopPropagationForTouch: true
    };
    this.dragService.addDragSource(dragSource);
    const finishedWithResizeFunc = () => this.dragService.removeDragSource(dragSource);
    return finishedWithResizeFunc;
  }
  onDragStart(params, mouseEvent) {
    this.dragStartX = mouseEvent.clientX;
    this.setResizeIcons();
    const shiftKey = mouseEvent instanceof MouseEvent && mouseEvent.shiftKey === true;
    params.onResizeStart(shiftKey);
  }
  setResizeIcons() {
    const ctrl = this.ctrlsService.get("gridCtrl");
    ctrl.setResizeCursor(true);
    ctrl.disableUserSelect(true);
  }
  onDragStop(params, mouseEvent) {
    params.onResizeEnd(this.resizeAmount);
    this.resetIcons();
  }
  resetIcons() {
    const ctrl = this.ctrlsService.get("gridCtrl");
    ctrl.setResizeCursor(false);
    ctrl.disableUserSelect(false);
  }
  onDragging(params, mouseEvent) {
    this.resizeAmount = mouseEvent.clientX - this.dragStartX;
    params.onResizing(this.resizeAmount);
  }
};
__decorateClass([
  Autowired("dragService")
], HorizontalResizeService.prototype, "dragService", 2);
__decorateClass([
  Autowired("ctrlsService")
], HorizontalResizeService.prototype, "ctrlsService", 2);
HorizontalResizeService = __decorateClass([
  Bean("horizontalResizeService")
], HorizontalResizeService);

// community-modules/core/src/headerRendering/cells/column/standardMenu.ts
var StandardMenuFactory = class extends BeanStub {
  hideActiveMenu() {
    if (this.hidePopup) {
      this.hidePopup();
    }
  }
  showMenuAfterMouseEvent(column, mouseEvent, containerType) {
    this.showPopup(column, (eMenu) => {
      this.popupService.positionPopupUnderMouseEvent({
        column,
        type: containerType,
        mouseEvent,
        ePopup: eMenu
      });
    }, containerType, mouseEvent.target, this.menuService.isLegacyMenuEnabled());
  }
  showMenuAfterButtonClick(column, eventSource, containerType) {
    let multiplier = -1;
    let alignSide = "left";
    const isLegacyMenuEnabled = this.menuService.isLegacyMenuEnabled();
    if (!isLegacyMenuEnabled && this.gos.get("enableRtl")) {
      multiplier = 1;
      alignSide = "right";
    }
    let nudgeX = isLegacyMenuEnabled ? void 0 : 4 * multiplier;
    let nudgeY = isLegacyMenuEnabled ? void 0 : 4;
    this.showPopup(column, (eMenu) => {
      this.popupService.positionPopupByComponent({
        type: containerType,
        eventSource,
        ePopup: eMenu,
        nudgeX,
        nudgeY,
        alignSide,
        keepWithinBounds: true,
        position: "under",
        column
      });
    }, containerType, eventSource, isLegacyMenuEnabled);
  }
  showPopup(column, positionCallback, containerType, eventSource, isLegacyMenuEnabled) {
    const comp = column ? this.createBean(new FilterWrapperComp(column, "COLUMN_MENU")) : void 0;
    this.activeMenu = comp;
    if (!(comp == null ? void 0 : comp.hasFilter()) || !column) {
      throw new Error("AG Grid - unable to show popup filter, filter instantiation failed");
    }
    const eMenu = document.createElement("div");
    setAriaRole(eMenu, "presentation");
    eMenu.classList.add("ag-menu");
    if (!isLegacyMenuEnabled) {
      eMenu.classList.add("ag-filter-menu");
    }
    this.tabListener = this.addManagedListener(eMenu, "keydown", (e) => this.trapFocusWithin(e, eMenu));
    eMenu.appendChild(comp == null ? void 0 : comp.getGui());
    let hidePopup;
    const afterGuiDetached = () => comp == null ? void 0 : comp.afterGuiDetached();
    const anchorToElement = this.menuService.isColumnMenuAnchoringEnabled() ? eventSource != null ? eventSource : this.ctrlsService.getGridBodyCtrl().getGui() : void 0;
    const closedCallback = (e) => {
      column.setMenuVisible(false, "contextMenu");
      const isKeyboardEvent = e instanceof KeyboardEvent;
      if (this.tabListener) {
        this.tabListener = this.tabListener();
      }
      if (isKeyboardEvent && eventSource && isVisible(eventSource)) {
        const focusableEl = this.focusService.findTabbableParent(eventSource);
        if (focusableEl) {
          focusableEl.focus();
        }
      }
      afterGuiDetached();
      this.destroyBean(this.activeMenu);
      this.dispatchVisibleChangedEvent(false, containerType, column);
    };
    const translate = this.localeService.getLocaleTextFunc();
    const ariaLabel = isLegacyMenuEnabled && containerType !== "columnFilter" ? translate("ariaLabelColumnMenu", "Column Menu") : translate("ariaLabelColumnFilter", "Column Filter");
    const addPopupRes = this.popupService.addPopup({
      modal: true,
      eChild: eMenu,
      closeOnEsc: true,
      closedCallback,
      positionCallback: () => positionCallback(eMenu),
      anchorToElement,
      ariaLabel
    });
    if (addPopupRes) {
      this.hidePopup = hidePopup = addPopupRes.hideFunc;
    }
    comp.afterInit().then(() => {
      positionCallback(eMenu);
      comp.afterGuiAttached({ container: containerType, hidePopup });
    });
    column.setMenuVisible(true, "contextMenu");
    this.dispatchVisibleChangedEvent(true, containerType, column);
  }
  trapFocusWithin(e, menu) {
    if (e.key !== KeyCode.TAB || e.defaultPrevented || this.focusService.findNextFocusableElement(menu, false, e.shiftKey)) {
      return;
    }
    e.preventDefault();
    this.focusService.focusInto(menu, e.shiftKey);
  }
  dispatchVisibleChangedEvent(visible, containerType, column) {
    const displayedEvent = {
      type: Events.EVENT_COLUMN_MENU_VISIBLE_CHANGED,
      visible,
      switchingTab: false,
      key: containerType,
      column: column != null ? column : null
    };
    this.eventService.dispatchEvent(displayedEvent);
  }
  isMenuEnabled(column) {
    var _a;
    return column.isFilterAllowed() && ((_a = column.getColDef().menuTabs) != null ? _a : ["filterMenuTab"]).includes("filterMenuTab");
  }
  showMenuAfterContextMenuEvent() {
  }
  destroy() {
    this.destroyBean(this.activeMenu);
    super.destroy();
  }
};
__decorateClass([
  Autowired("filterManager")
], StandardMenuFactory.prototype, "filterManager", 2);
__decorateClass([
  Autowired("popupService")
], StandardMenuFactory.prototype, "popupService", 2);
__decorateClass([
  Autowired("focusService")
], StandardMenuFactory.prototype, "focusService", 2);
__decorateClass([
  Autowired("ctrlsService")
], StandardMenuFactory.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("menuService")
], StandardMenuFactory.prototype, "menuService", 2);
StandardMenuFactory = __decorateClass([
  Bean("filterMenuFactory")
], StandardMenuFactory);

// community-modules/core/src/widgets/tabGuardCtrl.ts
var TabGuardClassNames = /* @__PURE__ */ ((TabGuardClassNames2) => {
  TabGuardClassNames2["TAB_GUARD"] = "ag-tab-guard";
  TabGuardClassNames2["TAB_GUARD_TOP"] = "ag-tab-guard-top";
  TabGuardClassNames2["TAB_GUARD_BOTTOM"] = "ag-tab-guard-bottom";
  return TabGuardClassNames2;
})(TabGuardClassNames || {});
var TabGuardCtrl = class extends BeanStub {
  constructor(params) {
    super();
    this.skipTabGuardFocus = false;
    this.forcingFocusOut = false;
    const {
      comp,
      eTopGuard,
      eBottomGuard,
      focusTrapActive,
      forceFocusOutWhenTabGuardsAreEmpty,
      focusInnerElement,
      onFocusIn,
      onFocusOut,
      shouldStopEventPropagation,
      onTabKeyDown,
      handleKeyDown,
      eFocusableElement
    } = params;
    this.comp = comp;
    this.eTopGuard = eTopGuard;
    this.eBottomGuard = eBottomGuard;
    this.providedFocusInnerElement = focusInnerElement;
    this.eFocusableElement = eFocusableElement;
    this.focusTrapActive = !!focusTrapActive;
    this.forceFocusOutWhenTabGuardsAreEmpty = !!forceFocusOutWhenTabGuardsAreEmpty;
    this.providedFocusIn = onFocusIn;
    this.providedFocusOut = onFocusOut;
    this.providedShouldStopEventPropagation = shouldStopEventPropagation;
    this.providedOnTabKeyDown = onTabKeyDown;
    this.providedHandleKeyDown = handleKeyDown;
  }
  postConstruct() {
    this.createManagedBean(new ManagedFocusFeature(
      this.eFocusableElement,
      {
        shouldStopEventPropagation: () => this.shouldStopEventPropagation(),
        onTabKeyDown: (e) => this.onTabKeyDown(e),
        handleKeyDown: (e) => this.handleKeyDown(e),
        onFocusIn: (e) => this.onFocusIn(e),
        onFocusOut: (e) => this.onFocusOut(e)
      }
    ));
    this.activateTabGuards();
    [this.eTopGuard, this.eBottomGuard].forEach(
      (guard) => this.addManagedListener(guard, "focus", this.onFocus.bind(this))
    );
  }
  handleKeyDown(e) {
    if (this.providedHandleKeyDown) {
      this.providedHandleKeyDown(e);
    }
  }
  tabGuardsAreActive() {
    return !!this.eTopGuard && this.eTopGuard.hasAttribute("tabIndex");
  }
  shouldStopEventPropagation() {
    if (this.providedShouldStopEventPropagation) {
      return this.providedShouldStopEventPropagation();
    }
    return false;
  }
  activateTabGuards() {
    if (this.forcingFocusOut) {
      return;
    }
    const tabIndex = this.gos.get("tabIndex");
    this.comp.setTabIndex(tabIndex.toString());
  }
  deactivateTabGuards() {
    this.comp.setTabIndex();
  }
  onFocus(e) {
    if (this.skipTabGuardFocus) {
      this.skipTabGuardFocus = false;
      return;
    }
    if (this.forceFocusOutWhenTabGuardsAreEmpty) {
      const isEmpty = this.focusService.findFocusableElements(this.eFocusableElement, ".ag-tab-guard").length === 0;
      if (isEmpty) {
        this.findNextElementOutsideAndFocus(e.target === this.eBottomGuard);
        return;
      }
    }
    const fromBottom = e.target === this.eBottomGuard;
    if (this.providedFocusInnerElement) {
      this.providedFocusInnerElement(fromBottom);
    } else {
      this.focusInnerElement(fromBottom);
    }
  }
  findNextElementOutsideAndFocus(up) {
    const eDocument = this.gos.getDocument();
    const focusableEls = this.focusService.findFocusableElements(eDocument.body, null, true);
    const index = focusableEls.indexOf(up ? this.eTopGuard : this.eBottomGuard);
    if (index === -1) {
      return;
    }
    let start;
    let end;
    if (up) {
      start = 0;
      end = index;
    } else {
      start = index + 1;
      end = focusableEls.length;
    }
    const focusableRange = focusableEls.slice(start, end);
    const targetTabIndex = this.gos.get("tabIndex");
    focusableRange.sort((a, b) => {
      const indexA = parseInt(a.getAttribute("tabindex") || "0");
      const indexB = parseInt(b.getAttribute("tabindex") || "0");
      if (indexB === targetTabIndex) {
        return 1;
      }
      if (indexA === targetTabIndex) {
        return -1;
      }
      if (indexA === 0) {
        return 1;
      }
      if (indexB === 0) {
        return -1;
      }
      return indexA - indexB;
    });
    focusableRange[up ? focusableRange.length - 1 : 0].focus();
  }
  onFocusIn(e) {
    if (this.focusTrapActive) {
      return;
    }
    if (this.providedFocusIn) {
      this.providedFocusIn(e);
    }
    this.deactivateTabGuards();
  }
  onFocusOut(e) {
    if (this.focusTrapActive) {
      return;
    }
    if (this.providedFocusOut) {
      this.providedFocusOut(e);
    }
    if (!this.eFocusableElement.contains(e.relatedTarget)) {
      this.activateTabGuards();
    }
  }
  onTabKeyDown(e) {
    if (this.providedOnTabKeyDown) {
      this.providedOnTabKeyDown(e);
      return;
    }
    if (this.focusTrapActive) {
      return;
    }
    if (e.defaultPrevented) {
      return;
    }
    const tabGuardsAreActive = this.tabGuardsAreActive();
    if (tabGuardsAreActive) {
      this.deactivateTabGuards();
    }
    const nextRoot = this.getNextFocusableElement(e.shiftKey);
    if (tabGuardsAreActive) {
      setTimeout(() => this.activateTabGuards(), 0);
    }
    if (!nextRoot) {
      return;
    }
    nextRoot.focus();
    e.preventDefault();
  }
  focusInnerElement(fromBottom = false) {
    const focusable = this.focusService.findFocusableElements(this.eFocusableElement);
    if (this.tabGuardsAreActive()) {
      focusable.splice(0, 1);
      focusable.splice(focusable.length - 1, 1);
    }
    if (!focusable.length) {
      return;
    }
    focusable[fromBottom ? focusable.length - 1 : 0].focus({ preventScroll: true });
  }
  getNextFocusableElement(backwards) {
    return this.focusService.findNextFocusableElement(this.eFocusableElement, false, backwards);
  }
  forceFocusOutOfContainer(up = false) {
    if (this.forcingFocusOut) {
      return;
    }
    const tabGuardToFocus = up ? this.eTopGuard : this.eBottomGuard;
    this.activateTabGuards();
    this.skipTabGuardFocus = true;
    this.forcingFocusOut = true;
    tabGuardToFocus.focus();
    window.setTimeout(() => {
      this.forcingFocusOut = false;
      this.activateTabGuards();
    });
  }
  isTabGuard(element) {
    return element === this.eTopGuard || element === this.eBottomGuard;
  }
};
__decorateClass([
  Autowired("focusService")
], TabGuardCtrl.prototype, "focusService", 2);
__decorateClass([
  PostConstruct
], TabGuardCtrl.prototype, "postConstruct", 1);

// community-modules/core/src/widgets/tabGuardComp.ts
var TabGuardComp = class extends Component {
  initialiseTabGuard(params) {
    this.eTopGuard = this.createTabGuard("top");
    this.eBottomGuard = this.createTabGuard("bottom");
    this.eFocusableElement = this.getFocusableElement();
    const tabGuards = [this.eTopGuard, this.eBottomGuard];
    const compProxy = {
      setTabIndex: (tabIndex) => {
        tabGuards.forEach((tabGuard) => tabIndex != null ? tabGuard.setAttribute("tabindex", tabIndex) : tabGuard.removeAttribute("tabindex"));
      }
    };
    this.addTabGuards(this.eTopGuard, this.eBottomGuard);
    this.tabGuardCtrl = this.createManagedBean(new TabGuardCtrl({
      comp: compProxy,
      focusTrapActive: !!params.focusTrapActive,
      eTopGuard: this.eTopGuard,
      eBottomGuard: this.eBottomGuard,
      eFocusableElement: this.eFocusableElement,
      onFocusIn: params.onFocusIn,
      onFocusOut: params.onFocusOut,
      focusInnerElement: params.focusInnerElement,
      handleKeyDown: params.handleKeyDown,
      onTabKeyDown: params.onTabKeyDown,
      shouldStopEventPropagation: params.shouldStopEventPropagation,
      forceFocusOutWhenTabGuardsAreEmpty: params.forceFocusOutWhenTabGuardsAreEmpty
    }));
  }
  createTabGuard(side) {
    const tabGuard = document.createElement("div");
    const cls = side === "top" ? "ag-tab-guard-top" /* TAB_GUARD_TOP */ : "ag-tab-guard-bottom" /* TAB_GUARD_BOTTOM */;
    tabGuard.classList.add("ag-tab-guard" /* TAB_GUARD */, cls);
    setAriaRole(tabGuard, "presentation");
    return tabGuard;
  }
  addTabGuards(topTabGuard, bottomTabGuard) {
    this.eFocusableElement.insertAdjacentElement("afterbegin", topTabGuard);
    this.eFocusableElement.insertAdjacentElement("beforeend", bottomTabGuard);
  }
  removeAllChildrenExceptTabGuards() {
    const tabGuards = [this.eTopGuard, this.eBottomGuard];
    clearElement(this.getFocusableElement());
    this.addTabGuards(...tabGuards);
  }
  forceFocusOutOfContainer(up = false) {
    this.tabGuardCtrl.forceFocusOutOfContainer(up);
  }
  appendChild(newChild, container) {
    if (!isNodeOrElement(newChild)) {
      newChild = newChild.getGui();
    }
    const { eBottomGuard: bottomTabGuard } = this;
    if (bottomTabGuard) {
      bottomTabGuard.insertAdjacentElement("beforebegin", newChild);
    } else {
      super.appendChild(newChild, container);
    }
  }
};

// community-modules/core/src/layout/tabbedLayout.ts
var _TabbedLayout = class _TabbedLayout extends TabGuardComp {
  constructor(params) {
    super(_TabbedLayout.getTemplate(params.cssClass));
    this.items = [];
    this.tabbedItemScrollMap = /* @__PURE__ */ new Map();
    this.params = params;
  }
  postConstruct() {
    this.setupHeader();
    if (this.params.items) {
      this.params.items.forEach((item) => this.addItem(item));
    }
    this.initialiseTabGuard({
      onTabKeyDown: this.onTabKeyDown.bind(this),
      handleKeyDown: this.handleKeyDown.bind(this),
      focusInnerElement: this.focusInnerElement.bind(this),
      focusTrapActive: true
    });
    this.addDestroyFunc(() => {
      var _a, _b, _c;
      return (_c = (_b = (_a = this.activeItem) == null ? void 0 : _a.tabbedItem) == null ? void 0 : _b.afterDetachedCallback) == null ? void 0 : _c.call(_b);
    });
  }
  static getTemplate(cssClass) {
    return (
      /* html */
      `<div class="ag-tabs ${cssClass}">
            <div ref="eHeader"></div>
            <div ref="eBody" role="presentation" class="ag-tabs-body ${cssClass ? `${cssClass}-body` : ""}"></div>
        </div>`
    );
  }
  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 = this.gos.getDocument().createElement("div");
      addCssClasses(this.eHeader, "header-wrapper");
      setAriaRole(this.eHeader, "presentation");
      this.eHeader.appendChild(this.eTabHeader);
    } else {
      this.eTabHeader = this.eHeader;
    }
    setAriaRole(this.eTabHeader, "tablist");
    addCssClasses(this.eTabHeader, "header");
  }
  setupCloseButton(addCssClasses) {
    const eDocument = this.gos.getDocument();
    const eCloseButton = eDocument.createElement("button");
    addCssClasses(eCloseButton, "close-button");
    const eIcon = createIconNoSpan(
      "close",
      this.gos,
      void 0,
      true
    );
    setAriaLabel(eCloseButton, this.params.closeButtonAriaLabel);
    eCloseButton.appendChild(eIcon);
    this.addManagedListener(eCloseButton, "click", () => {
      var _a, _b;
      return (_b = (_a = this.params).onCloseClicked) == null ? void 0 : _b.call(_a);
    });
    const eCloseButtonWrapper = eDocument.createElement("div");
    addCssClasses(eCloseButtonWrapper, "close-button-wrapper");
    setAriaRole(eCloseButtonWrapper, "presentation");
    eCloseButtonWrapper.appendChild(eCloseButton);
    this.eHeader.appendChild(eCloseButtonWrapper);
    this.eCloseButton = eCloseButton;
  }
  handleKeyDown(e) {
    switch (e.key) {
      case KeyCode.RIGHT:
      case KeyCode.LEFT:
        if (!this.eTabHeader.contains(this.gos.getActiveDomElement())) {
          return;
        }
        const isRightKey = e.key === KeyCode.RIGHT;
        const isRtl = this.gos.get("enableRtl");
        const currentPosition = this.items.indexOf(this.activeItem);
        const nextPosition = isRightKey !== isRtl ? Math.min(currentPosition + 1, this.items.length - 1) : Math.max(currentPosition - 1, 0);
        if (currentPosition === nextPosition) {
          return;
        }
        e.preventDefault();
        const nextItem = this.items[nextPosition];
        this.showItemWrapper(nextItem);
        nextItem.eHeaderButton.focus();
        break;
      case KeyCode.UP:
      case KeyCode.DOWN:
        e.stopPropagation();
        break;
    }
  }
  onTabKeyDown(e) {
    var _a, _b, _c, _d;
    if (e.defaultPrevented) {
      return;
    }
    const { focusService, eHeader, eBody, activeItem, params } = this;
    const { suppressTrapFocus, enableCloseButton } = params;
    const activeElement = this.gos.getActiveDomElement();
    const target = e.target;
    const backwards = e.shiftKey;
    if (eHeader.contains(activeElement)) {
      e.preventDefault();
      if (enableCloseButton && backwards && !((_a = this.eCloseButton) == null ? void 0 : _a.contains(activeElement))) {
        (_b = this.eCloseButton) == null ? void 0 : _b.focus();
      } else if (suppressTrapFocus && backwards) {
        (_c = this.focusService.findFocusableElementBeforeTabGuard(this.gos.getDocument().body, target)) == null ? void 0 : _c.focus();
      } else {
        this.focusBody(e.shiftKey);
      }
      return;
    }
    let nextEl = null;
    if (focusService.isTargetUnderManagedComponent(eBody, target)) {
      if (backwards) {
        nextEl = this.focusService.findFocusableElementBeforeTabGuard(eBody, target);
      }
      if (!nextEl && !suppressTrapFocus) {
        nextEl = activeItem.eHeaderButton;
      }
    }
    if (!nextEl && eBody.contains(activeElement)) {
      nextEl = focusService.findNextFocusableElement(eBody, false, backwards);
      if (!nextEl) {
        e.preventDefault();
        if (suppressTrapFocus && !backwards) {
          this.forceFocusOutOfContainer(backwards);
        } else if (enableCloseButton && !backwards) {
          (_d = this.eCloseButton) == null ? void 0 : _d.focus();
        } else {
          this.focusHeader();
        }
        return;
      }
    }
    if (nextEl) {
      e.preventDefault();
      nextEl.focus();
    }
  }
  focusInnerElement(fromBottom) {
    if (fromBottom) {
      this.focusHeader();
    } else {
      this.focusBody(true);
    }
  }
  focusHeader(preventScroll) {
    this.activeItem.eHeaderButton.focus({ preventScroll });
  }
  focusBody(fromBottom) {
    this.focusService.focusInto(this.eBody, fromBottom);
  }
  setAfterAttachedParams(params) {
    this.afterAttachedParams = params;
  }
  showFirstItem() {
    if (this.items.length > 0) {
      this.showItemWrapper(this.items[0]);
    }
  }
  addItem(item) {
    const eHeaderButton = document.createElement("span");
    setAriaRole(eHeaderButton, "tab");
    eHeaderButton.setAttribute("tabindex", "-1");
    eHeaderButton.appendChild(item.title);
    eHeaderButton.classList.add("ag-tab");
    this.eTabHeader.appendChild(eHeaderButton);
    setAriaLabel(eHeaderButton, item.titleLabel);
    const wrapper = {
      tabbedItem: item,
      eHeaderButton
    };
    this.items.push(wrapper);
    eHeaderButton.addEventListener("click", this.showItemWrapper.bind(this, wrapper));
  }
  showItem(tabbedItem) {
    const itemWrapper = this.items.find((wrapper) => wrapper.tabbedItem === tabbedItem);
    if (itemWrapper) {
      this.showItemWrapper(itemWrapper);
    }
  }
  showItemWrapper(wrapper) {
    var _a, _b, _c, _d, _e, _f;
    const { tabbedItem, eHeaderButton } = wrapper;
    (_b = (_a = this.params).onItemClicked) == null ? void 0 : _b.call(_a, { item: tabbedItem });
    if (this.activeItem === wrapper) {
      (_d = (_c = this.params).onActiveItemClicked) == null ? void 0 : _d.call(_c);
      return;
    }
    if (this.lastScrollListener) {
      this.lastScrollListener = this.lastScrollListener();
    }
    clearElement(this.eBody);
    tabbedItem.bodyPromise.then((body) => {
      this.eBody.appendChild(body);
      const onlyUnmanaged = !this.focusService.isKeyboardMode();
      if (!this.params.suppressFocusBodyOnOpen) {
        this.focusService.focusInto(this.eBody, false, onlyUnmanaged);
      }
      if (tabbedItem.afterAttachedCallback) {
        tabbedItem.afterAttachedCallback(this.afterAttachedParams);
      }
      if (this.params.keepScrollPosition) {
        const scrollableContainer = tabbedItem.getScrollableContainer && tabbedItem.getScrollableContainer() || body;
        this.lastScrollListener = this.addManagedListener(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");
      (_f = (_e = this.activeItem.tabbedItem).afterDetachedCallback) == null ? void 0 : _f.call(_e);
    }
    eHeaderButton.classList.add("ag-tab-selected");
    this.activeItem = wrapper;
  }
};
__decorateClass([
  Autowired("focusService")
], _TabbedLayout.prototype, "focusService", 2);
__decorateClass([
  RefSelector("eHeader")
], _TabbedLayout.prototype, "eHeader", 2);
__decorateClass([
  RefSelector("eBody")
], _TabbedLayout.prototype, "eBody", 2);
__decorateClass([
  PostConstruct
], _TabbedLayout.prototype, "postConstruct", 1);
var TabbedLayout = _TabbedLayout;

// community-modules/core/src/misc/resizeObserverService.ts
var DEBOUNCE_DELAY = 50;
var ResizeObserverService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.polyfillFunctions = [];
  }
  observeResize(element, callback) {
    const win = this.gos.getWindow();
    const useBrowserResizeObserver = () => {
      const resizeObserver = new win.ResizeObserver(callback);
      resizeObserver.observe(element);
      return () => resizeObserver.disconnect();
    };
    const usePolyfill = () => {
      var _a, _b;
      let widthLastTime = (_a = element == null ? void 0 : element.clientWidth) != null ? _a : 0;
      let heightLastTime = (_b = element == null ? void 0 : element.clientHeight) != null ? _b : 0;
      let running = true;
      const periodicallyCheckWidthAndHeight = () => {
        var _a2, _b2;
        if (running) {
          const newWidth = (_a2 = element == null ? void 0 : element.clientWidth) != null ? _a2 : 0;
          const newHeight = (_b2 = element == null ? void 0 : element.clientHeight) != null ? _b2 : 0;
          const changed = newWidth !== widthLastTime || newHeight !== heightLastTime;
          if (changed) {
            widthLastTime = newWidth;
            heightLastTime = newHeight;
            callback();
          }
          this.doNextPolyfillTurn(periodicallyCheckWidthAndHeight);
        }
      };
      periodicallyCheckWidthAndHeight();
      return () => running = false;
    };
    const suppressResize = this.gos.get("suppressBrowserResizeObserver");
    const resizeObserverExists = !!win.ResizeObserver;
    if (resizeObserverExists && !suppressResize) {
      return useBrowserResizeObserver();
    }
    return this.getFrameworkOverrides().wrapIncoming(() => usePolyfill(), "resize-observer");
  }
  doNextPolyfillTurn(func) {
    this.polyfillFunctions.push(func);
    this.schedulePolyfill();
  }
  schedulePolyfill() {
    if (this.polyfillScheduled) {
      return;
    }
    const executeAllFuncs = () => {
      const funcs = this.polyfillFunctions;
      this.polyfillScheduled = false;
      this.polyfillFunctions = [];
      funcs.forEach((f) => f());
    };
    this.polyfillScheduled = true;
    window.setTimeout(executeAllFuncs, DEBOUNCE_DELAY);
  }
};
ResizeObserverService = __decorateClass([
  Bean("resizeObserverService")
], ResizeObserverService);

// community-modules/core/src/misc/animationFrameService.ts
var AnimationFrameService = class extends BeanStub {
  constructor() {
    super(...arguments);
    // p1 and p2 are create tasks are to do with row and cell creation.
    // for them we want to execute according to row order, so we use
    // TaskItem so we know what index the item is for.
    this.createTasksP1 = { list: [], sorted: false };
    // eg drawing back-ground of rows
    this.createTasksP2 = { list: [], sorted: false };
    // eg cell renderers, adding hover functionality
    // destroy tasks are to do with row removal. they are done after row creation as the user will need to see new
    // rows first (as blank is scrolled into view), when we remove the old rows (no longer in view) is not as
    // important.
    this.destroyTasks = [];
    this.ticking = false;
    // we need to know direction of scroll, to build up rows in the direction of
    // the scroll. eg if user scrolls down, we extend the rows by building down.
    this.scrollGoingDown = true;
    this.lastPage = 0;
    this.lastScrollTop = 0;
    this.taskCount = 0;
    this.cancelledTasks = /* @__PURE__ */ new Set();
  }
  setScrollTop(scrollTop) {
    const isPaginationActive = this.gos.get("pagination");
    this.scrollGoingDown = scrollTop >= this.lastScrollTop;
    if (isPaginationActive && scrollTop === 0) {
      const currentPage = this.paginationProxy.getCurrentPage();
      if (currentPage !== this.lastPage) {
        this.lastPage = currentPage;
        this.scrollGoingDown = true;
      }
    }
    this.lastScrollTop = scrollTop;
  }
  init() {
    this.useAnimationFrame = !this.gos.get("suppressAnimationFrame");
  }
  isOn() {
    return this.useAnimationFrame;
  }
  // this method is for our AG Grid sanity only - if animation frames are turned off,
  // then no place in the code should be looking to add any work to be done in animation
  // frames. this stops bugs - where some code is asking for a frame to be executed
  // when it should not.
  verifyAnimationFrameOn(methodName) {
    if (this.useAnimationFrame === false) {
      console.warn(`AG Grid: AnimationFrameService.${methodName} called but animation frames are off`);
    }
  }
  createTask(task, index, list) {
    this.verifyAnimationFrameOn(list);
    const taskItem = { task, index, createOrder: ++this.taskCount };
    this.addTaskToList(this[list], taskItem);
    this.schedule();
  }
  cancelTask(task) {
    this.cancelledTasks.add(task);
  }
  addTaskToList(taskList, task) {
    taskList.list.push(task);
    taskList.sorted = false;
  }
  sortTaskList(taskList) {
    if (taskList.sorted) {
      return;
    }
    const sortDirection = this.scrollGoingDown ? 1 : -1;
    taskList.list.sort((a, b) => a.index !== b.index ? sortDirection * (b.index - a.index) : b.createOrder - a.createOrder);
    taskList.sorted = true;
  }
  addDestroyTask(task) {
    this.verifyAnimationFrameOn("createTasksP3");
    this.destroyTasks.push(task);
    this.schedule();
  }
  executeFrame(millis) {
    this.verifyAnimationFrameOn("executeFrame");
    const p1TaskList = this.createTasksP1;
    const p1Tasks = p1TaskList.list;
    const p2TaskList = this.createTasksP2;
    const p2Tasks = p2TaskList.list;
    const destroyTasks = this.destroyTasks;
    const frameStart = (/* @__PURE__ */ new Date()).getTime();
    let duration = (/* @__PURE__ */ new Date()).getTime() - frameStart;
    const noMaxMillis = millis <= 0;
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    while (noMaxMillis || duration < millis) {
      const gridBodyDidSomething = gridBodyCon.getScrollFeature().scrollGridIfNeeded();
      if (!gridBodyDidSomething) {
        let task;
        if (p1Tasks.length) {
          this.sortTaskList(p1TaskList);
          task = p1Tasks.pop().task;
        } else if (p2Tasks.length) {
          this.sortTaskList(p2TaskList);
          task = p2Tasks.pop().task;
        } else if (destroyTasks.length) {
          task = destroyTasks.pop();
        } else {
          this.cancelledTasks.clear();
          break;
        }
        if (!this.cancelledTasks.has(task)) {
          task();
        }
      }
      duration = (/* @__PURE__ */ new Date()).getTime() - frameStart;
    }
    if (p1Tasks.length || p2Tasks.length || destroyTasks.length) {
      this.requestFrame();
    } else {
      this.stopTicking();
    }
  }
  stopTicking() {
    this.ticking = false;
  }
  flushAllFrames() {
    if (!this.useAnimationFrame) {
      return;
    }
    this.executeFrame(-1);
  }
  schedule() {
    if (!this.useAnimationFrame) {
      return;
    }
    if (!this.ticking) {
      this.ticking = true;
      this.requestFrame();
    }
  }
  requestFrame() {
    const callback = this.executeFrame.bind(this, 60);
    this.requestAnimationFrame(callback);
  }
  requestAnimationFrame(callback) {
    const win = this.gos.getWindow();
    if (win.requestAnimationFrame) {
      win.requestAnimationFrame(callback);
    } else if (win.webkitRequestAnimationFrame) {
      win.webkitRequestAnimationFrame(callback);
    } else {
      win.setTimeout(callback, 0);
    }
  }
  isQueueEmpty() {
    return !this.ticking;
  }
  // a debounce utility used for parts of the app involved with rendering.
  // 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) {
    let pending = false;
    return () => {
      if (!this.isOn()) {
        window.setTimeout(func, 0);
        return;
      }
      if (pending) {
        return;
      }
      pending = true;
      this.addDestroyTask(() => {
        pending = false;
        func();
      });
    };
  }
};
__decorateClass([
  Autowired("ctrlsService")
], AnimationFrameService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("paginationProxy")
], AnimationFrameService.prototype, "paginationProxy", 2);
__decorateClass([
  PostConstruct
], AnimationFrameService.prototype, "init", 1);
AnimationFrameService = __decorateClass([
  Bean("animationFrameService")
], AnimationFrameService);

// community-modules/core/src/interfaces/iClientSideRowModel.ts
var ClientSideRowModelSteps = /* @__PURE__ */ ((ClientSideRowModelSteps2) => {
  ClientSideRowModelSteps2["EVERYTHING"] = "group";
  ClientSideRowModelSteps2["FILTER"] = "filter";
  ClientSideRowModelSteps2["SORT"] = "sort";
  ClientSideRowModelSteps2["MAP"] = "map";
  ClientSideRowModelSteps2["AGGREGATE"] = "aggregate";
  ClientSideRowModelSteps2["FILTER_AGGREGATES"] = "filter_aggregates";
  ClientSideRowModelSteps2["PIVOT"] = "pivot";
  ClientSideRowModelSteps2["NOTHING"] = "nothing";
  return ClientSideRowModelSteps2;
})(ClientSideRowModelSteps || {});

// community-modules/core/src/misc/expansionService.ts
var ExpansionService = class extends BeanStub {
  postConstruct() {
    this.isClientSideRowModel = this.rowModel.getType() === "clientSide";
  }
  expandRows(rowIds) {
    if (!this.isClientSideRowModel) {
      return;
    }
    const rowIdSet = new Set(rowIds);
    this.rowModel.forEachNode((node) => {
      if (node.id && rowIdSet.has(node.id)) {
        node.expanded = true;
      }
    });
    this.onGroupExpandedOrCollapsed();
  }
  getExpandedRows() {
    const expandedRows = [];
    this.rowModel.forEachNode(({ expanded, id }) => {
      if (expanded && id) {
        expandedRows.push(id);
      }
    });
    return expandedRows;
  }
  expandAll(value) {
    if (!this.isClientSideRowModel) {
      return;
    }
    this.rowModel.expandOrCollapseAll(value);
  }
  setRowNodeExpanded(rowNode, expanded, expandParents, forceSync) {
    if (rowNode) {
      if (expandParents && rowNode.parent && rowNode.parent.level !== -1) {
        this.setRowNodeExpanded(rowNode.parent, expanded, expandParents, forceSync);
      }
      rowNode.setExpanded(expanded, void 0, forceSync);
    }
  }
  onGroupExpandedOrCollapsed() {
    if (!this.isClientSideRowModel) {
      return;
    }
    this.rowModel.refreshModel({ step: "map" /* MAP */ });
  }
};
__decorateClass([
  Autowired("rowModel")
], ExpansionService.prototype, "rowModel", 2);
__decorateClass([
  PostConstruct
], ExpansionService.prototype, "postConstruct", 1);
ExpansionService = __decorateClass([
  Bean("expansionService")
], ExpansionService);

// community-modules/core/src/misc/menuService.ts
var MenuService = class extends BeanStub {
  postConstruct() {
    var _a;
    this.activeMenuFactory = (_a = this.enterpriseMenuFactory) != null ? _a : this.filterMenuFactory;
  }
  showColumnMenu(params) {
    this.showColumnMenuCommon(this.activeMenuFactory, params, "columnMenu");
  }
  showFilterMenu(params) {
    const menuFactory = this.enterpriseMenuFactory && this.isLegacyMenuEnabled() ? this.enterpriseMenuFactory : this.filterMenuFactory;
    this.showColumnMenuCommon(menuFactory, params, params.containerType, true);
  }
  showHeaderContextMenu(column, mouseEvent, touchEvent) {
    this.activeMenuFactory.showMenuAfterContextMenuEvent(column, mouseEvent, touchEvent);
  }
  getContextMenuPosition(rowNode, column) {
    const rowCtrl = this.getRowCtrl(rowNode);
    const eGui = this.getCellGui(rowCtrl, column);
    if (!eGui) {
      if (rowCtrl) {
        return { x: 0, y: rowCtrl.getRowYPosition() };
      }
      return { x: 0, y: 0 };
    }
    const rect = eGui.getBoundingClientRect();
    return {
      x: rect.x + rect.width / 2,
      y: rect.y + rect.height / 2
    };
  }
  showContextMenu(params) {
    var _a, _b, _c;
    const { column, rowNode } = params;
    let { anchorToElement, value } = params;
    if (rowNode && column && value == null) {
      value = rowNode.getValueFromValueService(column);
    }
    if (anchorToElement == null) {
      anchorToElement = this.getContextMenuAnchorElement(rowNode, column);
    }
    (_c = this.contextMenuFactory) == null ? void 0 : _c.onContextMenu(
      (_a = params.mouseEvent) != null ? _a : null,
      (_b = params.touchEvent) != null ? _b : null,
      rowNode != null ? rowNode : null,
      column != null ? column : null,
      value,
      anchorToElement
    );
  }
  showColumnChooser(params) {
    var _a;
    (_a = this.columnChooserFactory) == null ? void 0 : _a.showColumnChooser(params);
  }
  hidePopupMenu() {
    var _a;
    (_a = this.contextMenuFactory) == null ? void 0 : _a.hideActiveMenu();
    this.activeMenuFactory.hideActiveMenu();
  }
  hideColumnChooser() {
    var _a;
    (_a = this.columnChooserFactory) == null ? void 0 : _a.hideActiveColumnChooser();
  }
  isColumnMenuInHeaderEnabled(column) {
    const { suppressMenu, suppressHeaderMenuButton } = column.getColDef();
    const isSuppressMenuButton = suppressHeaderMenuButton != null ? suppressHeaderMenuButton : suppressMenu;
    return !isSuppressMenuButton && this.activeMenuFactory.isMenuEnabled(column) && (this.isLegacyMenuEnabled() || !!this.enterpriseMenuFactory);
  }
  isFilterMenuInHeaderEnabled(column) {
    return !column.getColDef().suppressHeaderFilterButton && this.filterManager.isFilterAllowed(column);
  }
  isHeaderContextMenuEnabled(column) {
    return !(column == null ? void 0 : column.getColDef().suppressHeaderContextMenu) && this.getColumnMenuType() === "new";
  }
  isHeaderMenuButtonAlwaysShowEnabled() {
    return this.isSuppressMenuHide();
  }
  isHeaderMenuButtonEnabled() {
    const menuHides = !this.isSuppressMenuHide();
    const onIpadAndMenuHides = isIOSUserAgent() && menuHides;
    return !onIpadAndMenuHides;
  }
  isHeaderFilterButtonEnabled(column) {
    return this.isFilterMenuInHeaderEnabled(column) && !this.isLegacyMenuEnabled() && !this.isFloatingFilterButtonDisplayed(column);
  }
  isFilterMenuItemEnabled(column) {
    return this.filterManager.isFilterAllowed(column) && !this.isLegacyMenuEnabled() && !this.isFilterMenuInHeaderEnabled(column) && !this.isFloatingFilterButtonDisplayed(column);
  }
  isColumnMenuAnchoringEnabled() {
    return !this.isLegacyMenuEnabled();
  }
  areAdditionalColumnMenuItemsEnabled() {
    return this.getColumnMenuType() === "new";
  }
  isLegacyMenuEnabled() {
    return this.getColumnMenuType() === "legacy";
  }
  isFloatingFilterButtonEnabled(column) {
    var _a;
    const colDef = column.getColDef();
    const legacySuppressFilterButton = (_a = colDef.floatingFilterComponentParams) == null ? void 0 : _a.suppressFilterButton;
    if (legacySuppressFilterButton != null) {
      warnOnce(`As of v31.1, 'colDef.floatingFilterComponentParams.suppressFilterButton' is deprecated. Use 'colDef.suppressFloatingFilterButton' instead.`);
    }
    return colDef.suppressFloatingFilterButton == null ? !legacySuppressFilterButton : !colDef.suppressFloatingFilterButton;
  }
  getColumnMenuType() {
    var _a;
    return (_a = this.gos.get("columnMenu")) != null ? _a : "legacy";
  }
  isFloatingFilterButtonDisplayed(column) {
    return !!column.getColDef().floatingFilter && this.isFloatingFilterButtonEnabled(column);
  }
  isSuppressMenuHide() {
    const suppressMenuHide = this.gos.get("suppressMenuHide");
    if (this.isLegacyMenuEnabled()) {
      return suppressMenuHide;
    } else {
      return this.gos.exists("suppressMenuHide") ? suppressMenuHide : true;
    }
  }
  showColumnMenuCommon(menuFactory, params, containerType, filtersOnly) {
    const { column, positionBy } = params;
    if (positionBy === "button") {
      const { buttonElement } = params;
      menuFactory.showMenuAfterButtonClick(column, buttonElement, containerType, filtersOnly);
    } else if (positionBy === "mouse") {
      const { mouseEvent } = params;
      menuFactory.showMenuAfterMouseEvent(column, mouseEvent, containerType, filtersOnly);
    } else if (column) {
      this.ctrlsService.getGridBodyCtrl().getScrollFeature().ensureColumnVisible(column, "auto");
      this.animationFrameService.requestAnimationFrame(() => {
        const headerCellCtrl = this.ctrlsService.getHeaderRowContainerCtrl(column.getPinned()).getHeaderCtrlForColumn(column);
        menuFactory.showMenuAfterButtonClick(column, headerCellCtrl.getAnchorElementForMenu(filtersOnly), containerType, true);
      });
    }
  }
  getRowCtrl(rowNode) {
    const { rowIndex, rowPinned } = rowNode || {};
    if (rowIndex == null) {
      return;
    }
    return this.rowRenderer.getRowByPosition({ rowIndex, rowPinned }) || void 0;
  }
  getCellGui(rowCtrl, column) {
    if (!rowCtrl || !column) {
      return;
    }
    const cellCtrl = rowCtrl.getCellCtrl(column);
    return (cellCtrl == null ? void 0 : cellCtrl.getGui()) || void 0;
  }
  getContextMenuAnchorElement(rowNode, column) {
    const gridBodyEl = this.ctrlsService.getGridBodyCtrl().getGridBodyElement();
    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;
  }
};
__decorateClass([
  Autowired("filterMenuFactory")
], MenuService.prototype, "filterMenuFactory", 2);
__decorateClass([
  Autowired("ctrlsService")
], MenuService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("animationFrameService")
], MenuService.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("filterManager")
], MenuService.prototype, "filterManager", 2);
__decorateClass([
  Autowired("rowRenderer")
], MenuService.prototype, "rowRenderer", 2);
__decorateClass([
  Optional("columnChooserFactory")
], MenuService.prototype, "columnChooserFactory", 2);
__decorateClass([
  Optional("contextMenuFactory")
], MenuService.prototype, "contextMenuFactory", 2);
__decorateClass([
  Optional("enterpriseMenuFactory")
], MenuService.prototype, "enterpriseMenuFactory", 2);
__decorateClass([
  PostConstruct
], MenuService.prototype, "postConstruct", 1);
MenuService = __decorateClass([
  Bean("menuService")
], MenuService);

// community-modules/core/src/rendering/autoWidthCalculator.ts
var AutoWidthCalculator = class extends BeanStub {
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      this.centerRowContainerCtrl = p.center;
    });
  }
  // this is the trick: we create a dummy container and clone all the cells
  // into the dummy, then check the dummy's width. then destroy the dummy
  // as we don't need it any more.
  // drawback: only the cells visible on the screen are considered
  getPreferredWidthForColumn(column, skipHeader) {
    const eHeaderCell = this.getHeaderCellForColumn(column);
    if (!eHeaderCell) {
      return -1;
    }
    const elements = this.rowRenderer.getAllCellsForColumn(column);
    if (!skipHeader) {
      elements.push(eHeaderCell);
    }
    return this.addElementsToContainerAndGetWidth(elements);
  }
  getPreferredWidthForColumnGroup(columnGroup) {
    const eHeaderCell = this.getHeaderCellForColumn(columnGroup);
    if (!eHeaderCell) {
      return -1;
    }
    return this.addElementsToContainerAndGetWidth([eHeaderCell]);
  }
  addElementsToContainerAndGetWidth(elements) {
    const eDummyContainer = document.createElement("form");
    eDummyContainer.style.position = "fixed";
    const eBodyContainer = this.centerRowContainerCtrl.getContainerElement();
    elements.forEach((el) => this.cloneItemIntoDummy(el, eDummyContainer));
    eBodyContainer.appendChild(eDummyContainer);
    const dummyContainerWidth = eDummyContainer.offsetWidth;
    eBodyContainer.removeChild(eDummyContainer);
    const autoSizePadding = this.getAutoSizePadding();
    return dummyContainerWidth + autoSizePadding;
  }
  getAutoSizePadding() {
    return this.gos.get("autoSizePadding");
  }
  getHeaderCellForColumn(column) {
    let element = null;
    this.ctrlsService.getHeaderRowContainerCtrls().forEach(
      (container) => {
        const res = container.getHtmlElementForColumnHeader(column);
        if (res != null) {
          element = res;
        }
      }
    );
    return element;
  }
  cloneItemIntoDummy(eCell, eDummyContainer) {
    const eCellClone = eCell.cloneNode(true);
    eCellClone.style.width = "";
    eCellClone.style.position = "static";
    eCellClone.style.left = "";
    const eCloneParent = document.createElement("div");
    const eCloneParentClassList = eCloneParent.classList;
    const isHeader = ["ag-header-cell", "ag-header-group-cell"].some(
      (cls) => eCellClone.classList.contains(cls)
    );
    if (isHeader) {
      eCloneParentClassList.add("ag-header", "ag-header-row");
      eCloneParent.style.position = "static";
    } else {
      eCloneParentClassList.add("ag-row");
    }
    let pointer = eCell.parentElement;
    while (pointer) {
      const isRow = ["ag-header-row", "ag-row"].some(
        (cls) => pointer.classList.contains(cls)
      );
      if (isRow) {
        for (let i = 0; i < pointer.classList.length; i++) {
          const item = pointer.classList[i];
          if (item != "ag-row-position-absolute") {
            eCloneParentClassList.add(item);
          }
        }
        break;
      }
      pointer = pointer.parentElement;
    }
    eCloneParent.appendChild(eCellClone);
    eDummyContainer.appendChild(eCloneParent);
  }
};
__decorateClass([
  Autowired("rowRenderer")
], AutoWidthCalculator.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("ctrlsService")
], AutoWidthCalculator.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("rowCssClassCalculator")
], AutoWidthCalculator.prototype, "rowCssClassCalculator", 2);
__decorateClass([
  PostConstruct
], AutoWidthCalculator.prototype, "postConstruct", 1);
AutoWidthCalculator = __decorateClass([
  Bean("autoWidthCalculator")
], AutoWidthCalculator);

// community-modules/core/src/rendering/features/stickyRowFeature.ts
var StickyRowFeature = class extends BeanStub {
  constructor(createRowCon, destroyRowCtrls) {
    super();
    this.createRowCon = createRowCon;
    this.destroyRowCtrls = destroyRowCtrls;
    this.stickyTopRowCtrls = [];
    this.stickyBottomRowCtrls = [];
    this.topContainerHeight = 0;
    this.bottomContainerHeight = 0;
  }
  postConstruct() {
    this.isClientSide = this.rowModel.getType() === "clientSide";
    this.ctrlsService.whenReady((params) => {
      this.gridBodyCtrl = params.gridBodyCtrl;
    });
  }
  getStickyTopRowCtrls() {
    return this.stickyTopRowCtrls;
  }
  getStickyBottomRowCtrls() {
    return this.stickyBottomRowCtrls;
  }
  /**
   * 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 ? this.getClientSideLastPixelOfGroup(row) : this.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;
  }
  getServerSideLastPixelOfGroup(row) {
    var _a, _b, _c, _d;
    if (this.isClientSide) {
      throw new Error("This func should only be called in server side row model.");
    }
    if (row.isExpandable() || row.footer) {
      if (row.master) {
        return row.detailNode.rowTop + row.detailNode.rowHeight;
      }
      const noOrContiguousSiblings = !row.sibling || Math.abs(row.sibling.rowIndex - row.rowIndex) === 1;
      if (noOrContiguousSiblings) {
        let storeBounds = (_a = row.childStore) == null ? void 0 : _a.getStoreBounds();
        if (row.footer) {
          storeBounds = (_b = row.sibling.childStore) == null ? void 0 : _b.getStoreBounds();
        }
        return ((_c = storeBounds == null ? void 0 : storeBounds.heightPx) != null ? _c : 0) + ((_d = storeBounds == null ? void 0 : storeBounds.topPx) != null ? _d : 0);
      }
      if (row.footer) {
        return row.rowTop + row.rowHeight;
      }
      return row.sibling.rowTop + row.sibling.rowHeight;
    }
    return Number.MAX_SAFE_INTEGER;
  }
  getClientSideLastPixelOfGroup(row) {
    if (!this.isClientSide) {
      throw new Error("This func should only be called in client side row model.");
    }
    if (row.isExpandable() || row.footer) {
      const grandTotalAtTop = row.footer && row.rowIndex === 0;
      const noOrContiguousSiblings = !row.sibling || Math.abs(row.sibling.rowIndex - row.rowIndex) === 1;
      if (grandTotalAtTop || noOrContiguousSiblings) {
        let lastAncestor = row.footer ? row.sibling : row;
        while (lastAncestor.isExpandable() && lastAncestor.expanded) {
          if (lastAncestor.master) {
            lastAncestor = lastAncestor.detailNode;
          } else if (lastAncestor.childrenAfterSort) {
            if (lastAncestor.childrenAfterSort.length === 0) {
              break;
            }
            lastAncestor = last(lastAncestor.childrenAfterSort);
          }
        }
        return lastAncestor.rowTop + lastAncestor.rowHeight;
      }
      if (row.footer) {
        return row.rowTop + row.rowHeight;
      }
      return row.sibling.rowTop + row.sibling.rowHeight;
    }
    return Number.MAX_SAFE_INTEGER;
  }
  updateStickyRows(container) {
    const isTop = container === "top";
    let newStickyContainerHeight = 0;
    if (!this.canRowsBeSticky()) {
      return this.refreshNodesAndContainerHeight(container, /* @__PURE__ */ new Set(), newStickyContainerHeight);
    }
    const pixelAtContainerBoundary = isTop ? this.rowRenderer.getFirstVisibleVerticalPixel() : this.rowRenderer.getLastVisibleVerticalPixel();
    const newStickyRows = /* @__PURE__ */ new Set();
    const addStickyRow = (stickyRow) => {
      newStickyRows.add(stickyRow);
      if (isTop) {
        const lastChildBottom = this.getLastPixelOfGroup(stickyRow);
        const stickRowBottom = pixelAtContainerBoundary + newStickyContainerHeight + stickyRow.rowHeight;
        if (lastChildBottom < stickRowBottom) {
          stickyRow.stickyRowTop = newStickyContainerHeight + (lastChildBottom - stickRowBottom);
        } else {
          stickyRow.stickyRowTop = newStickyContainerHeight;
        }
      } else {
        const lastChildBottom = this.getFirstPixelOfGroup(stickyRow);
        const stickRowTop = pixelAtContainerBoundary - (newStickyContainerHeight + stickyRow.rowHeight);
        if (lastChildBottom > stickRowTop) {
          stickyRow.stickyRowTop = newStickyContainerHeight - (lastChildBottom - stickRowTop);
        } else {
          stickyRow.stickyRowTop = newStickyContainerHeight;
        }
      }
      newStickyContainerHeight = 0;
      newStickyRows.forEach((rowNode) => {
        const thisRowLastPx = rowNode.stickyRowTop + rowNode.rowHeight;
        if (newStickyContainerHeight < thisRowLastPx) {
          newStickyContainerHeight = thisRowLastPx;
        }
      });
    };
    const suppressFootersSticky = this.areFooterRowsStickySuppressed();
    const suppressGroupsSticky = this.gos.get("suppressGroupRowsSticky");
    const isRowSticky = (row) => {
      if (!row.displayed) {
        return false;
      }
      if (row.footer) {
        if (suppressFootersSticky === true) {
          return false;
        }
        if (suppressFootersSticky === "grand" && row.level === -1) {
          return false;
        }
        ;
        if (suppressFootersSticky === "group" && row.level > -1) {
          return false;
        }
        ;
        const alreadySticking = newStickyRows.has(row);
        return !alreadySticking;
      }
      if (row.isExpandable()) {
        if (suppressGroupsSticky === true) {
          return false;
        }
        ;
        const alreadySticking = newStickyRows.has(row);
        return !alreadySticking && row.expanded;
      }
      return false;
    };
    for (let i = 0; i < 100; i++) {
      let firstPixelAfterStickyRows = pixelAtContainerBoundary + newStickyContainerHeight;
      if (!isTop) {
        firstPixelAfterStickyRows = pixelAtContainerBoundary - newStickyContainerHeight;
      }
      const firstIndex = this.rowModel.getRowIndexAtPixel(firstPixelAfterStickyRows);
      const firstRow = this.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 = !!this.gos.get("groupIncludeFooter") || suppressFootersSticky === "group";
    const suppressGrandRows = !!this.gos.get("groupIncludeTotalFooter") || suppressFootersSticky === "grand";
    if (suppressGroupRows && suppressGrandRows) {
      return true;
    }
    if (suppressGrandRows) {
      return "grand";
    }
    if (suppressGroupRows) {
      return "group";
    }
    return false;
  }
  canRowsBeSticky() {
    const isStickyEnabled = this.gos.isGroupRowsSticky();
    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.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.getRowNode() === stickRowNode)) {
      for (let i = 0; i < this.stickyTopRowCtrls.length; i++) {
        const currentNode = this.stickyTopRowCtrls[i].getRowNode();
        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].getRowNode();
      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].getRowNode();
      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].getRowNode());
    }
    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.getRowNode().rowIndex - a.getRowNode().rowIndex);
    if (!isTop) {
      newCtrlsList.reverse();
    }
    newCtrlsList.forEach((ctrl) => ctrl.setRowTop(ctrl.getRowNode().stickyRowTop));
    if (!hasSomethingChanged) {
      return false;
    }
    if (isTop) {
      this.stickyTopRowCtrls = newCtrlsList;
    } else {
      this.stickyBottomRowCtrls = newCtrlsList;
    }
    return true;
  }
};
__decorateClass([
  Autowired("rowModel")
], StickyRowFeature.prototype, "rowModel", 2);
__decorateClass([
  Autowired("rowRenderer")
], StickyRowFeature.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("ctrlsService")
], StickyRowFeature.prototype, "ctrlsService", 2);
__decorateClass([
  PostConstruct
], StickyRowFeature.prototype, "postConstruct", 1);

// community-modules/core/src/rendering/rowRenderer.ts
var RowRenderer = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.destroyFuncsForColumnListeners = [];
    // map of row ids to row objects. keeps track of which elements
    // are rendered for which rows in the dom.
    this.rowCtrlsByRowIndex = {};
    this.zombieRowCtrls = {};
    this.allRowCtrls = [];
    this.topRowCtrls = [];
    this.bottomRowCtrls = [];
    // we only allow one refresh at a time, otherwise the internal memory structure here
    // will get messed up. this can happen if the user has a cellRenderer, and inside the
    // renderer they call an API method that results in another pass of the refresh,
    // then it will be trying to draw rows in the middle of a refresh.
    this.refreshInProgress = false;
    this.dataFirstRenderedFired = false;
    this.setupRangeSelectionListeners = () => {
      const onRangeSelectionChanged = () => {
        this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onRangeSelectionChanged());
      };
      const onColumnMovedPinnedVisible = () => {
        this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.updateRangeBordersIfRangeCount());
      };
      const addRangeSelectionListeners = () => {
        this.eventService.addEventListener(Events.EVENT_RANGE_SELECTION_CHANGED, onRangeSelectionChanged);
        this.eventService.addEventListener(Events.EVENT_COLUMN_MOVED, onColumnMovedPinnedVisible);
        this.eventService.addEventListener(Events.EVENT_COLUMN_PINNED, onColumnMovedPinnedVisible);
        this.eventService.addEventListener(Events.EVENT_COLUMN_VISIBLE, onColumnMovedPinnedVisible);
      };
      const removeRangeSelectionListeners = () => {
        this.eventService.removeEventListener(Events.EVENT_RANGE_SELECTION_CHANGED, onRangeSelectionChanged);
        this.eventService.removeEventListener(Events.EVENT_COLUMN_MOVED, onColumnMovedPinnedVisible);
        this.eventService.removeEventListener(Events.EVENT_COLUMN_PINNED, onColumnMovedPinnedVisible);
        this.eventService.removeEventListener(Events.EVENT_COLUMN_VISIBLE, onColumnMovedPinnedVisible);
      };
      this.addDestroyFunc(() => removeRangeSelectionListeners());
      this.addManagedPropertyListener("enableRangeSelection", (params) => {
        const isEnabled = params.currentValue;
        if (isEnabled) {
          addRangeSelectionListeners();
        } else {
          removeRangeSelectionListeners();
        }
      });
      const rangeSelectionEnabled = this.gos.get("enableRangeSelection");
      if (rangeSelectionEnabled) {
        addRangeSelectionListeners();
      }
    };
  }
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
      this.initialise();
    });
  }
  initialise() {
    this.addManagedListener(this.eventService, Events.EVENT_PAGINATION_CHANGED, this.onPageLoaded.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_PINNED_ROW_DATA_CHANGED, this.onPinnedRowDataChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_BODY_SCROLL, this.onBodyScroll.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_BODY_HEIGHT_CHANGED, this.redraw.bind(this));
    this.addManagedPropertyListeners(["domLayout", "embedFullWidthRows"], () => this.onDomLayoutChanged());
    this.addManagedPropertyListeners(["suppressMaxRenderedRowRestriction", "rowBuffer"], () => this.redraw());
    this.addManagedPropertyListeners([
      "suppressCellFocus",
      "getBusinessKeyForNode",
      "fullWidthCellRenderer",
      "fullWidthCellRendererParams",
      "rowStyle",
      "getRowStyle",
      "rowClass",
      "getRowClass",
      "rowClassRules",
      "suppressStickyTotalRow",
      "groupRowRenderer",
      "groupRowRendererParams",
      // maybe only needs to refresh FW rows...
      "loadingCellRenderer",
      "loadingCellRendererParams",
      "detailCellRenderer",
      "detailCellRendererParams",
      "enableRangeSelection",
      "enableCellTextSelection"
    ], () => this.redrawRows());
    if (this.gos.isGroupRowsSticky()) {
      const rowModelType = this.rowModel.getType();
      if (rowModelType === "clientSide" || rowModelType === "serverSide") {
        this.stickyRowFeature = this.createManagedBean(new StickyRowFeature(
          this.createRowCon.bind(this),
          this.destroyRowCtrls.bind(this)
        ));
      }
    }
    this.registerCellEventListeners();
    this.initialiseCache();
    this.printLayout = this.gos.isDomLayout("print");
    this.embedFullWidthRows = this.printLayout || this.gos.get("embedFullWidthRows");
    this.redrawAfterModelUpdate();
  }
  initialiseCache() {
    if (this.gos.get("keepDetailRows")) {
      const countProp = this.getKeepDetailRowsCount();
      const count = countProp != null ? countProp : 3;
      this.cachedRowCtrls = new RowCtrlCache(count);
    }
  }
  getKeepDetailRowsCount() {
    return this.gos.get("keepDetailRowsCount");
  }
  getStickyTopRowCtrls() {
    if (!this.stickyRowFeature) {
      return [];
    }
    return this.stickyRowFeature.getStickyTopRowCtrls();
  }
  getStickyBottomRowCtrls() {
    if (!this.stickyRowFeature) {
      return [];
    }
    return this.stickyRowFeature.getStickyBottomRowCtrls();
  }
  updateAllRowCtrls() {
    const liveList = getAllValuesInObject(this.rowCtrlsByRowIndex);
    const zombieList = getAllValuesInObject(this.zombieRowCtrls);
    const cachedList = this.cachedRowCtrls ? this.cachedRowCtrls.getEntries() : [];
    if (zombieList.length > 0 || cachedList.length > 0) {
      this.allRowCtrls = [...liveList, ...zombieList, ...cachedList];
    } else {
      this.allRowCtrls = liveList;
    }
  }
  onCellFocusChanged(event) {
    this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onCellFocused(event));
    this.getFullWidthRowCtrls().forEach((rowCtrl) => rowCtrl.onFullWidthRowFocused(event));
  }
  // in a clean design, each cell would register for each of these events. however when scrolling, all the cells
  // registering and de-registering for events is a performance bottleneck. so we register here once and inform
  // all active cells.
  registerCellEventListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_CELL_FOCUSED, (event) => {
      this.onCellFocusChanged(event);
    });
    this.addManagedListener(this.eventService, Events.EVENT_CELL_FOCUS_CLEARED, () => {
      this.onCellFocusChanged();
    });
    this.addManagedListener(this.eventService, Events.EVENT_FLASH_CELLS, (event) => {
      this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onFlashCells(event));
    });
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_HOVER_CHANGED, () => {
      this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onColumnHover());
    });
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, () => {
      this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onDisplayedColumnsChanged());
    });
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, () => {
      if (this.printLayout) {
        this.getAllCellCtrls().forEach((cellCtrl) => cellCtrl.onLeftChanged());
      }
    });
    this.setupRangeSelectionListeners();
    this.refreshListenersToColumnsForCellComps();
    this.addManagedListener(this.eventService, Events.EVENT_GRID_COLUMNS_CHANGED, this.refreshListenersToColumnsForCellComps.bind(this));
    this.addDestroyFunc(this.removeGridColumnListeners.bind(this));
  }
  // executes all functions in destroyFuncsForColumnListeners and then clears the list
  removeGridColumnListeners() {
    this.destroyFuncsForColumnListeners.forEach((func) => func());
    this.destroyFuncsForColumnListeners.length = 0;
  }
  // this function adds listeners onto all the grid columns, which are the column that we could have cellComps for.
  // when the grid columns change, we add listeners again. in an ideal design, each CellComp would just register to
  // the column it belongs to on creation, however this was a bottleneck with the number of cells, so do it here
  // once instead.
  refreshListenersToColumnsForCellComps() {
    this.removeGridColumnListeners();
    const cols = this.columnModel.getAllGridColumns();
    cols.forEach((col) => {
      const forEachCellWithThisCol = (callback) => {
        this.getAllCellCtrls().forEach((cellCtrl) => {
          if (cellCtrl.getColumn() === col) {
            callback(cellCtrl);
          }
        });
      };
      const leftChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onLeftChanged());
      };
      const widthChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onWidthChanged());
      };
      const firstRightPinnedChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onFirstRightPinnedChanged());
      };
      const lastLeftPinnedChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onLastLeftPinnedChanged());
      };
      const colDefChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onColDefChanged());
      };
      col.addEventListener("leftChanged", leftChangedListener);
      col.addEventListener("widthChanged", widthChangedListener);
      col.addEventListener("firstRightPinnedChanged", firstRightPinnedChangedListener);
      col.addEventListener("lastLeftPinnedChanged", lastLeftPinnedChangedListener);
      col.addEventListener("colDefChanged", colDefChangedListener);
      this.destroyFuncsForColumnListeners.push(() => {
        col.removeEventListener("leftChanged", leftChangedListener);
        col.removeEventListener("widthChanged", widthChangedListener);
        col.removeEventListener("firstRightPinnedChanged", firstRightPinnedChangedListener);
        col.removeEventListener("lastLeftPinnedChanged", lastLeftPinnedChangedListener);
        col.removeEventListener("colDefChanged", colDefChangedListener);
      });
    });
  }
  onDomLayoutChanged() {
    const printLayout = this.gos.isDomLayout("print");
    const embedFullWidthRows = printLayout || this.gos.get("embedFullWidthRows");
    const destroyRows = embedFullWidthRows !== this.embedFullWidthRows || this.printLayout !== printLayout;
    this.printLayout = printLayout;
    this.embedFullWidthRows = embedFullWidthRows;
    if (destroyRows) {
      this.redrawAfterModelUpdate({ domLayoutChanged: true });
    }
  }
  // for row models that have datasources, when we update the datasource, we need to force the rowRenderer
  // to redraw all rows. otherwise the old rows from the old datasource will stay displayed.
  datasourceChanged() {
    this.firstRenderedRow = 0;
    this.lastRenderedRow = -1;
    const rowIndexesToRemove = Object.keys(this.rowCtrlsByRowIndex);
    this.removeRowCtrls(rowIndexesToRemove);
  }
  onPageLoaded(event) {
    const params = {
      recycleRows: event.keepRenderedRows,
      animate: event.animate,
      newData: event.newData,
      newPage: event.newPage,
      // because this is a model updated event (not pinned rows), we
      // can skip updating the pinned rows. this is needed so that if user
      // is doing transaction updates, the pinned rows are not getting constantly
      // trashed - or editing cells in pinned rows are not refreshed and put into read mode
      onlyBody: true
    };
    this.redrawAfterModelUpdate(params);
  }
  getAllCellsForColumn(column) {
    const res = [];
    this.getAllRowCtrls().forEach((rowCtrl) => {
      const eCell = rowCtrl.getCellElement(column);
      if (eCell) {
        res.push(eCell);
      }
    });
    return res;
  }
  refreshFloatingRowComps() {
    this.refreshFloatingRows(
      this.topRowCtrls,
      this.pinnedRowModel.getPinnedTopRowData()
    );
    this.refreshFloatingRows(
      this.bottomRowCtrls,
      this.pinnedRowModel.getPinnedBottomRowData()
    );
  }
  getTopRowCtrls() {
    return this.topRowCtrls;
  }
  getCentreRowCtrls() {
    return this.allRowCtrls;
  }
  getBottomRowCtrls() {
    return this.bottomRowCtrls;
  }
  refreshFloatingRows(rowComps, rowNodes) {
    rowComps.forEach((row) => {
      row.destroyFirstPass();
      row.destroySecondPass();
    });
    rowComps.length = 0;
    if (!rowNodes) {
      return;
    }
    rowNodes.forEach((rowNode) => {
      const rowCtrl = new RowCtrl(
        rowNode,
        this.beans,
        false,
        false,
        this.printLayout
      );
      rowComps.push(rowCtrl);
    });
  }
  onPinnedRowDataChanged() {
    const params = {
      recycleRows: true
    };
    this.redrawAfterModelUpdate(params);
  }
  redrawRow(rowNode, suppressEvent = false) {
    var _a;
    if (rowNode.sticky) {
      this.stickyRowFeature.refreshStickyNode(rowNode);
    } else if ((_a = this.cachedRowCtrls) == null ? void 0 : _a.has(rowNode)) {
      this.cachedRowCtrls.removeRow(rowNode);
      return;
    } else {
      const destroyAndRecreateCtrl = (dataStruct) => {
        const ctrl = dataStruct[rowNode.rowIndex];
        if (!ctrl) {
          return;
        }
        if (ctrl.getRowNode() !== rowNode) {
          return;
        }
        ctrl.destroyFirstPass();
        ctrl.destroySecondPass();
        dataStruct[rowNode.rowIndex] = this.createRowCon(rowNode, false, false);
      };
      switch (rowNode.rowPinned) {
        case "top":
          destroyAndRecreateCtrl(this.topRowCtrls);
          break;
        case "bottom":
          destroyAndRecreateCtrl(this.bottomRowCtrls);
          break;
        default:
          destroyAndRecreateCtrl(this.rowCtrlsByRowIndex);
          this.updateAllRowCtrls();
      }
    }
    if (!suppressEvent) {
      this.dispatchDisplayedRowsChanged(false);
    }
  }
  redrawRows(rowNodes) {
    const partialRefresh = rowNodes != null;
    if (partialRefresh) {
      rowNodes == null ? void 0 : rowNodes.forEach((node) => this.redrawRow(node, true));
      this.dispatchDisplayedRowsChanged(false);
      return;
    }
    this.redrawAfterModelUpdate();
  }
  getCellToRestoreFocusToAfterRefresh(params) {
    const focusedCell = (params == null ? void 0 : params.suppressKeepFocus) ? null : this.focusService.getFocusCellToUseAfterRefresh();
    if (focusedCell == null) {
      return null;
    }
    const activeElement = this.gos.getActiveDomElement();
    const cellDomData = this.gos.getDomData(activeElement, CellCtrl.DOM_DATA_KEY_CELL_CTRL);
    const rowDomData = this.gos.getDomData(activeElement, RowCtrl.DOM_DATA_KEY_ROW_CTRL);
    const gridElementFocused = cellDomData || rowDomData;
    return gridElementFocused ? focusedCell : null;
  }
  // gets called from:
  // +) initialisation (in registerGridComp) params = null
  // +) onDomLayoutChanged, params = null
  // +) onPageLoaded, recycleRows, animate, newData, newPage from event, onlyBody=true
  // +) onPinnedRowDataChanged, recycleRows = true
  // +) redrawRows (from Grid API), recycleRows = true/false
  redrawAfterModelUpdate(params = {}) {
    this.getLockOnRefresh();
    const focusedCell = this.getCellToRestoreFocusToAfterRefresh(params);
    this.updateContainerHeights();
    this.scrollToTopIfNewData(params);
    const recycleRows = !params.domLayoutChanged && !!params.recycleRows;
    const animate = params.animate && this.gos.isAnimateRows();
    const rowsToRecycle = recycleRows ? this.getRowsToRecycle() : null;
    if (!recycleRows) {
      this.removeAllRowComps();
    }
    this.workOutFirstAndLastRowsToRender();
    if (this.stickyRowFeature) {
      this.stickyRowFeature.checkStickyRows();
    }
    this.recycleRows(rowsToRecycle, animate);
    this.gridBodyCtrl.updateRowCount();
    if (!params.onlyBody) {
      this.refreshFloatingRowComps();
    }
    this.dispatchDisplayedRowsChanged();
    if (focusedCell != null) {
      this.restoreFocusedCell(focusedCell);
    }
    this.releaseLockOnRefresh();
  }
  scrollToTopIfNewData(params) {
    const scrollToTop = params.newData || params.newPage;
    const suppressScrollToTop = this.gos.get("suppressScrollOnNewData");
    if (scrollToTop && !suppressScrollToTop) {
      this.gridBodyCtrl.getScrollFeature().scrollToTop();
    }
  }
  updateContainerHeights() {
    if (this.printLayout) {
      this.rowContainerHeightService.setModelHeight(null);
      return;
    }
    let containerHeight = this.paginationProxy.getCurrentPageHeight();
    if (containerHeight === 0) {
      containerHeight = 1;
    }
    this.rowContainerHeightService.setModelHeight(containerHeight);
  }
  getLockOnRefresh() {
    if (this.refreshInProgress) {
      throw new Error(
        "AG Grid: cannot get grid to draw rows when it is in the middle of drawing rows. Your code probably called a grid API method while the grid was in the render stage. To overcome this, put the API call into a timeout, e.g. instead of api.redrawRows(), call setTimeout(function() { api.redrawRows(); }, 0). To see what part of your code that caused the refresh check this stacktrace."
      );
    }
    this.refreshInProgress = true;
  }
  releaseLockOnRefresh() {
    this.refreshInProgress = false;
  }
  isRefreshInProgress() {
    return this.refreshInProgress;
  }
  // sets the focus to the provided cell, if the cell is provided. this way, the user can call refresh without
  // worry about the focus been lost. this is important when the user is using keyboard navigation to do edits
  // and the cellEditor is calling 'refresh' to get other cells to update (as other cells might depend on the
  // edited cell).
  restoreFocusedCell(cellPosition) {
    if (cellPosition) {
      this.focusService.setRestoreFocusedCell(cellPosition);
      this.onCellFocusChanged(this.beans.gos.addGridCommonParams({
        rowIndex: cellPosition.rowIndex,
        column: cellPosition.column,
        rowPinned: cellPosition.rowPinned,
        forceBrowserFocus: true,
        preventScrollOnBrowserFocus: true,
        type: "mock"
      }));
    }
  }
  stopEditing(cancel = false) {
    this.getAllRowCtrls().forEach((rowCtrl) => {
      rowCtrl.stopEditing(cancel);
    });
  }
  getAllCellCtrls() {
    const res = [];
    const rowCtrls = this.getAllRowCtrls();
    const rowCtrlsLength = rowCtrls.length;
    for (let i = 0; i < rowCtrlsLength; i++) {
      const cellCtrls = rowCtrls[i].getAllCellCtrls();
      const cellCtrlsLength = cellCtrls.length;
      for (let j = 0; j < cellCtrlsLength; j++) {
        res.push(cellCtrls[j]);
      }
    }
    return res;
  }
  getAllRowCtrls() {
    const stickyTopRowCtrls = this.stickyRowFeature && this.stickyRowFeature.getStickyTopRowCtrls() || [];
    const stickyBottomRowCtrls = this.stickyRowFeature && this.stickyRowFeature.getStickyBottomRowCtrls() || [];
    const res = [...this.topRowCtrls, ...this.bottomRowCtrls, ...stickyTopRowCtrls, ...stickyBottomRowCtrls];
    for (const key in this.rowCtrlsByRowIndex) {
      res.push(this.rowCtrlsByRowIndex[key]);
    }
    return res;
  }
  addRenderedRowListener(eventName, rowIndex, callback) {
    const rowComp = this.rowCtrlsByRowIndex[rowIndex];
    if (rowComp) {
      rowComp.addEventListener(eventName, callback);
    }
  }
  flashCells(params = {}) {
    this.getCellCtrls(params.rowNodes, params.columns).forEach((cellCtrl) => cellCtrl.flashCell(params));
  }
  refreshCells(params = {}) {
    const refreshCellParams = {
      forceRefresh: params.force,
      newData: false,
      suppressFlash: params.suppressFlash
    };
    this.getCellCtrls(params.rowNodes, params.columns).forEach((cellCtrl) => cellCtrl.refreshOrDestroyCell(refreshCellParams));
    if (params.rowNodes) {
      this.getRowCtrls(params.rowNodes).forEach((rowCtrl) => {
        if (!rowCtrl.isFullWidth()) {
          return;
        }
        const refreshed = rowCtrl.refreshFullWidth();
        if (!refreshed) {
          this.redrawRow(rowCtrl.getRowNode(), true);
        }
      });
      this.dispatchDisplayedRowsChanged(false);
    }
  }
  getCellRendererInstances(params) {
    var _a;
    const cellRenderers = this.getCellCtrls(params.rowNodes, params.columns).map((cellCtrl) => cellCtrl.getCellRenderer()).filter((renderer) => renderer != null);
    if ((_a = params.columns) == null ? void 0 : _a.length) {
      return cellRenderers;
    }
    const fullWidthRenderers = [];
    const rowIdMap = this.mapRowNodes(params.rowNodes);
    this.getAllRowCtrls().forEach((rowCtrl) => {
      if (rowIdMap && !this.isRowInMap(rowCtrl.getRowNode(), rowIdMap)) {
        return;
      }
      if (!rowCtrl.isFullWidth()) {
        return;
      }
      const renderers = rowCtrl.getFullWidthCellRenderers();
      for (let i = 0; i < renderers.length; i++) {
        const renderer = renderers[i];
        if (renderer != null) {
          fullWidthRenderers.push(renderer);
        }
      }
    });
    return [...fullWidthRenderers, ...cellRenderers];
  }
  getCellEditorInstances(params) {
    const res = [];
    this.getCellCtrls(params.rowNodes, params.columns).forEach((cellCtrl) => {
      const cellEditor = cellCtrl.getCellEditor();
      if (cellEditor) {
        res.push(cellEditor);
      }
    });
    return res;
  }
  getEditingCells() {
    const res = [];
    this.getAllCellCtrls().forEach((cellCtrl) => {
      if (cellCtrl.isEditing()) {
        const cellPosition = cellCtrl.getCellPosition();
        res.push(cellPosition);
      }
    });
    return res;
  }
  mapRowNodes(rowNodes) {
    if (!rowNodes) {
      return;
    }
    const res = {
      top: {},
      bottom: {},
      normal: {}
    };
    rowNodes.forEach((rowNode) => {
      const id = rowNode.id;
      switch (rowNode.rowPinned) {
        case "top":
          res.top[id] = rowNode;
          break;
        case "bottom":
          res.bottom[id] = rowNode;
          break;
        default:
          res.normal[id] = rowNode;
          break;
      }
    });
    return res;
  }
  isRowInMap(rowNode, rowIdsMap) {
    const id = rowNode.id;
    const floating = rowNode.rowPinned;
    switch (floating) {
      case "top":
        return rowIdsMap.top[id] != null;
      case "bottom":
        return rowIdsMap.bottom[id] != null;
      default:
        return rowIdsMap.normal[id] != null;
    }
  }
  /**
   * @param rowNodes if provided, returns the RowCtrls for the provided rowNodes. otherwise returns all RowCtrls.
   */
  getRowCtrls(rowNodes) {
    const rowIdsMap = this.mapRowNodes(rowNodes);
    const allRowCtrls = this.getAllRowCtrls();
    if (!rowNodes || !rowIdsMap) {
      return allRowCtrls;
    }
    return allRowCtrls.filter((rowCtrl) => {
      const rowNode = rowCtrl.getRowNode();
      return this.isRowInMap(rowNode, rowIdsMap);
    });
  }
  // returns CellCtrl's that match the provided rowNodes and columns. eg if one row node
  // and two columns provided, that identifies 4 cells, so 4 CellCtrl's returned.
  getCellCtrls(rowNodes, columns) {
    let colIdsMap;
    if (exists(columns)) {
      colIdsMap = {};
      columns.forEach((colKey) => {
        const column = this.columnModel.getGridColumn(colKey);
        if (exists(column)) {
          colIdsMap[column.getId()] = true;
        }
      });
    }
    const res = [];
    this.getRowCtrls(rowNodes).forEach((rowCtrl) => {
      rowCtrl.getAllCellCtrls().forEach((cellCtrl) => {
        const colId = cellCtrl.getColumn().getId();
        const excludeColFromRefresh = colIdsMap && !colIdsMap[colId];
        if (excludeColFromRefresh) {
          return;
        }
        res.push(cellCtrl);
      });
    });
    return res;
  }
  destroy() {
    this.removeAllRowComps();
    super.destroy();
  }
  removeAllRowComps() {
    const rowIndexesToRemove = Object.keys(this.rowCtrlsByRowIndex);
    this.removeRowCtrls(rowIndexesToRemove);
    if (this.stickyRowFeature) {
      this.stickyRowFeature.destroyStickyCtrls();
    }
  }
  getRowsToRecycle() {
    const stubNodeIndexes = [];
    iterateObject(this.rowCtrlsByRowIndex, (index, rowCtrl) => {
      const stubNode = rowCtrl.getRowNode().id == null;
      if (stubNode) {
        stubNodeIndexes.push(index);
      }
    });
    this.removeRowCtrls(stubNodeIndexes);
    const ctrlsByIdMap = {};
    iterateObject(this.rowCtrlsByRowIndex, (index, rowCtrl) => {
      const rowNode = rowCtrl.getRowNode();
      ctrlsByIdMap[rowNode.id] = rowCtrl;
    });
    this.rowCtrlsByRowIndex = {};
    return ctrlsByIdMap;
  }
  // takes array of row indexes
  removeRowCtrls(rowsToRemove, suppressAnimation = false) {
    rowsToRemove.forEach((indexToRemove) => {
      const rowCtrl = this.rowCtrlsByRowIndex[indexToRemove];
      if (rowCtrl) {
        rowCtrl.destroyFirstPass(suppressAnimation);
        rowCtrl.destroySecondPass();
      }
      delete this.rowCtrlsByRowIndex[indexToRemove];
    });
  }
  onBodyScroll(e) {
    if (e.direction !== "vertical") {
      return;
    }
    this.redraw({ afterScroll: true });
  }
  // gets called when rows don't change, but viewport does, so after:
  // 1) height of grid body changes, ie number of displayed rows has changed
  // 2) grid scrolled to new position
  // 3) ensure index visible (which is a scroll)
  redraw(params = {}) {
    const { afterScroll } = params;
    let cellFocused;
    if (this.stickyRowFeature && browserSupportsPreventScroll()) {
      cellFocused = this.getCellToRestoreFocusToAfterRefresh() || void 0;
    }
    const oldFirstRow = this.firstRenderedRow;
    const oldLastRow = this.lastRenderedRow;
    this.workOutFirstAndLastRowsToRender();
    let hasStickyRowChanges = false;
    if (this.stickyRowFeature) {
      hasStickyRowChanges = this.stickyRowFeature.checkStickyRows();
    }
    const rangeChanged = this.firstRenderedRow !== oldFirstRow || this.lastRenderedRow !== oldLastRow;
    if (afterScroll && !hasStickyRowChanges && !rangeChanged) {
      return;
    }
    this.getLockOnRefresh();
    this.recycleRows(null, false, afterScroll);
    this.releaseLockOnRefresh();
    this.dispatchDisplayedRowsChanged(afterScroll && !hasStickyRowChanges);
    if (cellFocused != null) {
      const newFocusedCell = this.getCellToRestoreFocusToAfterRefresh();
      if (cellFocused != null && newFocusedCell == null) {
        this.animationFrameService.flushAllFrames();
        this.restoreFocusedCell(cellFocused);
      }
    }
  }
  removeRowCompsNotToDraw(indexesToDraw, suppressAnimation) {
    const indexesToDrawMap = {};
    indexesToDraw.forEach((index) => indexesToDrawMap[index] = true);
    const existingIndexes = Object.keys(this.rowCtrlsByRowIndex);
    const indexesNotToDraw = existingIndexes.filter((index) => !indexesToDrawMap[index]);
    this.removeRowCtrls(indexesNotToDraw, suppressAnimation);
  }
  calculateIndexesToDraw(rowsToRecycle) {
    let indexesToDraw = createArrayOfNumbers(this.firstRenderedRow, this.lastRenderedRow);
    const checkRowToDraw = (indexStr, rowComp) => {
      const index = rowComp.getRowNode().rowIndex;
      if (index == null) {
        return;
      }
      if (index < this.firstRenderedRow || index > this.lastRenderedRow) {
        if (this.doNotUnVirtualiseRow(rowComp)) {
          indexesToDraw.push(index);
        }
      }
    };
    iterateObject(this.rowCtrlsByRowIndex, checkRowToDraw);
    iterateObject(rowsToRecycle, checkRowToDraw);
    indexesToDraw.sort((a, b) => a - b);
    const ret = [];
    for (let i = 0; i < indexesToDraw.length; i++) {
      const currRow = indexesToDraw[i];
      const rowNode = this.paginationProxy.getRow(currRow);
      if (rowNode && !rowNode.sticky) {
        ret.push(currRow);
      }
    }
    return ret;
  }
  recycleRows(rowsToRecycle, animate = false, afterScroll = false) {
    const indexesToDraw = this.calculateIndexesToDraw(rowsToRecycle);
    if (this.printLayout || afterScroll) {
      animate = false;
    }
    this.removeRowCompsNotToDraw(indexesToDraw, !animate);
    const rowCtrls = [];
    indexesToDraw.forEach((rowIndex) => {
      const rowCtrl = this.createOrUpdateRowCtrl(rowIndex, rowsToRecycle, animate, afterScroll);
      if (exists(rowCtrl)) {
        rowCtrls.push(rowCtrl);
      }
    });
    if (rowsToRecycle) {
      const useAnimationFrame = afterScroll && !this.gos.get("suppressAnimationFrame") && !this.printLayout;
      if (useAnimationFrame) {
        this.beans.animationFrameService.addDestroyTask(() => {
          this.destroyRowCtrls(rowsToRecycle, animate);
          this.updateAllRowCtrls();
          this.dispatchDisplayedRowsChanged();
        });
      } else {
        this.destroyRowCtrls(rowsToRecycle, animate);
      }
    }
    this.updateAllRowCtrls();
  }
  dispatchDisplayedRowsChanged(afterScroll = false) {
    const event = { type: Events.EVENT_DISPLAYED_ROWS_CHANGED, afterScroll };
    this.eventService.dispatchEvent(event);
  }
  onDisplayedColumnsChanged() {
    const pinningLeft = this.columnModel.isPinningLeft();
    const pinningRight = this.columnModel.isPinningRight();
    const atLeastOneChanged = this.pinningLeft !== pinningLeft || pinningRight !== this.pinningRight;
    if (atLeastOneChanged) {
      this.pinningLeft = pinningLeft;
      this.pinningRight = pinningRight;
      if (this.embedFullWidthRows) {
        this.redrawFullWidthEmbeddedRows();
      }
    }
  }
  // when embedding, what gets showed in each section depends on what is pinned. eg if embedding group expand / collapse,
  // then it should go into the pinned left area if pinning left, or the center area if not pinning.
  redrawFullWidthEmbeddedRows() {
    const rowsToRemove = [];
    this.getFullWidthRowCtrls().forEach((fullWidthCtrl) => {
      const rowIndex = fullWidthCtrl.getRowNode().rowIndex;
      rowsToRemove.push(rowIndex.toString());
    });
    this.refreshFloatingRowComps();
    this.removeRowCtrls(rowsToRemove);
    this.redraw({ afterScroll: true });
  }
  getFullWidthRowCtrls(rowNodes) {
    const rowNodesMap = this.mapRowNodes(rowNodes);
    return this.getAllRowCtrls().filter((rowCtrl) => {
      if (!rowCtrl.isFullWidth()) {
        return false;
      }
      const rowNode = rowCtrl.getRowNode();
      if (rowNodesMap != null && !this.isRowInMap(rowNode, rowNodesMap)) {
        return false;
      }
      return true;
    });
  }
  createOrUpdateRowCtrl(rowIndex, rowsToRecycle, animate, afterScroll) {
    let rowNode;
    let rowCtrl = this.rowCtrlsByRowIndex[rowIndex];
    if (!rowCtrl) {
      rowNode = this.paginationProxy.getRow(rowIndex);
      if (exists(rowNode) && exists(rowsToRecycle) && rowsToRecycle[rowNode.id] && rowNode.alreadyRendered) {
        rowCtrl = rowsToRecycle[rowNode.id];
        rowsToRecycle[rowNode.id] = null;
      }
    }
    const creatingNewRowCtrl = !rowCtrl;
    if (creatingNewRowCtrl) {
      if (!rowNode) {
        rowNode = this.paginationProxy.getRow(rowIndex);
      }
      if (exists(rowNode)) {
        rowCtrl = this.createRowCon(rowNode, animate, afterScroll);
      } else {
        return;
      }
    }
    if (rowNode) {
      rowNode.alreadyRendered = true;
    }
    this.rowCtrlsByRowIndex[rowIndex] = rowCtrl;
    return rowCtrl;
  }
  destroyRowCtrls(rowCtrlsMap, animate) {
    const executeInAWhileFuncs = [];
    iterateObject(rowCtrlsMap, (nodeId, rowCtrl) => {
      if (!rowCtrl) {
        return;
      }
      if (this.cachedRowCtrls && rowCtrl.isCacheable()) {
        this.cachedRowCtrls.addRow(rowCtrl);
        return;
      }
      rowCtrl.destroyFirstPass(!animate);
      if (animate) {
        this.zombieRowCtrls[rowCtrl.getInstanceId()] = rowCtrl;
        executeInAWhileFuncs.push(() => {
          rowCtrl.destroySecondPass();
          delete this.zombieRowCtrls[rowCtrl.getInstanceId()];
        });
      } else {
        rowCtrl.destroySecondPass();
      }
    });
    if (animate) {
      executeInAWhileFuncs.push(() => {
        this.updateAllRowCtrls();
        this.dispatchDisplayedRowsChanged();
      });
      executeInAWhile(executeInAWhileFuncs);
    }
  }
  getRowBuffer() {
    return this.gos.get("rowBuffer");
  }
  getRowBufferInPixels() {
    const rowsToBuffer = this.getRowBuffer();
    const defaultRowHeight = this.gos.getRowHeightAsNumber();
    return rowsToBuffer * defaultRowHeight;
  }
  workOutFirstAndLastRowsToRender() {
    this.rowContainerHeightService.updateOffset();
    let newFirst;
    let newLast;
    if (!this.paginationProxy.isRowsToRender()) {
      newFirst = 0;
      newLast = -1;
    } else if (this.printLayout) {
      this.environment.refreshRowHeightVariable();
      newFirst = this.paginationProxy.getPageFirstRow();
      newLast = this.paginationProxy.getPageLastRow();
    } else {
      const bufferPixels = this.getRowBufferInPixels();
      const gridBodyCtrl = this.ctrlsService.getGridBodyCtrl();
      const suppressRowVirtualisation = this.gos.get("suppressRowVirtualisation");
      let rowHeightsChanged = false;
      let firstPixel;
      let lastPixel;
      do {
        const paginationOffset = this.paginationProxy.getPixelOffset();
        const { pageFirstPixel, pageLastPixel } = this.paginationProxy.getCurrentPagePixelRange();
        const divStretchOffset = this.rowContainerHeightService.getDivStretchOffset();
        const bodyVRange = gridBodyCtrl.getScrollFeature().getVScrollPosition();
        const bodyTopPixel = bodyVRange.top;
        const bodyBottomPixel = bodyVRange.bottom;
        if (suppressRowVirtualisation) {
          firstPixel = pageFirstPixel + divStretchOffset;
          lastPixel = pageLastPixel + divStretchOffset;
        } else {
          firstPixel = Math.max(bodyTopPixel + paginationOffset - bufferPixels, pageFirstPixel) + divStretchOffset;
          lastPixel = Math.min(bodyBottomPixel + paginationOffset + bufferPixels, pageLastPixel) + divStretchOffset;
        }
        this.firstVisibleVPixel = Math.max(bodyTopPixel + paginationOffset, pageFirstPixel) + divStretchOffset;
        this.lastVisibleVPixel = Math.min(bodyBottomPixel + paginationOffset, pageLastPixel) + divStretchOffset;
        rowHeightsChanged = this.ensureAllRowsInRangeHaveHeightsCalculated(firstPixel, lastPixel);
      } while (rowHeightsChanged);
      let firstRowIndex = this.paginationProxy.getRowIndexAtPixel(firstPixel);
      let lastRowIndex = this.paginationProxy.getRowIndexAtPixel(lastPixel);
      const pageFirstRow = this.paginationProxy.getPageFirstRow();
      const pageLastRow = this.paginationProxy.getPageLastRow();
      if (firstRowIndex < pageFirstRow) {
        firstRowIndex = pageFirstRow;
      }
      if (lastRowIndex > pageLastRow) {
        lastRowIndex = pageLastRow;
      }
      newFirst = firstRowIndex;
      newLast = lastRowIndex;
    }
    const rowLayoutNormal = this.gos.isDomLayout("normal");
    const suppressRowCountRestriction = this.gos.get("suppressMaxRenderedRowRestriction");
    const rowBufferMaxSize = Math.max(this.getRowBuffer(), 500);
    if (rowLayoutNormal && !suppressRowCountRestriction) {
      if (newLast - newFirst > rowBufferMaxSize) {
        newLast = newFirst + rowBufferMaxSize;
      }
    }
    const firstDiffers = newFirst !== this.firstRenderedRow;
    const lastDiffers = newLast !== this.lastRenderedRow;
    if (firstDiffers || lastDiffers) {
      this.firstRenderedRow = newFirst;
      this.lastRenderedRow = newLast;
      const event = {
        type: Events.EVENT_VIEWPORT_CHANGED,
        firstRow: newFirst,
        lastRow: newLast
      };
      this.eventService.dispatchEvent(event);
    }
  }
  /**
   * This event will only be fired once, and is queued until after the browser next renders.
   * This allows us to fire an event during the start of the render cycle, when we first see data being rendered
   * but not execute the event until all of the data has finished being rendered to the dom.
   */
  dispatchFirstDataRenderedEvent() {
    if (this.dataFirstRenderedFired) {
      return;
    }
    this.dataFirstRenderedFired = true;
    const event = {
      type: Events.EVENT_FIRST_DATA_RENDERED,
      firstRow: this.firstRenderedRow,
      lastRow: this.lastRenderedRow
    };
    window.requestAnimationFrame(() => {
      this.beans.eventService.dispatchEvent(event);
    });
  }
  ensureAllRowsInRangeHaveHeightsCalculated(topPixel, bottomPixel) {
    const res = this.paginationProxy.ensureRowHeightsValid(topPixel, bottomPixel, -1, -1);
    if (res) {
      this.updateContainerHeights();
    }
    return res;
  }
  getFirstVisibleVerticalPixel() {
    return this.firstVisibleVPixel;
  }
  getLastVisibleVerticalPixel() {
    return this.lastVisibleVPixel;
  }
  getFirstVirtualRenderedRow() {
    return this.firstRenderedRow;
  }
  getLastVirtualRenderedRow() {
    return this.lastRenderedRow;
  }
  // check that none of the rows to remove are editing or focused as:
  // a) if editing, we want to keep them, otherwise the user will loose the context of the edit,
  //    eg user starts editing, enters some text, then scrolls down and then up, next time row rendered
  //    the edit is reset - so we want to keep it rendered.
  // b) if focused, we want ot keep keyboard focus, so if user ctrl+c, it goes to clipboard,
  //    otherwise the user can range select and drag (with focus cell going out of the viewport)
  //    and then ctrl+c, nothing will happen if cell is removed from dom.
  // c) if detail record of master detail, as users complained that the context of detail rows
  //    was getting lost when detail row out of view. eg user expands to show detail row,
  //    then manipulates the detail panel (eg sorts the detail grid), then context is lost
  //    after detail panel is scrolled out of / into view.
  doNotUnVirtualiseRow(rowComp) {
    const REMOVE_ROW = false;
    const KEEP_ROW = true;
    const rowNode = rowComp.getRowNode();
    const rowHasFocus = this.focusService.isRowNodeFocused(rowNode);
    const rowIsEditing = rowComp.isEditing();
    const rowIsDetail = rowNode.detail;
    const mightWantToKeepRow = rowHasFocus || rowIsEditing || rowIsDetail;
    if (!mightWantToKeepRow) {
      return REMOVE_ROW;
    }
    const rowNodePresent = this.paginationProxy.isRowPresent(rowNode);
    return rowNodePresent ? KEEP_ROW : REMOVE_ROW;
  }
  createRowCon(rowNode, animate, afterScroll) {
    const rowCtrlFromCache = this.cachedRowCtrls ? this.cachedRowCtrls.getRow(rowNode) : null;
    if (rowCtrlFromCache) {
      return rowCtrlFromCache;
    }
    const suppressAnimationFrame = this.gos.get("suppressAnimationFrame");
    const useAnimationFrameForCreate = afterScroll && !suppressAnimationFrame && !this.printLayout;
    const res = new RowCtrl(
      rowNode,
      this.beans,
      animate,
      useAnimationFrameForCreate,
      this.printLayout
    );
    return res;
  }
  getRenderedNodes() {
    const renderedRows = this.rowCtrlsByRowIndex;
    return Object.values(renderedRows).map((rowCtrl) => rowCtrl.getRowNode());
  }
  getRowByPosition(rowPosition) {
    let rowCtrl;
    const { rowIndex } = rowPosition;
    switch (rowPosition.rowPinned) {
      case "top":
        rowCtrl = this.topRowCtrls[rowIndex];
        break;
      case "bottom":
        rowCtrl = this.bottomRowCtrls[rowIndex];
        break;
      default:
        rowCtrl = this.rowCtrlsByRowIndex[rowIndex];
        if (!rowCtrl) {
          rowCtrl = this.getStickyTopRowCtrls().find((ctrl) => ctrl.getRowNode().rowIndex === rowIndex) || null;
          if (!rowCtrl) {
            rowCtrl = this.getStickyBottomRowCtrls().find((ctrl) => ctrl.getRowNode().rowIndex === rowIndex) || null;
          }
        }
        break;
    }
    return rowCtrl;
  }
  // returns true if any row between startIndex and endIndex is rendered. used by
  // SSRM or IRM, as they don't want to purge visible blocks from cache.
  isRangeInRenderedViewport(startIndex, endIndex) {
    const parentClosed = startIndex == null || endIndex == null;
    if (parentClosed) {
      return false;
    }
    const blockAfterViewport = startIndex > this.lastRenderedRow;
    const blockBeforeViewport = endIndex < this.firstRenderedRow;
    const blockInsideViewport = !blockBeforeViewport && !blockAfterViewport;
    return blockInsideViewport;
  }
};
__decorateClass([
  Autowired("animationFrameService")
], RowRenderer.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("paginationProxy")
], RowRenderer.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("columnModel")
], RowRenderer.prototype, "columnModel", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], RowRenderer.prototype, "pinnedRowModel", 2);
__decorateClass([
  Autowired("rowModel")
], RowRenderer.prototype, "rowModel", 2);
__decorateClass([
  Autowired("focusService")
], RowRenderer.prototype, "focusService", 2);
__decorateClass([
  Autowired("beans")
], RowRenderer.prototype, "beans", 2);
__decorateClass([
  Autowired("rowContainerHeightService")
], RowRenderer.prototype, "rowContainerHeightService", 2);
__decorateClass([
  Autowired("ctrlsService")
], RowRenderer.prototype, "ctrlsService", 2);
__decorateClass([
  PostConstruct
], RowRenderer.prototype, "postConstruct", 1);
RowRenderer = __decorateClass([
  Bean("rowRenderer")
], RowRenderer);
var RowCtrlCache = class {
  constructor(maxCount) {
    // map for fast access
    this.entriesMap = {};
    // list for keeping order
    this.entriesList = [];
    this.maxCount = maxCount;
  }
  addRow(rowCtrl) {
    this.entriesMap[rowCtrl.getRowNode().id] = rowCtrl;
    this.entriesList.push(rowCtrl);
    rowCtrl.setCached(true);
    if (this.entriesList.length > this.maxCount) {
      const rowCtrlToDestroy = this.entriesList[0];
      rowCtrlToDestroy.destroyFirstPass();
      rowCtrlToDestroy.destroySecondPass();
      this.removeFromCache(rowCtrlToDestroy);
    }
  }
  getRow(rowNode) {
    if (rowNode == null || rowNode.id == null) {
      return null;
    }
    const res = this.entriesMap[rowNode.id];
    if (!res) {
      return null;
    }
    this.removeFromCache(res);
    res.setCached(false);
    const rowNodeMismatch = res.getRowNode() != rowNode;
    return rowNodeMismatch ? null : res;
  }
  has(rowNode) {
    return this.entriesMap[rowNode.id] != null;
  }
  removeRow(rowNode) {
    const rowNodeId = rowNode.id;
    const ctrl = this.entriesMap[rowNodeId];
    delete this.entriesMap[rowNodeId];
    removeFromArray(this.entriesList, ctrl);
  }
  removeFromCache(rowCtrl) {
    const rowNodeId = rowCtrl.getRowNode().id;
    delete this.entriesMap[rowNodeId];
    removeFromArray(this.entriesList, rowCtrl);
  }
  getEntries() {
    return this.entriesList;
  }
};

// community-modules/core/src/pinnedRowModel/pinnedRowModel.ts
var PinnedRowModel = class extends BeanStub {
  init() {
    this.setPinnedTopRowData();
    this.setPinnedBottomRowData();
    this.addManagedPropertyListener("pinnedTopRowData", () => this.setPinnedTopRowData());
    this.addManagedPropertyListener("pinnedBottomRowData", () => this.setPinnedBottomRowData());
  }
  isEmpty(floating) {
    const rows = floating === "top" ? this.pinnedTopRows : this.pinnedBottomRows;
    return missingOrEmpty(rows);
  }
  isRowsToRender(floating) {
    return !this.isEmpty(floating);
  }
  getRowAtPixel(pixel, floating) {
    const rows = floating === "top" ? this.pinnedTopRows : this.pinnedBottomRows;
    if (missingOrEmpty(rows)) {
      return 0;
    }
    for (let i = 0; i < rows.length; i++) {
      const rowNode = rows[i];
      const rowTopPixel = rowNode.rowTop + rowNode.rowHeight - 1;
      if (rowTopPixel >= pixel) {
        return i;
      }
    }
    return rows.length - 1;
  }
  setPinnedTopRowData() {
    const rowData = this.gos.get("pinnedTopRowData");
    this.pinnedTopRows = this.createNodesFromData(rowData, true);
    const event = {
      type: Events.EVENT_PINNED_ROW_DATA_CHANGED
    };
    this.eventService.dispatchEvent(event);
  }
  setPinnedBottomRowData() {
    const rowData = this.gos.get("pinnedBottomRowData");
    this.pinnedBottomRows = this.createNodesFromData(rowData, false);
    const event = {
      type: Events.EVENT_PINNED_ROW_DATA_CHANGED
    };
    this.eventService.dispatchEvent(event);
  }
  createNodesFromData(allData, isTop) {
    const rowNodes = [];
    if (allData) {
      let nextRowTop = 0;
      allData.forEach((dataItem, index) => {
        const rowNode = new RowNode(this.beans);
        rowNode.data = dataItem;
        const idPrefix = isTop ? RowNode.ID_PREFIX_TOP_PINNED : RowNode.ID_PREFIX_BOTTOM_PINNED;
        rowNode.id = idPrefix + index;
        rowNode.rowPinned = isTop ? "top" : "bottom";
        rowNode.setRowTop(nextRowTop);
        rowNode.setRowHeight(this.gos.getRowHeightForNode(rowNode).height);
        rowNode.setRowIndex(index);
        nextRowTop += rowNode.rowHeight;
        rowNodes.push(rowNode);
      });
    }
    return rowNodes;
  }
  getPinnedTopRowData() {
    return this.pinnedTopRows;
  }
  getPinnedBottomRowData() {
    return this.pinnedBottomRows;
  }
  getPinnedTopTotalHeight() {
    return this.getTotalHeight(this.pinnedTopRows);
  }
  getPinnedTopRowCount() {
    return this.pinnedTopRows ? this.pinnedTopRows.length : 0;
  }
  getPinnedBottomRowCount() {
    return this.pinnedBottomRows ? this.pinnedBottomRows.length : 0;
  }
  getPinnedTopRow(index) {
    return this.pinnedTopRows[index];
  }
  getPinnedBottomRow(index) {
    return this.pinnedBottomRows[index];
  }
  forEachPinnedTopRow(callback) {
    if (missingOrEmpty(this.pinnedTopRows)) {
      return;
    }
    this.pinnedTopRows.forEach(callback);
  }
  forEachPinnedBottomRow(callback) {
    if (missingOrEmpty(this.pinnedBottomRows)) {
      return;
    }
    this.pinnedBottomRows.forEach(callback);
  }
  getPinnedBottomTotalHeight() {
    return this.getTotalHeight(this.pinnedBottomRows);
  }
  getTotalHeight(rowNodes) {
    if (!rowNodes || rowNodes.length === 0) {
      return 0;
    }
    const lastNode = last(rowNodes);
    return lastNode.rowTop + lastNode.rowHeight;
  }
};
__decorateClass([
  Autowired("beans")
], PinnedRowModel.prototype, "beans", 2);
__decorateClass([
  PostConstruct
], PinnedRowModel.prototype, "init", 1);
PinnedRowModel = __decorateClass([
  Bean("pinnedRowModel")
], PinnedRowModel);

// community-modules/core/src/interfaces/serverSideTransaction.ts
var ServerSideTransactionResultStatus = /* @__PURE__ */ ((ServerSideTransactionResultStatus2) => {
  ServerSideTransactionResultStatus2["Applied"] = "Applied";
  ServerSideTransactionResultStatus2["StoreNotFound"] = "StoreNotFound";
  ServerSideTransactionResultStatus2["StoreLoading"] = "StoreLoading";
  ServerSideTransactionResultStatus2["StoreWaitingToLoad"] = "StoreWaitingToLoad";
  ServerSideTransactionResultStatus2["StoreLoadingFailed"] = "StoreLoadingFailed";
  ServerSideTransactionResultStatus2["StoreWrongType"] = "StoreWrongType";
  ServerSideTransactionResultStatus2["Cancelled"] = "Cancelled";
  ServerSideTransactionResultStatus2["StoreNotStarted"] = "StoreNotStarted";
  return ServerSideTransactionResultStatus2;
})(ServerSideTransactionResultStatus || {});

// community-modules/core/src/utils/changedPath.ts
var ChangedPath = class {
  constructor(keepingColumns, rootNode) {
    // whether changed path is active of not. it is active when a) doing
    // a transaction update or b) doing change detection. if we are doing
    // a CSRM refresh for other reasons (after sort or filter, or user calling
    // setRowData() without delta mode) then we are not active. we are also
    // marked as not active if secondary columns change in pivot (as this impacts
    // aggregations)
    this.active = true;
    // for each node in the change path, we also store which columns need
    // to be re-aggregated.
    this.nodeIdsToColumns = {};
    // for quick lookup, all items in the change path are mapped by nodeId
    this.mapToItems = {};
    this.keepingColumns = keepingColumns;
    this.pathRoot = {
      rowNode: rootNode,
      children: null
    };
    this.mapToItems[rootNode.id] = this.pathRoot;
  }
  // can be set inactive by:
  // a) ClientSideRowModel, if no transactions or
  // b) PivotService, if secondary columns changed
  setInactive() {
    this.active = false;
  }
  isActive() {
    return this.active;
  }
  depthFirstSearchChangedPath(pathItem, callback) {
    if (pathItem.children) {
      for (let i = 0; i < pathItem.children.length; i++) {
        this.depthFirstSearchChangedPath(pathItem.children[i], callback);
      }
    }
    callback(pathItem.rowNode);
  }
  depthFirstSearchEverything(rowNode, callback, traverseEverything) {
    if (rowNode.childrenAfterGroup) {
      for (let i = 0; i < rowNode.childrenAfterGroup.length; i++) {
        const childNode = rowNode.childrenAfterGroup[i];
        if (childNode.childrenAfterGroup) {
          this.depthFirstSearchEverything(rowNode.childrenAfterGroup[i], callback, traverseEverything);
        } else if (traverseEverything) {
          callback(childNode);
        }
      }
    }
    callback(rowNode);
  }
  // traverseLeafNodes -> used when NOT doing changed path, ie traversing everything. the callback
  // will be called for child nodes in addition to parent nodes.
  forEachChangedNodeDepthFirst(callback, traverseLeafNodes = false, includeUnchangedNodes = false) {
    if (this.active && !includeUnchangedNodes) {
      this.depthFirstSearchChangedPath(this.pathRoot, callback);
    } else {
      this.depthFirstSearchEverything(this.pathRoot.rowNode, callback, traverseLeafNodes);
    }
  }
  executeFromRootNode(callback) {
    callback(this.pathRoot.rowNode);
  }
  createPathItems(rowNode) {
    let pointer = rowNode;
    let newEntryCount = 0;
    while (!this.mapToItems[pointer.id]) {
      const newEntry = {
        rowNode: pointer,
        children: null
      };
      this.mapToItems[pointer.id] = newEntry;
      newEntryCount++;
      pointer = pointer.parent;
    }
    return newEntryCount;
  }
  populateColumnsMap(rowNode, columns) {
    if (!this.keepingColumns || !columns) {
      return;
    }
    let pointer = rowNode;
    while (pointer) {
      if (!this.nodeIdsToColumns[pointer.id]) {
        this.nodeIdsToColumns[pointer.id] = {};
      }
      columns.forEach((col) => this.nodeIdsToColumns[pointer.id][col.getId()] = true);
      pointer = pointer.parent;
    }
  }
  linkPathItems(rowNode, newEntryCount) {
    let pointer = rowNode;
    for (let i = 0; i < newEntryCount; i++) {
      const thisItem = this.mapToItems[pointer.id];
      const parentItem = this.mapToItems[pointer.parent.id];
      if (!parentItem.children) {
        parentItem.children = [];
      }
      parentItem.children.push(thisItem);
      pointer = pointer.parent;
    }
  }
  // called by
  // 1) change detection (provides cols) and
  // 2) groupStage if doing transaction update (doesn't provide cols)
  addParentNode(rowNode, columns) {
    if (!rowNode || rowNode.isRowPinned()) {
      return;
    }
    const newEntryCount = this.createPathItems(rowNode);
    this.linkPathItems(rowNode, newEntryCount);
    this.populateColumnsMap(rowNode, columns);
  }
  canSkip(rowNode) {
    return this.active && !this.mapToItems[rowNode.id];
  }
  getValueColumnsForNode(rowNode, valueColumns) {
    if (!this.keepingColumns) {
      return valueColumns;
    }
    const colsForThisNode = this.nodeIdsToColumns[rowNode.id];
    const result = valueColumns.filter((col) => colsForThisNode[col.getId()]);
    return result;
  }
  getNotValueColumnsForNode(rowNode, valueColumns) {
    if (!this.keepingColumns) {
      return null;
    }
    const colsForThisNode = this.nodeIdsToColumns[rowNode.id];
    const result = valueColumns.filter((col) => !colsForThisNode[col.getId()]);
    return result;
  }
};

// community-modules/core/src/rowNodeCache/rowNodeBlock.ts
var _RowNodeBlock = class _RowNodeBlock extends BeanStub {
  constructor(id) {
    super();
    this.state = _RowNodeBlock.STATE_WAITING_TO_LOAD;
    this.version = 0;
    this.id = id;
  }
  getId() {
    return this.id;
  }
  load() {
    this.state = _RowNodeBlock.STATE_LOADING;
    this.loadFromDatasource();
  }
  getVersion() {
    return this.version;
  }
  setStateWaitingToLoad() {
    this.version++;
    this.state = _RowNodeBlock.STATE_WAITING_TO_LOAD;
  }
  getState() {
    return this.state;
  }
  pageLoadFailed(version) {
    const requestMostRecentAndLive = this.isRequestMostRecentAndLive(version);
    if (requestMostRecentAndLive) {
      this.state = _RowNodeBlock.STATE_FAILED;
      this.processServerFail();
    }
    this.dispatchLoadCompleted(false);
  }
  success(version, params) {
    this.successCommon(version, params);
  }
  pageLoaded(version, rows, lastRow) {
    this.successCommon(version, { rowData: rows, rowCount: lastRow });
  }
  isRequestMostRecentAndLive(version) {
    const thisIsMostRecentRequest = version === this.version;
    const weAreNotDestroyed = this.isAlive();
    return thisIsMostRecentRequest && weAreNotDestroyed;
  }
  successCommon(version, params) {
    this.dispatchLoadCompleted();
    const requestMostRecentAndLive = this.isRequestMostRecentAndLive(version);
    if (requestMostRecentAndLive) {
      this.state = _RowNodeBlock.STATE_LOADED;
      this.processServerResult(params);
    }
  }
  dispatchLoadCompleted(success = true) {
    const event = {
      type: _RowNodeBlock.EVENT_LOAD_COMPLETE,
      success,
      block: this
    };
    this.dispatchEvent(event);
  }
};
_RowNodeBlock.EVENT_LOAD_COMPLETE = "loadComplete";
_RowNodeBlock.STATE_WAITING_TO_LOAD = "needsLoading";
_RowNodeBlock.STATE_LOADING = "loading";
_RowNodeBlock.STATE_LOADED = "loaded";
_RowNodeBlock.STATE_FAILED = "failed";
var RowNodeBlock = _RowNodeBlock;

// community-modules/core/src/rowNodeCache/rowNodeBlockLoader.ts
var RowNodeBlockLoader = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.activeBlockLoadsCount = 0;
    this.blocks = [];
    this.active = true;
  }
  postConstruct() {
    this.maxConcurrentRequests = this.getMaxConcurrentDatasourceRequests();
    const blockLoadDebounceMillis = this.gos.get("blockLoadDebounceMillis");
    if (blockLoadDebounceMillis && blockLoadDebounceMillis > 0) {
      this.checkBlockToLoadDebounce = _.debounce(this.performCheckBlocksToLoad.bind(this), blockLoadDebounceMillis);
    }
  }
  setBeans(loggerFactory) {
    this.logger = loggerFactory.create("RowNodeBlockLoader");
  }
  getMaxConcurrentDatasourceRequests() {
    const res = this.gos.get("maxConcurrentDatasourceRequests");
    if (res == null) {
      return 2;
    }
    if (res <= 0) {
      return;
    }
    return res;
  }
  addBlock(block) {
    this.blocks.push(block);
    block.addEventListener(RowNodeBlock.EVENT_LOAD_COMPLETE, this.loadComplete.bind(this));
    this.checkBlockToLoad();
  }
  removeBlock(block) {
    _.removeFromArray(this.blocks, block);
  }
  destroy() {
    super.destroy();
    this.active = false;
  }
  loadComplete() {
    this.activeBlockLoadsCount--;
    this.checkBlockToLoad();
    this.dispatchEvent({ type: RowNodeBlockLoader.BLOCK_LOADED_EVENT });
    if (this.activeBlockLoadsCount == 0) {
      this.dispatchEvent({ type: RowNodeBlockLoader.BLOCK_LOADER_FINISHED_EVENT });
    }
  }
  checkBlockToLoad() {
    if (this.checkBlockToLoadDebounce) {
      this.checkBlockToLoadDebounce();
    } else {
      this.performCheckBlocksToLoad();
    }
  }
  performCheckBlocksToLoad() {
    if (!this.active) {
      return;
    }
    this.printCacheStatus();
    if (this.maxConcurrentRequests != null && this.activeBlockLoadsCount >= this.maxConcurrentRequests) {
      this.logger.log(`checkBlockToLoad: max loads exceeded`);
      return;
    }
    const loadAvailability = this.getAvailableLoadingCount();
    const blocksToLoad = this.blocks.filter((block) => block.getState() === RowNodeBlock.STATE_WAITING_TO_LOAD).slice(0, loadAvailability);
    this.registerLoads(blocksToLoad.length);
    blocksToLoad.forEach((block) => block.load());
    this.printCacheStatus();
  }
  getBlockState() {
    if (this.gos.isRowModelType("serverSide")) {
      const ssrm = this.rowModel;
      return ssrm.getBlockStates();
    }
    const result = {};
    this.blocks.forEach((block) => {
      const { id, state } = block.getBlockStateJson();
      result[id] = state;
    });
    return result;
  }
  printCacheStatus() {
    if (this.logger.isLogging()) {
      this.logger.log(`printCacheStatus: activePageLoadsCount = ${this.activeBlockLoadsCount}, blocks = ${JSON.stringify(this.getBlockState())}`);
    }
  }
  isLoading() {
    return this.activeBlockLoadsCount > 0;
  }
  registerLoads(count) {
    this.activeBlockLoadsCount += count;
  }
  getAvailableLoadingCount() {
    return this.maxConcurrentRequests !== void 0 ? this.maxConcurrentRequests - this.activeBlockLoadsCount : void 0;
  }
};
RowNodeBlockLoader.BLOCK_LOADED_EVENT = "blockLoaded";
RowNodeBlockLoader.BLOCK_LOADER_FINISHED_EVENT = "blockLoaderFinished";
__decorateClass([
  Autowired("rowModel")
], RowNodeBlockLoader.prototype, "rowModel", 2);
__decorateClass([
  PostConstruct
], RowNodeBlockLoader.prototype, "postConstruct", 1);
__decorateClass([
  __decorateParam(0, Qualifier("loggerFactory"))
], RowNodeBlockLoader.prototype, "setBeans", 1);
RowNodeBlockLoader = __decorateClass([
  Bean("rowNodeBlockLoader")
], RowNodeBlockLoader);

// community-modules/core/src/pagination/paginationProxy.ts
var PaginationProxy = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.currentPage = 0;
    this.topDisplayedRowIndex = 0;
    this.bottomDisplayedRowIndex = 0;
    this.pixelOffset = 0;
    this.masterRowCount = 0;
  }
  postConstruct() {
    this.active = this.gos.get("pagination");
    this.pageSizeFromGridOptions = this.gos.get("paginationPageSize");
    this.paginateChildRows = this.isPaginateChildRows();
    this.addManagedListener(this.eventService, Events.EVENT_MODEL_UPDATED, this.onModelUpdated.bind(this));
    this.addManagedPropertyListener("pagination", this.onPaginationGridOptionChanged.bind(this));
    this.addManagedPropertyListener("paginationPageSize", this.onPageSizeGridOptionChanged.bind(this));
    this.onModelUpdated();
  }
  ensureRowHeightsValid(startPixel, endPixel, startLimitIndex, endLimitIndex) {
    const res = this.rowModel.ensureRowHeightsValid(startPixel, endPixel, this.getPageFirstRow(), this.getPageLastRow());
    if (res) {
      this.calculatePages();
    }
    return res;
  }
  isPaginateChildRows() {
    const shouldPaginate = this.gos.get("groupRemoveSingleChildren") || this.gos.get("groupRemoveLowestSingleChildren");
    if (shouldPaginate) {
      return true;
    }
    return this.gos.get("paginateChildRows");
  }
  onModelUpdated(modelUpdatedEvent) {
    this.calculatePages();
    const paginationChangedEvent = {
      type: Events.EVENT_PAGINATION_CHANGED,
      animate: modelUpdatedEvent ? modelUpdatedEvent.animate : false,
      newData: modelUpdatedEvent ? modelUpdatedEvent.newData : false,
      newPage: modelUpdatedEvent ? modelUpdatedEvent.newPage : false,
      newPageSize: modelUpdatedEvent ? modelUpdatedEvent.newPageSize : false,
      keepRenderedRows: modelUpdatedEvent ? modelUpdatedEvent.keepRenderedRows : false
    };
    this.eventService.dispatchEvent(paginationChangedEvent);
  }
  onPaginationGridOptionChanged() {
    this.active = this.gos.get("pagination");
    this.calculatePages();
    const paginationChangedEvent = {
      type: Events.EVENT_PAGINATION_CHANGED,
      animate: false,
      newData: false,
      newPage: false,
      newPageSize: false,
      // important to keep rendered rows, otherwise every time grid is resized,
      // we would destroy all the rows.
      keepRenderedRows: true
    };
    this.eventService.dispatchEvent(paginationChangedEvent);
  }
  onPageSizeGridOptionChanged() {
    this.setPageSize(this.gos.get("paginationPageSize"), "gridOptions");
  }
  goToPage(page) {
    if (!this.active || this.currentPage === page || typeof this.currentPage !== "number") {
      return;
    }
    this.currentPage = page;
    this.calculatePages();
    const paginationChangedEvent = {
      type: Events.EVENT_PAGINATION_CHANGED,
      animate: false,
      newData: false,
      newPage: true,
      newPageSize: false,
      keepRenderedRows: false
    };
    this.eventService.dispatchEvent(paginationChangedEvent);
  }
  getPixelOffset() {
    return this.pixelOffset;
  }
  getRow(index) {
    return this.rowModel.getRow(index);
  }
  getRowNode(id) {
    return this.rowModel.getRowNode(id);
  }
  getRowIndexAtPixel(pixel) {
    return this.rowModel.getRowIndexAtPixel(pixel);
  }
  getCurrentPageHeight() {
    if (missing(this.topRowBounds) || missing(this.bottomRowBounds)) {
      return 0;
    }
    return Math.max(this.bottomRowBounds.rowTop + this.bottomRowBounds.rowHeight - this.topRowBounds.rowTop, 0);
  }
  getCurrentPagePixelRange() {
    const pageFirstPixel = this.topRowBounds ? this.topRowBounds.rowTop : 0;
    const pageLastPixel = this.bottomRowBounds ? this.bottomRowBounds.rowTop + this.bottomRowBounds.rowHeight : 0;
    return { pageFirstPixel, pageLastPixel };
  }
  isRowPresent(rowNode) {
    if (!this.rowModel.isRowPresent(rowNode)) {
      return false;
    }
    const nodeIsInPage = rowNode.rowIndex >= this.topDisplayedRowIndex && rowNode.rowIndex <= this.bottomDisplayedRowIndex;
    return nodeIsInPage;
  }
  isEmpty() {
    return this.rowModel.isEmpty();
  }
  isRowsToRender() {
    return this.rowModel.isRowsToRender();
  }
  forEachNode(callback) {
    return this.rowModel.forEachNode(callback);
  }
  forEachNodeOnPage(callback) {
    const firstRow = this.getPageFirstRow();
    const lastRow = this.getPageLastRow();
    for (let i = firstRow; i <= lastRow; i++) {
      const node = this.getRow(i);
      if (node) {
        callback(node);
      }
    }
  }
  getType() {
    return this.rowModel.getType();
  }
  getRowBounds(index) {
    const res = this.rowModel.getRowBounds(index);
    res.rowIndex = index;
    return res;
  }
  getPageFirstRow() {
    return this.topRowBounds ? this.topRowBounds.rowIndex : -1;
  }
  getPageLastRow() {
    return this.bottomRowBounds ? this.bottomRowBounds.rowIndex : -1;
  }
  getRowCount() {
    return this.rowModel.getRowCount();
  }
  getPageForIndex(index) {
    return Math.floor(index / this.pageSize);
  }
  goToPageWithIndex(index) {
    if (!this.active) {
      return;
    }
    const pageNumber = this.getPageForIndex(index);
    this.goToPage(pageNumber);
  }
  isRowInPage(row) {
    if (!this.active) {
      return true;
    }
    const rowPage = this.getPageForIndex(row.rowIndex);
    return rowPage === this.currentPage;
  }
  isLastPageFound() {
    return this.rowModel.isLastRowIndexKnown();
  }
  getCurrentPage() {
    return this.currentPage;
  }
  goToNextPage() {
    this.goToPage(this.currentPage + 1);
  }
  goToPreviousPage() {
    this.goToPage(this.currentPage - 1);
  }
  goToFirstPage() {
    this.goToPage(0);
  }
  goToLastPage() {
    const rowCount = this.rowModel.getRowCount();
    const lastPage = Math.floor(rowCount / this.pageSize);
    this.goToPage(lastPage);
  }
  getPageSize() {
    return this.pageSize;
  }
  getTotalPages() {
    return this.totalPages;
  }
  /** This is only for state setting before data has been loaded */
  setPage(page) {
    this.currentPage = page;
  }
  get pageSize() {
    if (exists(this.pageSizeAutoCalculated)) {
      return this.pageSizeAutoCalculated;
    }
    if (exists(this.pageSizeFromPageSizeSelector)) {
      return this.pageSizeFromPageSizeSelector;
    }
    if (exists(this.pageSizeFromInitialState)) {
      return this.pageSizeFromInitialState;
    }
    if (exists(this.pageSizeFromGridOptions)) {
      return this.pageSizeFromGridOptions;
    }
    return this.defaultPageSize;
  }
  unsetAutoCalculatedPageSize() {
    if (this.pageSizeAutoCalculated === void 0) {
      return;
    }
    const oldPageSize = this.pageSizeAutoCalculated;
    this.pageSizeAutoCalculated = void 0;
    if (this.pageSize === oldPageSize) {
      return;
    }
    this.calculatePages();
    const paginationChangedEvent = {
      type: Events.EVENT_PAGINATION_CHANGED,
      animate: false,
      newData: false,
      newPage: false,
      newPageSize: true,
      keepRenderedRows: false
    };
    this.eventService.dispatchEvent(paginationChangedEvent);
  }
  setPageSize(size, source) {
    const currentSize = this.pageSize;
    switch (source) {
      case "autoCalculated":
        this.pageSizeAutoCalculated = size;
        break;
      case "pageSizeSelector":
        this.pageSizeFromPageSizeSelector = size;
        if (this.currentPage !== 0) {
          this.goToFirstPage();
        }
        break;
      case "initialState":
        this.pageSizeFromInitialState = size;
        break;
      case "gridOptions":
        this.pageSizeFromGridOptions = size;
        this.pageSizeFromInitialState = void 0;
        this.pageSizeFromPageSizeSelector = void 0;
        if (this.currentPage !== 0) {
          this.goToFirstPage();
        }
        break;
    }
    if (currentSize !== this.pageSize) {
      this.calculatePages();
      const paginationChangedEvent = {
        type: Events.EVENT_PAGINATION_CHANGED,
        animate: false,
        newData: false,
        newPage: false,
        newPageSize: true,
        keepRenderedRows: true
      };
      this.eventService.dispatchEvent(paginationChangedEvent);
    }
  }
  calculatePages() {
    if (this.active) {
      if (this.paginateChildRows) {
        this.calculatePagesAllRows();
      } else {
        this.calculatePagesMasterRowsOnly();
      }
    } else {
      this.calculatedPagesNotActive();
    }
    this.topRowBounds = this.rowModel.getRowBounds(this.topDisplayedRowIndex);
    if (this.topRowBounds) {
      this.topRowBounds.rowIndex = this.topDisplayedRowIndex;
    }
    this.bottomRowBounds = this.rowModel.getRowBounds(this.bottomDisplayedRowIndex);
    if (this.bottomRowBounds) {
      this.bottomRowBounds.rowIndex = this.bottomDisplayedRowIndex;
    }
    this.setPixelOffset(exists(this.topRowBounds) ? this.topRowBounds.rowTop : 0);
  }
  setPixelOffset(value) {
    if (this.pixelOffset === value) {
      return;
    }
    this.pixelOffset = value;
    this.eventService.dispatchEvent({ type: Events.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED });
  }
  setZeroRows() {
    this.masterRowCount = 0;
    this.topDisplayedRowIndex = 0;
    this.bottomDisplayedRowIndex = -1;
    this.currentPage = 0;
    this.totalPages = 0;
  }
  adjustCurrentPageIfInvalid() {
    if (this.currentPage >= this.totalPages) {
      this.currentPage = this.totalPages - 1;
    }
    if (!isFinite(this.currentPage) || isNaN(this.currentPage) || this.currentPage < 0) {
      this.currentPage = 0;
    }
  }
  calculatePagesMasterRowsOnly() {
    this.masterRowCount = this.rowModel.getTopLevelRowCount();
    if (this.masterRowCount <= 0) {
      this.setZeroRows();
      return;
    }
    const masterLastRowIndex = this.masterRowCount - 1;
    this.totalPages = Math.floor(masterLastRowIndex / this.pageSize) + 1;
    this.adjustCurrentPageIfInvalid();
    const masterPageStartIndex = this.pageSize * this.currentPage;
    let masterPageEndIndex = this.pageSize * (this.currentPage + 1) - 1;
    if (masterPageEndIndex > masterLastRowIndex) {
      masterPageEndIndex = masterLastRowIndex;
    }
    this.topDisplayedRowIndex = this.rowModel.getTopLevelRowDisplayedIndex(masterPageStartIndex);
    if (masterPageEndIndex === masterLastRowIndex) {
      this.bottomDisplayedRowIndex = this.rowModel.getRowCount() - 1;
    } else {
      const firstIndexNotToShow = this.rowModel.getTopLevelRowDisplayedIndex(masterPageEndIndex + 1);
      this.bottomDisplayedRowIndex = firstIndexNotToShow - 1;
    }
  }
  getMasterRowCount() {
    return this.masterRowCount;
  }
  calculatePagesAllRows() {
    this.masterRowCount = this.rowModel.getRowCount();
    if (this.masterRowCount === 0) {
      this.setZeroRows();
      return;
    }
    const maxRowIndex = this.masterRowCount - 1;
    this.totalPages = Math.floor(maxRowIndex / this.pageSize) + 1;
    this.adjustCurrentPageIfInvalid();
    this.topDisplayedRowIndex = this.pageSize * this.currentPage;
    this.bottomDisplayedRowIndex = this.pageSize * (this.currentPage + 1) - 1;
    if (this.bottomDisplayedRowIndex > maxRowIndex) {
      this.bottomDisplayedRowIndex = maxRowIndex;
    }
  }
  calculatedPagesNotActive() {
    this.setPageSize(void 0, "autoCalculated");
    this.totalPages = 1;
    this.currentPage = 0;
    this.topDisplayedRowIndex = 0;
    this.bottomDisplayedRowIndex = this.rowModel.getRowCount() - 1;
  }
};
__decorateClass([
  Autowired("rowModel")
], PaginationProxy.prototype, "rowModel", 2);
__decorateClass([
  PostConstruct
], PaginationProxy.prototype, "postConstruct", 1);
PaginationProxy = __decorateClass([
  Bean("paginationProxy")
], PaginationProxy);

// community-modules/core/src/styling/stylingService.ts
var StylingService = class extends BeanStub {
  processAllCellClasses(colDef, params, onApplicableClass, onNotApplicableClass) {
    this.processClassRules(void 0, colDef.cellClassRules, params, onApplicableClass, onNotApplicableClass);
    this.processStaticCellClasses(colDef, params, onApplicableClass);
  }
  processClassRules(previousClassRules, classRules, params, onApplicableClass, onNotApplicableClass) {
    if (classRules == null && previousClassRules == null) {
      return;
    }
    const classesToApply = {};
    const classesToRemove = {};
    const forEachSingleClass = (className, callback) => {
      className.split(" ").forEach((singleClass) => {
        if (singleClass.trim() == "")
          return;
        callback(singleClass);
      });
    };
    if (classRules) {
      const classNames = Object.keys(classRules);
      for (let i = 0; i < classNames.length; i++) {
        const className = classNames[i];
        const rule = classRules[className];
        let resultOfRule;
        if (typeof rule === "string") {
          resultOfRule = this.expressionService.evaluate(rule, params);
        } else if (typeof rule === "function") {
          resultOfRule = rule(params);
        }
        forEachSingleClass(className, (singleClass) => {
          resultOfRule ? classesToApply[singleClass] = true : classesToRemove[singleClass] = true;
        });
      }
    }
    if (previousClassRules && onNotApplicableClass) {
      Object.keys(previousClassRules).forEach((className) => forEachSingleClass(className, (singleClass) => {
        if (!classesToApply[singleClass]) {
          classesToRemove[singleClass] = true;
        }
      }));
    }
    if (onNotApplicableClass) {
      Object.keys(classesToRemove).forEach(onNotApplicableClass);
    }
    Object.keys(classesToApply).forEach(onApplicableClass);
  }
  getStaticCellClasses(colDef, params) {
    const { cellClass } = colDef;
    if (!cellClass) {
      return [];
    }
    let classOrClasses;
    if (typeof cellClass === "function") {
      const cellClassFunc = cellClass;
      classOrClasses = cellClassFunc(params);
    } else {
      classOrClasses = cellClass;
    }
    if (typeof classOrClasses === "string") {
      classOrClasses = [classOrClasses];
    }
    return classOrClasses || [];
  }
  processStaticCellClasses(colDef, params, onApplicableClass) {
    const classOrClasses = this.getStaticCellClasses(colDef, params);
    classOrClasses.forEach((cssClassItem) => {
      onApplicableClass(cssClassItem);
    });
  }
};
__decorateClass([
  Autowired("expressionService")
], StylingService.prototype, "expressionService", 2);
StylingService = __decorateClass([
  Bean("stylingService")
], StylingService);

// community-modules/core/src/widgets/agToggleButton.ts
var AgToggleButton = class extends AgCheckbox {
  constructor(config) {
    super(config, "ag-toggle-button");
  }
  setValue(value, silent) {
    super.setValue(value, silent);
    this.addOrRemoveCssClass("ag-selected", this.getValue());
    return this;
  }
};

// community-modules/core/src/widgets/agInputTextArea.ts
var AgInputTextArea = class extends AgAbstractInputField {
  constructor(config) {
    super(config, "ag-text-area", null, "textarea");
  }
  setValue(value, silent) {
    const ret = super.setValue(value, silent);
    this.eInput.value = value;
    return ret;
  }
  setCols(cols) {
    this.eInput.cols = cols;
    return this;
  }
  setRows(rows) {
    this.eInput.rows = rows;
    return this;
  }
};

// community-modules/core/src/widgets/agInputDateField.ts
var AgInputDateField = class extends AgInputTextField {
  constructor(config) {
    super(config, "ag-date-field", "date");
  }
  postConstruct() {
    super.postConstruct();
    this.addManagedListener(this.eInput, "wheel", this.onWheel.bind(this));
    const usingSafari = isBrowserSafari();
    this.addManagedListener(this.eInput, "mousedown", () => {
      if (this.isDisabled() || usingSafari) {
        return;
      }
      this.eInput.focus();
    });
    this.eInput.step = "any";
  }
  onWheel(e) {
    if (this.gos.getActiveDomElement() === this.eInput) {
      e.preventDefault();
    }
  }
  setMin(minDate) {
    var _a;
    const min = minDate instanceof Date ? (_a = serialiseDate(minDate != null ? minDate : null, false)) != null ? _a : void 0 : minDate;
    if (this.min === min) {
      return this;
    }
    this.min = min;
    addOrRemoveAttribute(this.eInput, "min", min);
    return this;
  }
  setMax(maxDate) {
    var _a;
    const max = maxDate instanceof Date ? (_a = serialiseDate(maxDate != null ? maxDate : null, false)) != null ? _a : void 0 : maxDate;
    if (this.max === max) {
      return this;
    }
    this.max = max;
    addOrRemoveAttribute(this.eInput, "max", max);
    return this;
  }
  setStep(step) {
    if (this.step === step) {
      return this;
    }
    this.step = step;
    addOrRemoveAttribute(this.eInput, "step", step);
    return this;
  }
  getDate() {
    var _a;
    if (!this.eInput.validity.valid) {
      return void 0;
    }
    return (_a = parseDateTimeFromString(this.getValue())) != null ? _a : void 0;
  }
  setDate(date, silent) {
    this.setValue(serialiseDate(date != null ? date : null, false), silent);
  }
};

// community-modules/core/src/widgets/agInputRange.ts
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.addManagedListener(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;
  }
};

// community-modules/core/src/widgets/agRichSelectRow.ts
var RichSelectRow = class extends Component {
  constructor(params, wrapperEl) {
    super(
      /* html */
      `<div class="ag-rich-select-row" role="presentation"></div>`
    );
    this.params = params;
    this.wrapperEl = wrapperEl;
  }
  postConstruct() {
    this.addManagedListener(this.getGui(), "click", this.onClick.bind(this));
  }
  setState(value) {
    let formattedValue = "";
    if (this.params.valueFormatter) {
      formattedValue = this.params.valueFormatter(value);
    }
    const rendererSuccessful = this.populateWithRenderer(value, formattedValue);
    if (!rendererSuccessful) {
      this.populateWithoutRenderer(value, formattedValue);
    }
    this.value = value;
  }
  highlightString(matchString) {
    const { parsedValue } = this;
    if (this.params.cellRenderer || !exists(parsedValue)) {
      return;
    }
    let hasMatch = exists(matchString);
    if (hasMatch) {
      const index = parsedValue == null ? void 0 : parsedValue.toLocaleLowerCase().indexOf(matchString.toLocaleLowerCase());
      if (index >= 0) {
        const highlightEndIndex = index + matchString.length;
        const startPart = escapeString(parsedValue.slice(0, index), true);
        const highlightedPart = escapeString(parsedValue.slice(index, highlightEndIndex), true);
        const endPart = escapeString(parsedValue.slice(highlightEndIndex));
        this.renderValueWithoutRenderer(`${startPart}<span class="ag-rich-select-row-text-highlight">${highlightedPart}</span>${endPart}`);
      } else {
        hasMatch = false;
      }
    }
    if (!hasMatch) {
      this.renderValueWithoutRenderer(parsedValue);
    }
  }
  updateHighlighted(highlighted) {
    var _a;
    const eGui = this.getGui();
    const parentId = `ag-rich-select-row-${this.getCompId()}`;
    (_a = eGui.parentElement) == null ? void 0 : _a.setAttribute("id", parentId);
    if (highlighted) {
      const parentAriaEl = this.getParentComponent().getAriaElement();
      setAriaActiveDescendant(parentAriaEl, parentId);
      this.wrapperEl.setAttribute("data-active-option", parentId);
    }
    setAriaSelected(eGui.parentElement, highlighted);
    this.addOrRemoveCssClass("ag-rich-select-row-selected", highlighted);
  }
  populateWithoutRenderer(value, valueFormatted) {
    const eDocument = this.gos.getDocument();
    const eGui = this.getGui();
    const span = eDocument.createElement("span");
    span.style.overflow = "hidden";
    span.style.textOverflow = "ellipsis";
    const parsedValue = escapeString(exists(valueFormatted) ? valueFormatted : value, true);
    this.parsedValue = exists(parsedValue) ? parsedValue : null;
    eGui.appendChild(span);
    this.renderValueWithoutRenderer(parsedValue);
    this.setTooltip({
      newTooltipText: this.parsedValue,
      shouldDisplayTooltip: () => span.scrollWidth > span.clientWidth
    });
  }
  renderValueWithoutRenderer(value) {
    const span = this.getGui().querySelector("span");
    if (!span) {
      return;
    }
    span.innerHTML = exists(value) ? value : "&nbsp;";
  }
  populateWithRenderer(value, valueFormatted) {
    let cellRendererPromise;
    let userCompDetails;
    if (this.params.cellRenderer) {
      userCompDetails = this.userComponentFactory.getCellRendererDetails(this.params, {
        value,
        valueFormatted,
        setTooltip: (value2, shouldDisplayTooltip) => {
          this.setTooltip({ newTooltipText: value2, shouldDisplayTooltip });
        }
      });
    }
    if (userCompDetails) {
      cellRendererPromise = userCompDetails.newAgStackInstance();
    }
    if (cellRendererPromise) {
      bindCellRendererToHtmlElement(cellRendererPromise, this.getGui());
    }
    if (cellRendererPromise) {
      cellRendererPromise.then((childComponent) => {
        this.addDestroyFunc(() => {
          this.getContext().destroyBean(childComponent);
        });
      });
      return true;
    }
    return false;
  }
  onClick() {
    const parent = this.getParentComponent();
    const event = {
      type: Events.EVENT_FIELD_PICKER_VALUE_SELECTED,
      fromEnterKey: false,
      value: this.value
    };
    parent == null ? void 0 : parent.dispatchEvent(event);
  }
};
__decorateClass([
  Autowired("userComponentFactory")
], RichSelectRow.prototype, "userComponentFactory", 2);
__decorateClass([
  PostConstruct
], RichSelectRow.prototype, "postConstruct", 1);

// community-modules/core/src/widgets/virtualList.ts
var _VirtualList = class _VirtualList extends TabGuardComp {
  constructor(params) {
    super(_VirtualList.getTemplate((params == null ? void 0 : params.cssIdentifier) || "default"));
    this.renderedRows = /* @__PURE__ */ new Map();
    this.rowHeight = 20;
    this.pageSize = -1;
    this.isScrolling = false;
    this.isHeightFromTheme = true;
    const { cssIdentifier = "default", ariaRole = "listbox", listName } = params || {};
    this.cssIdentifier = cssIdentifier;
    this.ariaRole = ariaRole;
    this.listName = listName;
  }
  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.setAriaProperties();
    this.addManagedListener(this.eventService, Events.EVENT_GRID_STYLES_CHANGED, this.onGridStylesChanged.bind(this));
  }
  onGridStylesChanged() {
    this.rowHeight = this.getItemHeight();
    this.refresh();
  }
  setAriaProperties() {
    const translate = this.localeService.getLocaleTextFunc();
    const listName = translate("ariaDefaultListName", this.listName || "List");
    const ariaEl = this.eContainer;
    setAriaRole(ariaEl, this.ariaRole);
    setAriaLabel(ariaEl, listName);
  }
  addResizeObserver() {
    const listener = () => this.animationFrameService.requestAnimationFrame(() => this.drawVirtualRows());
    const destroyObserver = this.resizeObserverService.observeResize(this.getGui(), listener);
    this.addDestroyFunc(destroyObserver);
  }
  focusInnerElement(fromBottom) {
    this.focusRow(fromBottom ? this.model.getRowCount() - 1 : 0);
  }
  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) {
    switch (e.key) {
      case KeyCode.UP:
      case KeyCode.DOWN:
        if (this.navigate(e.key === KeyCode.UP)) {
          e.preventDefault();
        }
        break;
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_DOWN:
        if (this.navigateToPage(e.key) !== null) {
          e.preventDefault();
        }
        break;
    }
  }
  onTabKeyDown(e) {
    if (this.navigate(e.shiftKey)) {
      e.preventDefault();
    } else {
      stopPropagationForAgGrid(e);
      this.forceFocusOutOfContainer(e.shiftKey);
    }
  }
  navigate(up) {
    if (this.lastFocusedRowIndex == null) {
      return false;
    }
    const nextRow = this.lastFocusedRowIndex + (up ? -1 : 1);
    if (nextRow < 0 || nextRow >= this.model.getRowCount()) {
      return false;
    }
    this.focusRow(nextRow);
    return true;
  }
  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);
    this.animationFrameService.requestAnimationFrame(() => {
      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));
  }
  static getTemplate(cssIdentifier) {
    return (
      /* html */
      `<div class="ag-virtual-list-viewport ag-${cssIdentifier}-virtual-list-viewport" role="presentation">
                <div class="ag-virtual-list-container ag-${cssIdentifier}-virtual-list-container" ref="eContainer"></div>
            </div>`
    );
  }
  getItemHeight() {
    if (!this.isHeightFromTheme) {
      return this.rowHeight;
    }
    return this.environment.getListItemHeight();
  }
  /**
   * 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) {
      console.warn("AG Grid: invalid row index for ensureIndexVisible: " + index);
      return false;
    }
    const rowTopPixel = index * this.rowHeight;
    const rowBottomPixel = rowTopPixel + this.rowHeight;
    const eGui = this.getGui();
    const viewportTopPixel = eGui.scrollTop;
    const viewportHeight = eGui.offsetHeight;
    const viewportBottomPixel = viewportTopPixel + viewportHeight;
    const diff = scrollPartialIntoView ? 0 : this.rowHeight;
    const viewportScrolledPastRow = viewportTopPixel > rowTopPixel + diff;
    const viewportScrolledBeforeRow = viewportBottomPixel < rowBottomPixel - diff;
    if (viewportScrolledPastRow) {
      eGui.scrollTop = rowTopPixel;
      return true;
    }
    if (viewportScrolledBeforeRow) {
      const newScrollPosition = rowBottomPixel - viewportHeight;
      eGui.scrollTop = newScrollPosition;
      return true;
    }
    return false;
  }
  setComponentCreator(componentCreator) {
    this.componentCreator = componentCreator;
  }
  setComponentUpdater(componentUpdater) {
    this.componentUpdater = componentUpdater;
  }
  getRowHeight() {
    return this.rowHeight;
  }
  getScrollTop() {
    return this.getGui().scrollTop;
  }
  setRowHeight(rowHeight) {
    this.isHeightFromTheme = false;
    this.rowHeight = rowHeight;
    this.refresh();
  }
  refresh(softRefresh) {
    if (this.model == null || !this.isAlive()) {
      return;
    }
    const rowCount = this.model.getRowCount();
    this.eContainer.style.height = `${rowCount * this.rowHeight}px`;
    waitUntil(
      () => this.eContainer.clientHeight >= rowCount * this.rowHeight,
      () => {
        if (!this.isAlive()) {
          return;
        }
        if (this.canSoftRefresh(softRefresh)) {
          this.drawVirtualRows(true);
        } else {
          this.clearVirtualRows();
          this.drawVirtualRows();
        }
      }
    );
  }
  canSoftRefresh(softRefresh) {
    return !!(softRefresh && this.renderedRows.size && typeof this.model.areRowsEqual === "function" && this.componentUpdater);
  }
  clearVirtualRows() {
    this.renderedRows.forEach((_2, 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;
    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((_2, 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 eDiv = document.createElement("div");
    eDiv.classList.add("ag-virtual-list-item", `ag-${this.cssIdentifier}-virtual-list-item`);
    setAriaRole(eDiv, this.ariaRole === "tree" ? "treeitem" : "option");
    setAriaSetSize(eDiv, this.model.getRowCount());
    setAriaPosInSet(eDiv, rowIndex + 1);
    eDiv.setAttribute("tabindex", "-1");
    eDiv.style.height = `${this.rowHeight}px`;
    eDiv.style.top = `${this.rowHeight * rowIndex}px`;
    const rowComponent = this.componentCreator(value, eDiv);
    rowComponent.addGuiEventListener("focusin", () => this.lastFocusedRowIndex = rowIndex);
    eDiv.appendChild(rowComponent.getGui());
    if (this.renderedRows.has(rowIndex - 1)) {
      this.renderedRows.get(rowIndex - 1).eDiv.insertAdjacentElement("afterend", eDiv);
    } else if (this.renderedRows.has(rowIndex + 1)) {
      this.renderedRows.get(rowIndex + 1).eDiv.insertAdjacentElement("beforebegin", eDiv);
    } else {
      this.eContainer.appendChild(eDiv);
    }
    this.renderedRows.set(rowIndex, { rowComponent, eDiv, value });
  }
  removeRow(rowIndex) {
    const component = this.renderedRows.get(rowIndex);
    this.eContainer.removeChild(component.eDiv);
    this.destroyBean(component.rowComponent);
    this.renderedRows.delete(rowIndex);
  }
  refreshRows() {
    const rowCount = this.model.getRowCount();
    this.renderedRows.forEach((row, rowIndex) => {
      var _a, _b;
      if (rowIndex >= rowCount) {
        this.removeRow(rowIndex);
      } else {
        const newValue = this.model.getRow(rowIndex);
        if ((_b = (_a = this.model).areRowsEqual) == null ? void 0 : _b.call(_a, 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();
    super.destroy();
  }
};
__decorateClass([
  Autowired("resizeObserverService")
], _VirtualList.prototype, "resizeObserverService", 2);
__decorateClass([
  Autowired("animationFrameService")
], _VirtualList.prototype, "animationFrameService", 2);
__decorateClass([
  RefSelector("eContainer")
], _VirtualList.prototype, "eContainer", 2);
__decorateClass([
  PostConstruct
], _VirtualList.prototype, "postConstruct", 1);
var VirtualList = _VirtualList;

// community-modules/core/src/widgets/agRichSelect.ts
var TEMPLATE2 = (
  /* html */
  `
    <div class="ag-picker-field" role="presentation">
        <div ref="eLabel"></div>
            <div ref="eWrapper" class="ag-wrapper ag-picker-field-wrapper ag-rich-select-value ag-picker-collapsed">
            <div ref="eDisplayField" class="ag-picker-field-display"></div>
            <ag-input-text-field ref="eInput" class="ag-rich-select-field-input"></ag-input-text-field>
            <div ref="eIcon" class="ag-picker-field-icon" aria-hidden="true"></div>
        </div>
    </div>`
);
var AgRichSelect = class extends AgPickerField {
  constructor(config) {
    var _a, _b;
    super(__spreadProps(__spreadValues({
      pickerAriaLabelKey: "ariaLabelRichSelectField",
      pickerAriaLabelValue: "Rich Select Field",
      pickerType: "ag-list",
      className: "ag-rich-select",
      pickerIcon: "smallDown",
      ariaRole: "combobox",
      template: (_a = config == null ? void 0 : config.template) != null ? _a : TEMPLATE2,
      modalPicker: false
    }, config), {
      // maxPickerHeight needs to be set after expanding `config`
      maxPickerHeight: (_b = config == null ? void 0 : config.maxPickerHeight) != null ? _b : "calc(var(--ag-row-height) * 6.5)"
    }));
    this.searchString = "";
    this.highlightedItem = -1;
    this.lastRowHovered = -1;
    this.searchStringCreator = null;
    const { cellRowHeight, value, valueList, searchStringCreator } = config || {};
    if (cellRowHeight != null) {
      this.cellRowHeight = cellRowHeight;
    }
    if (value !== void 0) {
      this.value = value;
    }
    if (valueList != null) {
      this.values = valueList;
    }
    if (searchStringCreator) {
      this.searchStringCreator = searchStringCreator;
    }
  }
  postConstruct() {
    super.postConstruct();
    this.createLoadingElement();
    this.createListComponent();
    const { allowTyping, placeholder } = this.config;
    if (allowTyping) {
      this.eInput.setAutoComplete(false).setInputPlaceholder(placeholder);
      this.eDisplayField.classList.add("ag-hidden");
    } else {
      this.eInput.setDisplayed(false);
    }
    this.eWrapper.tabIndex = this.gos.get("tabIndex");
    const { searchDebounceDelay = 300 } = this.config;
    this.clearSearchString = debounce(this.clearSearchString, searchDebounceDelay);
    this.renderSelectedValue();
    if (allowTyping) {
      this.eInput.onValueChange((value) => this.searchTextFromString(value));
      this.addManagedListener(this.eWrapper, "focus", this.onWrapperFocus.bind(this));
    }
    this.addManagedListener(this.eWrapper, "focusout", this.onWrapperFocusOut.bind(this));
  }
  createLoadingElement() {
    const eDocument = this.gos.getDocument();
    const translate = this.localeService.getLocaleTextFunc();
    const el = eDocument.createElement("div");
    el.classList.add("ag-loading-text");
    el.innerText = translate("loadingOoo", "Loading...");
    this.eLoading = el;
  }
  createListComponent() {
    this.listComponent = this.createBean(new VirtualList({ cssIdentifier: "rich-select" }));
    this.listComponent.setComponentCreator(this.createRowComponent.bind(this));
    const componentUpdater = (item, component) => {
    };
    this.listComponent.setComponentUpdater(componentUpdater);
    this.listComponent.setParentComponent(this);
    this.addManagedListener(this.listComponent, Events.EVENT_FIELD_PICKER_VALUE_SELECTED, (e) => {
      this.onListValueSelected(e.value, e.fromEnterKey);
    });
    const { cellRowHeight } = this;
    if (cellRowHeight) {
      this.listComponent.setRowHeight(cellRowHeight);
    }
    const eListGui = this.listComponent.getGui();
    const eListAriaEl = this.listComponent.getAriaElement();
    this.addManagedListener(eListGui, "mousemove", this.onPickerMouseMove.bind(this));
    this.addManagedListener(eListGui, "mousedown", (e) => e.preventDefault());
    eListGui.classList.add("ag-rich-select-list");
    const listId = `ag-rich-select-list-${this.listComponent.getCompId()}`;
    eListAriaEl.setAttribute("id", listId);
    const translate = this.localeService.getLocaleTextFunc();
    const ariaLabel = translate(this.config.pickerAriaLabelKey, this.config.pickerAriaLabelValue);
    setAriaLabel(eListAriaEl, ariaLabel);
    setAriaControls(this.eWrapper, eListAriaEl);
  }
  renderSelectedValue() {
    const { value, eDisplayField, config } = this;
    const { allowTyping, initialInputValue } = this.config;
    const valueFormatted = this.config.valueFormatter ? this.config.valueFormatter(value) : value;
    if (allowTyping) {
      this.eInput.setValue(initialInputValue != null ? initialInputValue : valueFormatted);
      return;
    }
    let userCompDetails;
    if (config.cellRenderer) {
      userCompDetails = this.userComponentFactory.getCellRendererDetails(this.config, {
        value,
        valueFormatted
      });
    }
    let userCompDetailsPromise;
    if (userCompDetails) {
      userCompDetailsPromise = userCompDetails.newAgStackInstance();
    }
    if (userCompDetailsPromise) {
      clearElement(eDisplayField);
      bindCellRendererToHtmlElement(userCompDetailsPromise, eDisplayField);
      userCompDetailsPromise.then((renderer) => {
        this.addDestroyFunc(() => this.getContext().destroyBean(renderer));
      });
    } else {
      if (exists(this.value)) {
        eDisplayField.innerText = valueFormatted;
        eDisplayField.classList.remove("ag-display-as-placeholder");
      } else {
        const { placeholder } = config;
        if (exists(placeholder)) {
          eDisplayField.innerHTML = `${escapeString(placeholder)}`;
          eDisplayField.classList.add("ag-display-as-placeholder");
        } else {
          clearElement(eDisplayField);
        }
      }
      this.setTooltip({
        newTooltipText: valueFormatted != null ? valueFormatted : null,
        shouldDisplayTooltip: () => this.eDisplayField.scrollWidth > this.eDisplayField.clientWidth
      });
    }
  }
  getCurrentValueIndex() {
    const { currentList, value } = this;
    if (value == null || !currentList) {
      return -1;
    }
    for (let i = 0; i < currentList.length; i++) {
      if (currentList[i] === value) {
        return i;
      }
    }
    return -1;
  }
  highlightFilterMatch() {
    var _a;
    (_a = this.listComponent) == null ? void 0 : _a.forEachRenderedRow((cmp, idx) => {
      cmp.highlightString(this.searchString);
    });
  }
  highlightSelectedValue(index) {
    var _a;
    if (index == null) {
      index = this.getCurrentValueIndex();
    }
    this.highlightedItem = index;
    (_a = this.listComponent) == null ? void 0 : _a.forEachRenderedRow((cmp, idx) => {
      const highlighted = index === -1 ? false : this.highlightedItem === idx;
      cmp.updateHighlighted(highlighted);
    });
  }
  setRowHeight(height) {
    if (height !== this.cellRowHeight) {
      this.cellRowHeight = height;
    }
    if (this.listComponent) {
      this.listComponent.setRowHeight(height);
    }
  }
  createPickerComponent() {
    const { values: values2 } = this;
    if (values2) {
      this.setValueList({ valueList: values2 });
    }
    return this.listComponent;
  }
  setSearchStringCreator(searchStringFn) {
    this.searchStringCreator = searchStringFn;
  }
  setValueList(params) {
    const { valueList, refresh } = params;
    if (!this.listComponent) {
      return;
    }
    if (this.currentList === valueList) {
      return;
    }
    this.currentList = valueList;
    this.listComponent.setModel({
      getRowCount: () => valueList.length,
      getRow: (index) => valueList[index],
      areRowsEqual: (oldRow, newRow) => oldRow === newRow
    });
    if (refresh) {
      if (!this.values) {
        this.values = valueList;
        if (this.isPickerDisplayed) {
          this.showCurrentValueInPicker();
        }
      } else {
        this.listComponent.refresh(true);
      }
    }
  }
  showPicker() {
    super.showPicker();
    this.showCurrentValueInPicker();
    this.displayOrHidePicker();
  }
  showCurrentValueInPicker() {
    var _a, _b;
    if (!this.listComponent) {
      return;
    }
    if (!this.currentList) {
      if (this.isPickerDisplayed && this.eLoading) {
        this.listComponent.appendChild(this.eLoading);
      }
      return;
    }
    if ((_a = this.eLoading) == null ? void 0 : _a.offsetParent) {
      (_b = this.eLoading.parentElement) == null ? void 0 : _b.removeChild(this.eLoading);
    }
    const currentValueIndex = this.getCurrentValueIndex();
    if (currentValueIndex !== -1) {
      this.listComponent.refresh();
      this.listComponent.ensureIndexVisible(currentValueIndex);
      this.listComponent.refresh(true);
      this.highlightSelectedValue(currentValueIndex);
    } else {
      this.listComponent.refresh();
    }
  }
  beforeHidePicker() {
    this.highlightedItem = -1;
    super.beforeHidePicker();
  }
  onWrapperFocus() {
    if (!this.eInput) {
      return;
    }
    const focusableEl = this.eInput.getFocusableElement();
    focusableEl.focus();
    focusableEl.select();
  }
  onWrapperFocusOut(e) {
    if (!this.eWrapper.contains(e.relatedTarget)) {
      this.hidePicker();
    }
  }
  buildSearchStringFromKeyboardEvent(searchKey) {
    let { key } = searchKey;
    if (key === KeyCode.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();
  }
  buildSearchStrings(values2) {
    const { valueFormatter = (value) => value } = this.config;
    let searchStrings;
    if (typeof values2[0] === "number" || typeof values2[0] === "string") {
      searchStrings = values2.map((v) => valueFormatter(v));
    } else if (typeof values2[0] === "object" && this.searchStringCreator) {
      searchStrings = this.searchStringCreator(values2);
    }
    return searchStrings;
  }
  getSuggestionsAndFilteredValues(searchValue, valueList) {
    let suggestions = [];
    let filteredValues = [];
    if (!searchValue.length) {
      return { suggestions, filteredValues };
    }
    ;
    const { searchType = "fuzzy", filterList } = this.config;
    if (searchType === "fuzzy") {
      const fuzzySearchResult = fuzzySuggestions(this.searchString, valueList, true);
      suggestions = fuzzySearchResult.values;
      const indices = fuzzySearchResult.indices;
      if (filterList && indices.length) {
        for (let i = 0; i < indices.length; i++) {
          filteredValues.push(this.values[indices[i]]);
        }
      }
    } else {
      suggestions = valueList.filter((val, idx) => {
        const currentValue = val.toLocaleLowerCase();
        const valueToMatch = this.searchString.toLocaleLowerCase();
        const isMatch = searchType === "match" ? currentValue.startsWith(valueToMatch) : currentValue.indexOf(valueToMatch) !== -1;
        if (filterList && isMatch) {
          filteredValues.push(this.values[idx]);
        }
        return isMatch;
      });
    }
    return { suggestions, filteredValues };
  }
  filterListModel(filteredValues) {
    const { filterList } = this.config;
    if (!filterList) {
      return;
    }
    this.setValueList({ valueList: filteredValues, refresh: true });
    this.alignPickerToComponent();
  }
  runSearch() {
    var _a, _b;
    const { values: values2 } = this;
    const searchStrings = this.buildSearchStrings(values2);
    if (!searchStrings) {
      this.highlightSelectedValue(-1);
      return;
    }
    const { suggestions, filteredValues } = this.getSuggestionsAndFilteredValues(this.searchString, searchStrings);
    const { filterList, highlightMatch, searchType = "fuzzy" } = this.config;
    const filterValueLen = filteredValues.length;
    const shouldFilter = !!(filterList && this.searchString !== "");
    this.filterListModel(shouldFilter ? filteredValues : values2);
    if (suggestions.length) {
      const topSuggestionIndex = shouldFilter ? 0 : searchStrings.indexOf(suggestions[0]);
      this.selectListItem(topSuggestionIndex);
    } else {
      this.highlightSelectedValue(-1);
      if (!shouldFilter || filterValueLen) {
        (_a = this.listComponent) == null ? void 0 : _a.ensureIndexVisible(0);
      } else if (shouldFilter) {
        this.getAriaElement().removeAttribute("data-active-option");
        const eListAriaEl = (_b = this.listComponent) == null ? void 0 : _b.getAriaElement();
        if (eListAriaEl) {
          setAriaActiveDescendant(eListAriaEl, null);
        }
      }
    }
    if (highlightMatch && searchType !== "fuzzy") {
      this.highlightFilterMatch();
    }
    this.displayOrHidePicker();
  }
  displayOrHidePicker() {
    var _a;
    const eListGui = (_a = this.listComponent) == null ? void 0 : _a.getGui();
    const toggleValue = this.currentList ? this.currentList.length === 0 : false;
    eListGui == null ? void 0 : eListGui.classList.toggle("ag-hidden", toggleValue);
  }
  clearSearchString() {
    this.searchString = "";
  }
  selectListItem(index, preventUnnecessaryScroll) {
    if (!this.isPickerDisplayed || !this.currentList || !this.listComponent || index < 0 || index >= this.currentList.length) {
      return;
    }
    const wasScrolled = this.listComponent.ensureIndexVisible(index, !preventUnnecessaryScroll);
    if (wasScrolled && !preventUnnecessaryScroll) {
      this.listComponent.refresh(true);
    }
    this.highlightSelectedValue(index);
  }
  setValue(value, silent, fromPicker) {
    const index = this.currentList ? this.currentList.indexOf(value) : -1;
    if (index === -1) {
      return this;
    }
    this.value = value;
    if (!fromPicker) {
      this.selectListItem(index);
    }
    this.renderSelectedValue();
    return super.setValue(value, silent);
  }
  createRowComponent(value) {
    const row = new RichSelectRow(this.config, this.eWrapper);
    row.setParentComponent(this.listComponent);
    this.getContext().createBean(row);
    row.setState(value);
    const { highlightMatch, searchType = "fuzzy" } = this.config;
    if (highlightMatch && searchType !== "fuzzy") {
      row.highlightString(this.searchString);
    }
    return row;
  }
  getRowForMouseEvent(e) {
    const { listComponent } = this;
    if (!listComponent) {
      return -1;
    }
    const eGui = listComponent == null ? void 0 : listComponent.getGui();
    const rect = eGui.getBoundingClientRect();
    const scrollTop = listComponent.getScrollTop();
    const mouseY = e.clientY - rect.top + scrollTop;
    return Math.floor(mouseY / listComponent.getRowHeight());
  }
  onPickerMouseMove(e) {
    if (!this.listComponent) {
      return;
    }
    const row = this.getRowForMouseEvent(e);
    if (row !== -1 && row != this.lastRowHovered) {
      this.lastRowHovered = row;
      this.selectListItem(row, true);
    }
  }
  onNavigationKeyDown(event, key) {
    event.preventDefault();
    const isDown = key === KeyCode.DOWN;
    if (!this.isPickerDisplayed && isDown) {
      this.showPicker();
      return;
    }
    const oldIndex = this.highlightedItem;
    const diff = isDown ? 1 : -1;
    const newIndex = oldIndex === -1 ? 0 : oldIndex + diff;
    this.selectListItem(newIndex);
  }
  onPageNavigation(key) {
    var _a;
    if (!this.isPickerDisplayed) {
      return;
    }
    const newIndex = (_a = this.listComponent) == null ? void 0 : _a.navigateToPage(key, this.highlightedItem);
    if (newIndex != null) {
      this.animationFrameService.requestAnimationFrame(() => {
        if (!this.isAlive()) {
          return null;
        }
        this.highlightSelectedValue(newIndex);
      });
    }
  }
  onEnterKeyDown(e) {
    if (!this.isPickerDisplayed) {
      return;
    }
    e.preventDefault();
    if (this.currentList) {
      this.onListValueSelected(this.currentList[this.highlightedItem], true);
    }
  }
  onTabKeyDown() {
    if (!this.isPickerDisplayed || !this.currentList) {
      return;
    }
    this.setValue(this.currentList[this.highlightedItem], false, true);
  }
  onListValueSelected(value, fromEnterKey) {
    this.setValue(value, false, true);
    this.dispatchPickerEvent(value, fromEnterKey);
    this.hidePicker();
  }
  dispatchPickerEvent(value, fromEnterKey) {
    const event = {
      type: Events.EVENT_FIELD_PICKER_VALUE_SELECTED,
      fromEnterKey,
      value
    };
    this.dispatchEvent(event);
  }
  getFocusableElement() {
    const { allowTyping } = this.config;
    if (allowTyping) {
      return this.eInput.getFocusableElement();
    }
    return super.getFocusableElement();
  }
  onKeyDown(event) {
    const key = event.key;
    const { allowTyping } = this.config;
    switch (key) {
      case KeyCode.LEFT:
      case KeyCode.RIGHT:
        if (!allowTyping) {
          event.preventDefault();
        }
        break;
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        if (allowTyping) {
          event.preventDefault();
          const inputEl = this.eInput.getInputElement();
          const target = key === KeyCode.PAGE_HOME ? 0 : inputEl.value.length;
          inputEl.setSelectionRange(target, target);
          break;
        }
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_DOWN:
        event.preventDefault();
        this.onPageNavigation(key);
        break;
      case KeyCode.DOWN:
      case KeyCode.UP:
        this.onNavigationKeyDown(event, key);
        break;
      case KeyCode.ESCAPE:
        if (this.isPickerDisplayed) {
          if (isVisible(this.listComponent.getGui())) {
            event.preventDefault();
            stopPropagationForAgGrid(event);
          }
          this.hidePicker();
        }
        break;
      case KeyCode.ENTER:
        this.onEnterKeyDown(event);
        break;
      case KeyCode.TAB:
        this.onTabKeyDown();
        break;
      default:
        if (!allowTyping) {
          this.buildSearchStringFromKeyboardEvent(event);
        }
    }
  }
  destroy() {
    if (this.listComponent) {
      this.destroyBean(this.listComponent);
      this.listComponent = void 0;
    }
    this.eLoading = void 0;
    super.destroy();
  }
};
__decorateClass([
  Autowired("userComponentFactory")
], AgRichSelect.prototype, "userComponentFactory", 2);
__decorateClass([
  Autowired("animationFrameService")
], AgRichSelect.prototype, "animationFrameService", 2);
__decorateClass([
  RefSelector("eInput")
], AgRichSelect.prototype, "eInput", 2);

// community-modules/core/src/widgets/agSlider.ts
var _AgSlider = class _AgSlider extends AgAbstractLabel {
  constructor(config) {
    super(config, _AgSlider.TEMPLATE);
    this.labelAlignment = "top";
  }
  init() {
    this.eSlider.addCssClass("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) {
    const eventChanged = Events.EVENT_FIELD_VALUE_CHANGED;
    this.addManagedListener(this.eText, eventChanged, () => {
      const textValue = parseFloat(this.eText.getValue());
      this.eSlider.setValue(textValue.toString(), true);
      callbackFn(textValue || 0);
    });
    this.addManagedListener(this.eSlider, eventChanged, () => {
      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.dispatchEvent({ type: Events.EVENT_FIELD_VALUE_CHANGED });
    }
    return this;
  }
  setStep(step) {
    this.eSlider.setStep(step);
    this.eText.setStep(step);
    return this;
  }
};
_AgSlider.TEMPLATE = /* html */
`<div class="ag-slider">
            <label ref="eLabel"></label>
            <div class="ag-wrapper ag-slider-wrapper">
                <ag-input-range ref="eSlider"></ag-input-range>
                <ag-input-number-field ref="eText"></ag-input-number-field>
            </div>
        </div>`;
__decorateClass([
  RefSelector("eLabel")
], _AgSlider.prototype, "eLabel", 2);
__decorateClass([
  RefSelector("eSlider")
], _AgSlider.prototype, "eSlider", 2);
__decorateClass([
  RefSelector("eText")
], _AgSlider.prototype, "eText", 2);
__decorateClass([
  PostConstruct
], _AgSlider.prototype, "init", 1);
var AgSlider = _AgSlider;

// community-modules/core/src/widgets/agGroupComponent.ts
var _AgGroupComponent = class _AgGroupComponent extends Component {
  constructor(params = {}) {
    super(_AgGroupComponent.getTemplate(params));
    this.params = params;
    this.suppressEnabledCheckbox = true;
    this.suppressToggleExpandOnEnableChange = false;
    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 != null ? 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;
    }
  }
  static getTemplate(params) {
    const cssIdentifier = params.cssIdentifier || "default";
    const direction = params.direction || "vertical";
    return (
      /* html */
      `
            <div class="ag-group ag-${cssIdentifier}-group" role="presentation">
                <div ref="eToolbar" class="ag-group-toolbar ag-${cssIdentifier}-group-toolbar">
                    <ag-checkbox ref="cbGroupEnabled"></ag-checkbox>
                </div>
                <div ref="eContainer" class="ag-group-container ag-group-container-${direction} ag-${cssIdentifier}-group-container"></div>
            </div>
        `
    );
  }
  postConstruct() {
    this.setupTitleBar();
    if (this.items.length) {
      const initialItems = this.items;
      this.items = [];
      this.addItems(initialItems);
    }
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    this.cbGroupEnabled.setLabel(localeTextFunc("enabled", "Enabled"));
    if (this.enabled) {
      this.setEnabled(this.enabled, void 0, true);
    }
    this.setAlignItems(this.alignItems);
    const { onEnableChange, suppressOpenCloseIcons } = this.params;
    this.hideEnabledCheckbox(this.suppressEnabledCheckbox);
    this.hideOpenCloseIcons(suppressOpenCloseIcons != null ? suppressOpenCloseIcons : false);
    this.refreshChildDisplay();
    setDisplayed(this.eContainer, this.expanded);
    this.cbGroupEnabled.onValueChange((newSelection) => {
      this.setEnabled(newSelection, true, this.suppressToggleExpandOnEnableChange);
      this.dispatchEnableChangeEvent(newSelection);
    });
    if (onEnableChange != null) {
      this.onEnableChange(onEnableChange);
    }
  }
  refreshChildDisplay() {
    var _a;
    setDisplayed(this.eToolbar, this.expanded && !this.suppressEnabledCheckbox);
    (_a = this.eTitleBar) == null ? void 0 : _a.refreshOnExpand(this.expanded);
  }
  isExpanded() {
    return this.expanded;
  }
  setAlignItems(alignment) {
    if (this.alignItems !== alignment) {
      this.removeCssClass(`ag-group-item-alignment-${this.alignItems}`);
    }
    this.alignItems = alignment;
    const newCls = `ag-group-item-alignment-${this.alignItems}`;
    this.addCssClass(newCls);
    return this;
  }
  toggleGroupExpand(expanded) {
    var _a;
    let silent = false;
    if (((_a = this.eTitleBar) == null ? void 0 : _a.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();
    setDisplayed(this.eContainer, expanded);
    if (!silent) {
      this.dispatchEvent({ type: expanded ? _AgGroupComponent.EVENT_EXPANDED : _AgGroupComponent.EVENT_COLLAPSED });
    }
    return this;
  }
  addItems(items) {
    items.forEach((item) => this.addItem(item));
  }
  prependItem(item) {
    this.insertItem(item, true);
  }
  addItem(item) {
    this.insertItem(item, false);
  }
  insertItem(item, prepend) {
    const container = this.eContainer;
    const el = item instanceof Component ? item.getGui() : item;
    el.classList.add("ag-group-item", `ag-${this.cssIdentifier}-group-item`);
    if (prepend) {
      container.insertAdjacentElement("afterbegin", el);
      this.items.unshift(el);
    } else {
      container.appendChild(el);
      this.items.push(el);
    }
  }
  hideItem(hide, index) {
    const itemToHide = this.items[index];
    setDisplayed(itemToHide, !hide);
  }
  getItemIndex(item) {
    const el = item instanceof Component ? item.getGui() : item;
    return this.items.indexOf(el);
  }
  setTitle(title) {
    var _a;
    (_a = this.eTitleBar) == null ? void 0 : _a.setTitle(title);
    return this;
  }
  addTitleBarWidget(el) {
    var _a;
    (_a = this.eTitleBar) == null ? void 0 : _a.addWidget(el);
    return this;
  }
  addCssClassToTitleBar(cssClass) {
    var _a;
    (_a = this.eTitleBar) == null ? void 0 : _a.addCssClass(cssClass);
  }
  dispatchEnableChangeEvent(enabled) {
    const event = {
      type: _AgGroupComponent.EVENT_ENABLE_CHANGE,
      enabled
    };
    this.dispatchEvent(event);
  }
  setEnabled(enabled, skipToggle, skipExpand) {
    var _a;
    this.enabled = enabled;
    this.refreshDisabledStyles();
    if (!skipExpand) {
      this.toggleGroupExpand(enabled);
    }
    if (!skipToggle) {
      this.cbGroupEnabled.setValue(enabled);
      (_a = this.eToggle) == null ? void 0 : _a.setValue(enabled);
    }
    return this;
  }
  isEnabled() {
    return this.enabled;
  }
  onEnableChange(callbackFn) {
    this.addManagedListener(this, _AgGroupComponent.EVENT_ENABLE_CHANGE, (event) => callbackFn(event.enabled));
    return this;
  }
  hideEnabledCheckbox(hide) {
    this.suppressEnabledCheckbox = hide;
    this.refreshChildDisplay();
    this.refreshDisabledStyles();
    return this;
  }
  hideOpenCloseIcons(hide) {
    var _a;
    (_a = this.eTitleBar) == null ? void 0 : _a.hideOpenCloseIcons(hide);
    return this;
  }
  refreshDisabledStyles() {
    var _a;
    const disabled = !this.enabled;
    this.eContainer.classList.toggle("ag-disabled", disabled);
    (_a = this.eTitleBar) == null ? void 0 : _a.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.addManagedListener(titleBar, DefaultTitleBar.EVENT_EXPAND_CHANGED, (event) => this.toggleGroupExpand(event.expanded));
    return titleBar;
  }
  createToggleTitleBar() {
    var _a;
    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.addCssClass("ag-group-title-bar");
    eToggle.addCssClass(`ag-${(_a = this.params.cssIdentifier) != null ? _a : "default"}-group-title-bar ag-unselectable`);
    this.eToggle = eToggle;
    this.toggleGroupExpand(this.enabled);
    return eToggle;
  }
};
_AgGroupComponent.EVENT_EXPANDED = "expanded";
_AgGroupComponent.EVENT_COLLAPSED = "collapsed";
_AgGroupComponent.EVENT_ENABLE_CHANGE = "enableChange";
__decorateClass([
  RefSelector("eToolbar")
], _AgGroupComponent.prototype, "eToolbar", 2);
__decorateClass([
  RefSelector("cbGroupEnabled")
], _AgGroupComponent.prototype, "cbGroupEnabled", 2);
__decorateClass([
  RefSelector("eContainer")
], _AgGroupComponent.prototype, "eContainer", 2);
__decorateClass([
  PostConstruct
], _AgGroupComponent.prototype, "postConstruct", 1);
var AgGroupComponent = _AgGroupComponent;
var TITLE_BAR_DISABLED_CLASS = "ag-disabled-group-title-bar";
var _DefaultTitleBar = class _DefaultTitleBar extends Component {
  constructor(params = {}) {
    super(_DefaultTitleBar.getTemplate(params));
    this.suppressOpenCloseIcons = false;
    const { title, suppressOpenCloseIcons } = params;
    if (!!title && title.length > 0) {
      this.title = title;
    }
    if (suppressOpenCloseIcons != null) {
      this.suppressOpenCloseIcons = suppressOpenCloseIcons;
    }
  }
  static getTemplate(params) {
    var _a;
    const cssIdentifier = (_a = params.cssIdentifier) != null ? _a : "default";
    return (
      /* html */
      `
            <div class="ag-group-title-bar ag-${cssIdentifier}-group-title-bar ag-unselectable" role="button">
                <span class="ag-group-title-bar-icon ag-${cssIdentifier}-group-title-bar-icon" ref="eGroupOpenedIcon" role="presentation"></span>
                <span class="ag-group-title-bar-icon ag-${cssIdentifier}-group-title-bar-icon" ref="eGroupClosedIcon" role="presentation"></span>
                <span ref="eTitle" class="ag-group-title ag-${cssIdentifier}-group-title"></span>
            </div>
        `
    );
  }
  postConstruct() {
    this.setTitle(this.title);
    this.hideOpenCloseIcons(this.suppressOpenCloseIcons);
    this.setupExpandContract();
  }
  setupExpandContract() {
    this.eGroupClosedIcon.appendChild(createIcon("columnSelectClosed", this.gos, null));
    this.eGroupOpenedIcon.appendChild(createIcon("columnSelectOpen", this.gos, null));
    this.addManagedListener(this.getGui(), "click", () => this.dispatchExpandChanged());
    this.addManagedListener(this.getGui(), "keydown", (e) => {
      switch (e.key) {
        case KeyCode.ENTER:
        case KeyCode.SPACE:
          e.preventDefault();
          this.dispatchExpandChanged();
          break;
        case KeyCode.RIGHT:
        case KeyCode.LEFT:
          e.preventDefault();
          this.dispatchExpandChanged(e.key === KeyCode.RIGHT);
          break;
      }
    });
  }
  refreshOnExpand(expanded) {
    this.refreshAriaStatus(expanded);
    this.refreshOpenCloseIcons(expanded);
  }
  refreshAriaStatus(expanded) {
    if (!this.suppressOpenCloseIcons) {
      setAriaExpanded(this.getGui(), expanded);
    }
  }
  refreshOpenCloseIcons(expanded) {
    const showIcon = !this.suppressOpenCloseIcons;
    setDisplayed(this.eGroupOpenedIcon, showIcon && expanded);
    setDisplayed(this.eGroupClosedIcon, showIcon && !expanded);
  }
  isSuppressCollapse() {
    return this.suppressOpenCloseIcons;
  }
  dispatchExpandChanged(expanded) {
    const event = {
      type: _DefaultTitleBar.EVENT_EXPAND_CHANGED,
      expanded
    };
    this.dispatchEvent(event);
  }
  setTitle(title) {
    const eGui = this.getGui();
    const hasTitle = !!title && title.length > 0;
    title = hasTitle ? title : void 0;
    this.eTitle.textContent = title != null ? title : "";
    setDisplayed(eGui, hasTitle);
    if (title !== this.title) {
      this.title = title;
    }
    const disabled = eGui.classList.contains(TITLE_BAR_DISABLED_CLASS);
    this.refreshDisabledStyles(disabled);
    return this;
  }
  addWidget(el) {
    this.getGui().appendChild(el);
    return this;
  }
  hideOpenCloseIcons(hide) {
    this.suppressOpenCloseIcons = hide;
    if (hide) {
      this.dispatchExpandChanged(true);
    }
    return this;
  }
  refreshDisabledStyles(disabled) {
    const eGui = this.getGui();
    if (disabled) {
      eGui.classList.add(TITLE_BAR_DISABLED_CLASS);
      eGui.removeAttribute("tabindex");
    } else {
      eGui.classList.remove(TITLE_BAR_DISABLED_CLASS);
      if (typeof this.title === "string") {
        eGui.setAttribute("tabindex", "0");
      } else {
        eGui.removeAttribute("tabindex");
      }
    }
  }
};
_DefaultTitleBar.EVENT_EXPAND_CHANGED = "expandedChanged";
__decorateClass([
  RefSelector("eGroupOpenedIcon")
], _DefaultTitleBar.prototype, "eGroupOpenedIcon", 2);
__decorateClass([
  RefSelector("eGroupClosedIcon")
], _DefaultTitleBar.prototype, "eGroupClosedIcon", 2);
__decorateClass([
  RefSelector("eTitle")
], _DefaultTitleBar.prototype, "eTitle", 2);
__decorateClass([
  PostConstruct
], _DefaultTitleBar.prototype, "postConstruct", 1);
var DefaultTitleBar = _DefaultTitleBar;

// community-modules/core/src/widgets/agMenuList.ts
var AgMenuList = class extends TabGuardComp {
  constructor(level = 0, params) {
    super(
      /* html */
      `<div class="ag-menu-list" role="tree"></div>`
    );
    this.level = level;
    this.menuItems = [];
    this.params = params != null ? params : {
      column: null,
      node: null,
      value: null
    };
  }
  postConstruct() {
    this.initialiseTabGuard({
      onTabKeyDown: (e) => this.onTabKeyDown(e),
      handleKeyDown: (e) => this.handleKeyDown(e),
      onFocusIn: (e) => this.handleFocusIn(e),
      onFocusOut: (e) => this.handleFocusOut(e)
    });
  }
  onTabKeyDown(e) {
    const parent = this.getParentComponent();
    const parentGui = parent && parent.getGui();
    const isManaged = parentGui && parentGui.classList.contains("ag-focus-managed");
    if (!isManaged) {
      e.preventDefault();
    }
    if (e.shiftKey) {
      this.closeIfIsChild(e);
    }
  }
  handleKeyDown(e) {
    switch (e.key) {
      case KeyCode.UP:
      case KeyCode.RIGHT:
      case KeyCode.DOWN:
      case KeyCode.LEFT:
        e.preventDefault();
        this.handleNavKey(e.key);
        break;
      case KeyCode.ESCAPE:
        if (this.closeIfIsChild()) {
          stopPropagationForAgGrid(e);
        }
        break;
    }
  }
  handleFocusIn(e) {
    var _a, _b;
    const oldFocusedElement = e.relatedTarget;
    if (!this.tabGuardCtrl.isTabGuard(oldFocusedElement) && (this.getGui().contains(oldFocusedElement) || ((_b = (_a = this.activeMenuItem) == null ? void 0 : _a.getSubMenuGui()) == null ? void 0 : _b.contains(oldFocusedElement)))) {
      return;
    }
    if (this.activeMenuItem) {
      this.activeMenuItem.activate();
    } else {
      this.activateFirstItem();
    }
  }
  handleFocusOut(e) {
    var _a;
    const newFocusedElement = e.relatedTarget;
    if (!this.activeMenuItem || this.getGui().contains(newFocusedElement) || ((_a = this.activeMenuItem.getSubMenuGui()) == null ? void 0 : _a.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") {
        console.warn(`AG Grid: unrecognised menu item ${menuItemOrString}`);
        return AgPromise.resolve({ eGui: null });
      } else {
        return this.addItem(menuItemOrString);
      }
    })).then((elements) => {
      elements.forEach((element) => {
        if (element == null ? void 0 : element.eGui) {
          this.appendChild(element.eGui);
          if (element.comp) {
            this.menuItems.push(element.comp);
          }
        }
      });
    });
  }
  addItem(menuItemDef) {
    const menuItem = this.createManagedBean(new AgMenuItemComponent());
    return menuItem.init({
      menuItemDef,
      isAnotherSubMenuOpen: () => this.menuItems.some((m) => m.isSubMenuOpen()),
      level: this.level,
      contextParams: this.params
    }).then(() => {
      menuItem.setParentComponent(this);
      this.addManagedListener(menuItem, AgMenuItemComponent.EVENT_CLOSE_MENU, (event) => {
        this.dispatchEvent(event);
      });
      this.addManagedListener(menuItem, AgMenuItemComponent.EVENT_MENU_ITEM_ACTIVATED, (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 separatorHtml = (
      /* html */
      `
            <div class="ag-menu-separator" aria-hidden="true">
                <div class="ag-menu-separator-part"></div>
                <div class="ag-menu-separator-part"></div>
                <div class="ag-menu-separator-part"></div>
                <div class="ag-menu-separator-part"></div>
            </div>`
    );
    return loadTemplate(separatorHtml);
  }
  handleNavKey(key) {
    switch (key) {
      case KeyCode.UP:
      case KeyCode.DOWN:
        const nextItem = this.findNextItem(key === KeyCode.UP);
        if (nextItem && nextItem !== this.activeMenuItem) {
          nextItem.activate();
        }
        return;
    }
    const left = this.gos.get("enableRtl") ? KeyCode.RIGHT : KeyCode.LEFT;
    if (key === left) {
      this.closeIfIsChild();
    } else {
      this.openChild();
    }
  }
  closeIfIsChild(e) {
    const parentItem = this.getParentComponent();
    if (parentItem && parentItem instanceof AgMenuItemComponent) {
      if (e) {
        e.preventDefault();
      }
      parentItem.closeSubMenu();
      parentItem.getGui().focus();
      return true;
    }
    return false;
  }
  openChild() {
    if (this.activeMenuItem) {
      this.activeMenuItem.openSubMenu(true);
    }
  }
  findNextItem(up) {
    const items = this.menuItems.filter((item) => !item.isDisabled());
    if (!items.length) {
      return;
    }
    if (!this.activeMenuItem) {
      return up ? last(items) : items[0];
    }
    if (up) {
      items.reverse();
    }
    let nextItem;
    let foundCurrent = false;
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      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();
  }
};
__decorateClass([
  Autowired("focusService")
], AgMenuList.prototype, "focusService", 2);
__decorateClass([
  PostConstruct
], AgMenuList.prototype, "postConstruct", 1);

// community-modules/core/src/widgets/agMenuPanel.ts
var AgMenuPanel = class extends TabGuardComp {
  constructor(wrappedComponent) {
    super();
    this.wrappedComponent = wrappedComponent;
    this.setTemplateFromElement(wrappedComponent.getGui());
  }
  postConstruct() {
    this.initialiseTabGuard({
      onTabKeyDown: (e) => this.onTabKeyDown(e),
      handleKeyDown: (e) => this.handleKeyDown(e)
    });
  }
  handleKeyDown(e) {
    if (e.key === KeyCode.ESCAPE) {
      this.closePanel();
    }
  }
  onTabKeyDown(e) {
    if (e.defaultPrevented) {
      return;
    }
    this.closePanel();
    e.preventDefault();
  }
  closePanel() {
    const menuItem = this.parentComponent;
    menuItem.closeSubMenu();
    setTimeout(() => menuItem.getGui().focus(), 0);
  }
};
__decorateClass([
  PostConstruct
], AgMenuPanel.prototype, "postConstruct", 1);

// community-modules/core/src/widgets/agMenuItemComponent.ts
var _AgMenuItemComponent = class _AgMenuItemComponent extends BeanStub {
  constructor() {
    super(...arguments);
    this.isActive = false;
    this.subMenuIsOpen = false;
    this.subMenuIsOpening = false;
    this.suppressRootStyles = true;
    this.suppressAria = true;
    this.suppressFocus = true;
  }
  init(params) {
    var _a, _b;
    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 = (_b = (_a = this.params.menuItemParams) == null ? void 0 : _a.cssClassPrefix) != null ? _b : "ag-menu-option";
    const compDetails = this.userComponentFactory.getMenuItemCompDetails(this.params, __spreadProps(__spreadValues({}, menuItemDef), {
      level,
      isAnotherSubMenuOpen,
      openSubMenu: (activateFirstItem) => this.openSubMenu(activateFirstItem),
      closeSubMenu: () => this.closeSubMenu(),
      closeMenu: (event) => this.closeMenu(event),
      updateTooltip: (tooltip, shouldDisplayTooltip) => this.refreshTooltip(tooltip, shouldDisplayTooltip),
      onItemActivated: () => this.onItemActivated()
    }));
    return compDetails.newAgStackInstance().then((comp) => {
      var _a2;
      this.menuItemComp = comp;
      const configureDefaults = (_a2 = comp.configureDefaults) == null ? void 0 : _a2.call(comp);
      if (configureDefaults) {
        this.configureDefaults(configureDefaults === true ? void 0 : configureDefaults);
      }
    });
  }
  addListeners(eGui, params) {
    if (!(params == null ? void 0 : params.suppressClick)) {
      this.addManagedListener(eGui, "click", (e) => this.onItemSelected(e));
    }
    if (!(params == null ? void 0 : params.suppressKeyboardSelect)) {
      this.addManagedListener(eGui, "keydown", (e) => {
        if (e.key === KeyCode.ENTER || e.key === KeyCode.SPACE) {
          e.preventDefault();
          this.onItemSelected(e);
        }
      });
    }
    if (!(params == null ? void 0 : params.suppressMouseDown)) {
      this.addManagedListener(eGui, "mousedown", (e) => {
        e.stopPropagation();
        e.preventDefault();
      });
    }
    if (!(params == null ? void 0 : params.suppressMouseOver)) {
      this.addManagedListener(eGui, "mouseenter", () => this.onMouseEnter());
      this.addManagedListener(eGui, "mouseleave", () => this.onMouseLeave());
    }
  }
  isDisabled() {
    return !!this.params.disabled;
  }
  openSubMenu(activateFirstItem = false) {
    var _a, _b;
    this.closeSubMenu();
    if (!this.params.subMenu) {
      return;
    }
    this.subMenuIsOpening = true;
    const ePopup = loadTemplate(
      /* html */
      `<div class="ag-menu" role="presentation"></div>`
    );
    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);
      ePopup.appendChild(subMenuGui);
      if (this.childComponent.afterGuiAttached) {
        afterGuiAttached = () => {
          this.childComponent.afterGuiAttached();
          this.subMenuIsOpening = false;
        };
      }
    } else if (this.params.subMenu) {
      const childMenu = this.createBean(new AgMenuList(this.level + 1, this.contextParams));
      childMenu.setParentComponent(this);
      childMenu.addMenuItems(this.params.subMenu);
      ePopup.appendChild(childMenu.getGui());
      this.addManagedListener(childMenu, _AgMenuItemComponent.EVENT_CLOSE_MENU, (e) => this.dispatchEvent(e));
      childMenu.addGuiEventListener("mouseenter", () => this.cancelDeactivate());
      destroySubMenu = () => this.destroyBean(childMenu);
      if (activateFirstItem) {
        afterGuiAttached = () => {
          childMenu.activateFirstItem();
          this.subMenuIsOpening = false;
        };
      }
    }
    const positionCallback = this.popupService.positionPopupForMenu.bind(
      this.popupService,
      { eventSource: this.eGui, ePopup }
    );
    const translate = this.localeService.getLocaleTextFunc();
    const addPopupRes = this.popupService.addPopup({
      modal: true,
      eChild: ePopup,
      positionCallback,
      anchorToElement: this.eGui,
      ariaLabel: translate("ariaLabelSubMenu", "SubMenu"),
      afterGuiAttached
    });
    this.subMenuIsOpen = true;
    this.setAriaExpanded(true);
    this.hideSubMenu = () => {
      var _a2, _b2;
      if (addPopupRes) {
        addPopupRes.hideFunc();
      }
      this.subMenuIsOpen = false;
      this.setAriaExpanded(false);
      destroySubMenu();
      (_b2 = (_a2 = this.menuItemComp).setExpanded) == null ? void 0 : _b2.call(_a2, false);
      this.eSubMenuGui = void 0;
    };
    (_b = (_a = this.menuItemComp).setExpanded) == null ? void 0 : _b.call(_a, 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) {
    var _a, _b;
    this.cancelActivate();
    if (this.params.disabled) {
      return;
    }
    this.isActive = true;
    if (!this.suppressRootStyles) {
      this.eGui.classList.add(`${this.cssClassPrefix}-active`);
    }
    (_b = (_a = this.menuItemComp).setActive) == null ? void 0 : _b.call(_a, true);
    if (!this.suppressFocus) {
      this.eGui.focus({ preventScroll: true });
    }
    if (openSubMenu && this.params.subMenu) {
      window.setTimeout(() => {
        if (this.isAlive() && this.isActive) {
          this.openSubMenu();
        }
      }, 300);
    }
    this.onItemActivated();
  }
  deactivate() {
    var _a, _b;
    this.cancelDeactivate();
    if (!this.suppressRootStyles) {
      this.eGui.classList.remove(`${this.cssClassPrefix}-active`);
    }
    (_b = (_a = this.menuItemComp).setActive) == null ? void 0 : _b.call(_a, false);
    this.isActive = false;
    if (this.subMenuIsOpen) {
      this.hideSubMenu();
    }
  }
  getGui() {
    return this.menuItemComp.getGui();
  }
  getParentComponent() {
    return this.parentComponent;
  }
  setParentComponent(component) {
    this.parentComponent = component;
  }
  getSubMenuGui() {
    return this.eSubMenuGui;
  }
  onItemSelected(event) {
    var _a, _b;
    (_b = (_a = this.menuItemComp).select) == null ? void 0 : _b.call(_a);
    if (this.params.action) {
      this.getFrameworkOverrides().wrapOutgoing(() => this.params.action(this.gos.addGridCommonParams(__spreadValues({}, this.contextParams))));
    } else {
      this.openSubMenu(event && event.type === "keydown");
    }
    if (this.params.subMenu && !this.params.action || this.params.suppressCloseOnSelect) {
      return;
    }
    this.closeMenu(event);
  }
  closeMenu(event) {
    const e = {
      type: _AgMenuItemComponent.EVENT_CLOSE_MENU
    };
    if (event) {
      if (event instanceof MouseEvent) {
        e.mouseEvent = event;
      } else {
        e.keyboardEvent = event;
      }
    }
    this.dispatchEvent(e);
  }
  onItemActivated() {
    const event = {
      type: _AgMenuItemComponent.EVENT_MENU_ITEM_ACTIVATED,
      menuItem: this
    };
    this.dispatchEvent(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), _AgMenuItemComponent.ACTIVATION_DELAY);
    } else {
      this.activate(true);
    }
  }
  onMouseLeave() {
    this.cancelActivate();
    if (this.isSubMenuOpen()) {
      this.deactivateTimeoutId = window.setTimeout(() => this.deactivate(), _AgMenuItemComponent.ACTIVATION_DELAY);
    } else {
      this.deactivate();
    }
  }
  configureDefaults(params) {
    var _a, _b, _c;
    if (!this.menuItemComp) {
      setTimeout(() => this.configureDefaults(params));
      return;
    }
    let eGui = this.menuItemComp.getGui();
    const rootElement = (_b = (_a = this.menuItemComp).getRootElement) == null ? void 0 : _b.call(_a);
    if (rootElement) {
      if (!(params == null ? void 0 : params.suppressRootStyles)) {
        eGui.classList.add("ag-menu-option-custom");
      }
      eGui = rootElement;
    }
    this.eGui = eGui;
    this.suppressRootStyles = !!(params == null ? void 0 : params.suppressRootStyles);
    if (!this.suppressRootStyles) {
      eGui.classList.add(this.cssClassPrefix);
      (_c = this.params.cssClasses) == null ? void 0 : _c.forEach((it) => eGui.classList.add(it));
      if (this.params.disabled) {
        eGui.classList.add(`${this.cssClassPrefix}-disabled`);
      }
    }
    if (!(params == null ? void 0 : params.suppressTooltip)) {
      this.refreshTooltip(this.params.tooltip);
    }
    this.suppressAria = !!(params == null ? void 0 : params.suppressAria);
    if (!this.suppressAria) {
      setAriaRole(eGui, "treeitem");
      setAriaLevel(eGui, this.level + 1);
      if (this.params.disabled) {
        setAriaDisabled(eGui, true);
      }
    }
    if (!(params == null ? void 0 : params.suppressTabIndex)) {
      eGui.setAttribute("tabindex", "-1");
    }
    if (!this.params.disabled) {
      this.addListeners(eGui, params);
    }
    this.suppressFocus = !!(params == null ? void 0 : params.suppressFocus);
  }
  refreshTooltip(tooltip, shouldDisplayTooltip) {
    this.tooltip = tooltip;
    if (this.tooltipFeature) {
      this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    }
    if (!tooltip || !this.menuItemComp) {
      return;
    }
    this.tooltipFeature = this.createBean(new TooltipFeature({
      getGui: () => this.getGui(),
      getTooltipValue: () => this.tooltip,
      getLocation: () => "menu",
      shouldDisplayTooltip
    }));
  }
  destroy() {
    if (this.tooltipFeature) {
      this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    }
    super.destroy();
  }
};
_AgMenuItemComponent.EVENT_CLOSE_MENU = "closeMenu";
_AgMenuItemComponent.EVENT_MENU_ITEM_ACTIVATED = "menuItemActivated";
_AgMenuItemComponent.ACTIVATION_DELAY = 80;
__decorateClass([
  Autowired("popupService")
], _AgMenuItemComponent.prototype, "popupService", 2);
__decorateClass([
  Autowired("userComponentFactory")
], _AgMenuItemComponent.prototype, "userComponentFactory", 2);
var AgMenuItemComponent = _AgMenuItemComponent;

// community-modules/core/src/widgets/agPanel.ts
var _AgPanel = class _AgPanel extends Component {
  constructor(config) {
    super(_AgPanel.getTemplate(config));
    this.config = config;
    this.closable = true;
  }
  static getTemplate(config) {
    const cssIdentifier = config.cssIdentifier || "default";
    return (
      /* html */
      `<div class="ag-panel ag-${cssIdentifier}-panel" tabindex="-1">
            <div ref="eTitleBar" class="ag-panel-title-bar ag-${cssIdentifier}-panel-title-bar ag-unselectable">
                <span ref="eTitle" class="ag-panel-title-bar-title ag-${cssIdentifier}-panel-title-bar-title"></span>
                <div ref="eTitleBarButtons" class="ag-panel-title-bar-buttons ag-${cssIdentifier}-panel-title-bar-buttons"></div>
            </div>
            <div ref="eContentWrapper" class="ag-panel-content-wrapper ag-${cssIdentifier}-panel-content-wrapper"></div>
        </div>`
    );
  }
  postConstruct() {
    const {
      component,
      closable,
      hideTitleBar,
      title,
      minWidth = 250,
      width,
      minHeight = 250,
      height,
      centered,
      popup,
      x,
      y
    } = this.config;
    this.positionableFeature = new PositionableFeature(this.getGui(), {
      minWidth,
      width,
      minHeight,
      height,
      centered,
      x,
      y,
      popup,
      calculateTopBuffer: () => this.positionableFeature.getHeight() - this.getBodyHeight()
    });
    this.createManagedBean(this.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 {
      setDisplayed(this.eTitleBar, false);
    }
    this.addManagedListener(this.eTitleBar, "mousedown", (e) => {
      if (eGui.contains(e.relatedTarget) || eGui.contains(this.gos.getActiveDomElement()) || 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 && this.positionableFeature.isPositioned()) {
      return;
    }
    if (this.renderComponent) {
      this.renderComponent();
    }
    this.positionableFeature.initialisePosition();
    this.eContentWrapper.style.height = "0";
  }
  renderComponent() {
    const eGui = this.getGui();
    eGui.focus();
    this.close = () => {
      eGui.parentElement.removeChild(eGui);
      this.destroy();
    };
  }
  getHeight() {
    return this.positionableFeature.getHeight();
  }
  setHeight(height) {
    this.positionableFeature.setHeight(height);
  }
  getWidth() {
    return this.positionableFeature.getWidth();
  }
  setWidth(width) {
    this.positionableFeature.setWidth(width);
  }
  setClosable(closable) {
    if (closable !== this.closable) {
      this.closable = closable;
    }
    if (closable) {
      const closeButtonComp = this.closeButtonComp = new Component(_AgPanel.CLOSE_BTN_TEMPLATE);
      this.getContext().createBean(closeButtonComp);
      const eGui = closeButtonComp.getGui();
      const child = createIconNoSpan("close", this.gos);
      child.classList.add("ag-panel-title-bar-button-icon");
      eGui.appendChild(child);
      this.addTitleBarButton(closeButtonComp);
      closeButtonComp.addManagedListener(eGui, "click", this.onBtClose.bind(this));
    } else if (this.closeButtonComp) {
      const eGui = this.closeButtonComp.getGui();
      eGui.parentElement.removeChild(eGui);
      this.closeButtonComp = this.destroyBean(this.closeButtonComp);
    }
  }
  setBodyComponent(bodyComponent) {
    bodyComponent.setParentComponent(this);
    this.eContentWrapper.appendChild(bodyComponent.getGui());
  }
  addTitleBarButton(button, position) {
    const eTitleBarButtons = this.eTitleBarButtons;
    const buttons = eTitleBarButtons.children;
    const len = buttons.length;
    if (position == null) {
      position = len;
    }
    position = Math.max(0, Math.min(position, len));
    button.addCssClass("ag-panel-title-bar-button");
    const eGui = button.getGui();
    if (position === 0) {
      eTitleBarButtons.insertAdjacentElement("afterbegin", eGui);
    } else if (position === len) {
      eTitleBarButtons.insertAdjacentElement("beforeend", eGui);
    } else {
      buttons[position - 1].insertAdjacentElement("afterend", eGui);
    }
    button.setParentComponent(this);
  }
  getBodyHeight() {
    return 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();
  }
};
_AgPanel.CLOSE_BTN_TEMPLATE = /* html */
`<div class="ag-button"></div>`;
__decorateClass([
  RefSelector("eContentWrapper")
], _AgPanel.prototype, "eContentWrapper", 2);
__decorateClass([
  RefSelector("eTitleBar")
], _AgPanel.prototype, "eTitleBar", 2);
__decorateClass([
  RefSelector("eTitleBarButtons")
], _AgPanel.prototype, "eTitleBarButtons", 2);
__decorateClass([
  RefSelector("eTitle")
], _AgPanel.prototype, "eTitle", 2);
__decorateClass([
  PostConstruct
], _AgPanel.prototype, "postConstruct", 1);
var AgPanel = _AgPanel;

// community-modules/core/src/widgets/agDialog.ts
var AgDialog = class extends AgPanel {
  constructor(config) {
    super(__spreadProps(__spreadValues({}, config), { popup: true }));
    this.isMaximizable = false;
    this.isMaximized = false;
    this.maximizeListeners = [];
    this.resizeListenerDestroy = null;
    this.lastPosition = {
      x: 0,
      y: 0,
      width: 0,
      height: 0
    };
  }
  postConstruct() {
    const eGui = this.getGui();
    const { movable, resizable, maximizable } = this.config;
    this.addCssClass("ag-dialog");
    super.postConstruct();
    this.addManagedListener(eGui, "focusin", (e) => {
      this.popupService.bringPopupToFront(eGui);
    });
    if (movable) {
      this.setMovable(movable);
    }
    if (maximizable) {
      this.setMaximizable(maximizable);
    }
    if (resizable) {
      this.setResizable(resizable);
    }
  }
  renderComponent() {
    const eGui = this.getGui();
    const { alwaysOnTop, modal, title, afterGuiAttached } = this.config;
    const translate = this.localeService.getLocaleTextFunc();
    const addPopupRes = this.popupService.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) {
    var _a, _b;
    this.destroy();
    (_b = (_a = this.config).closedCallback) == null ? void 0 : _b.call(_a, event);
  }
  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() {
    setDisplayed(this.maximizeIcon, !this.isMaximized);
    setDisplayed(this.minimizeIcon, this.isMaximized);
  }
  clearMaximizebleListeners() {
    if (this.maximizeListeners.length) {
      this.maximizeListeners.forEach((destroyListener) => destroyListener());
      this.maximizeListeners.length = 0;
    }
    if (this.resizeListenerDestroy) {
      this.resizeListenerDestroy();
      this.resizeListenerDestroy = null;
    }
  }
  destroy() {
    this.maximizeButtonComp = this.destroyBean(this.maximizeButtonComp);
    this.clearMaximizebleListeners();
    super.destroy();
  }
  setResizable(resizable) {
    this.positionableFeature.setResizable(resizable);
  }
  setMovable(movable) {
    this.positionableFeature.setMovable(movable, this.eTitleBar);
  }
  setMaximizable(maximizable) {
    if (!maximizable) {
      this.clearMaximizebleListeners();
      if (this.maximizeButtonComp) {
        this.destroyBean(this.maximizeButtonComp);
        this.maximizeButtonComp = this.maximizeIcon = this.minimizeIcon = void 0;
      }
      return;
    }
    const eTitleBar = this.eTitleBar;
    if (!eTitleBar || maximizable === this.isMaximizable) {
      return;
    }
    const maximizeButtonComp = this.buildMaximizeAndMinimizeElements();
    this.refreshMaximizeIcon();
    maximizeButtonComp.addManagedListener(maximizeButtonComp.getGui(), "click", this.toggleMaximize.bind(this));
    this.addTitleBarButton(maximizeButtonComp, 0);
    this.maximizeListeners.push(
      this.addManagedListener(eTitleBar, "dblclick", this.toggleMaximize.bind(this))
    );
    this.resizeListenerDestroy = this.addManagedListener(this, "resize", () => {
      this.isMaximized = false;
      this.refreshMaximizeIcon();
    });
  }
  buildMaximizeAndMinimizeElements() {
    const maximizeButtonComp = this.maximizeButtonComp = this.createBean(new Component(
      /* html */
      `<div class="ag-dialog-button"></span>`
    ));
    const eGui = maximizeButtonComp.getGui();
    this.maximizeIcon = createIconNoSpan("maximize", this.gos);
    eGui.appendChild(this.maximizeIcon);
    this.maximizeIcon.classList.add("ag-panel-title-bar-button-icon");
    this.minimizeIcon = createIconNoSpan("minimize", this.gos);
    eGui.appendChild(this.minimizeIcon);
    this.minimizeIcon.classList.add("ag-panel-title-bar-button-icon");
    return maximizeButtonComp;
  }
};
__decorateClass([
  Autowired("popupService")
], AgDialog.prototype, "popupService", 2);

// community-modules/core/src/widgets/popupService.ts
var instanceIdSeq = 0;
var PopupService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.popupList = [];
  }
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      this.gridCtrl = p.gridCtrl;
    });
    this.addManagedListener(this.eventService, Events.EVENT_GRID_STYLES_CHANGED, this.handleThemeChange.bind(this));
  }
  getPopupParent() {
    const ePopupParent = this.gos.get("popupParent");
    if (ePopupParent) {
      return ePopupParent;
    }
    return this.gridCtrl.getGui();
  }
  positionPopupForMenu(params) {
    const { eventSource, ePopup } = params;
    const popupIdx = this.getPopupIndex(ePopup);
    if (popupIdx !== -1) {
      const popup = this.popupList[popupIdx];
      popup.alignedToElement = eventSource;
    }
    const sourceRect = eventSource.getBoundingClientRect();
    const parentRect = this.getParentRect();
    const y = this.keepXYWithinBounds(ePopup, sourceRect.top - parentRect.top, 0 /* vertical */);
    const minWidth = ePopup.clientWidth > 0 ? ePopup.clientWidth : 200;
    ePopup.style.minWidth = `${minWidth}px`;
    const widthOfParent = parentRect.right - parentRect.left;
    const maxX = widthOfParent - minWidth;
    let x;
    if (this.gos.get("enableRtl")) {
      x = xLeftPosition();
      if (x < 0) {
        x = xRightPosition();
        this.setAlignedStyles(ePopup, "left");
      }
      if (x > maxX) {
        x = 0;
        this.setAlignedStyles(ePopup, "right");
      }
    } else {
      x = xRightPosition();
      if (x > maxX) {
        x = xLeftPosition();
        this.setAlignedStyles(ePopup, "right");
      }
      if (x < 0) {
        x = 0;
        this.setAlignedStyles(ePopup, "left");
      }
    }
    ePopup.style.left = `${x}px`;
    ePopup.style.top = `${y}px`;
    function xRightPosition() {
      return sourceRect.right - parentRect.left - 2;
    }
    function xLeftPosition() {
      return sourceRect.left - parentRect.left - minWidth;
    }
  }
  positionPopupUnderMouseEvent(params) {
    const { ePopup, nudgeX, nudgeY, skipObserver } = params;
    this.positionPopup({
      ePopup,
      nudgeX,
      nudgeY,
      keepWithinBounds: true,
      skipObserver,
      updatePosition: () => this.calculatePointerAlign(params.mouseEvent),
      postProcessCallback: () => this.callPostProcessPopup(params.type, params.ePopup, null, params.mouseEvent, params.column, params.rowNode)
    });
  }
  calculatePointerAlign(e) {
    const parentRect = this.getParentRect();
    return {
      x: e.clientX - parentRect.left,
      y: e.clientY - parentRect.top
    };
  }
  positionPopupByComponent(params) {
    const { ePopup, nudgeX, nudgeY, keepWithinBounds, eventSource, alignSide = "left", position = "over", column, rowNode, type } = params;
    const sourceRect = eventSource.getBoundingClientRect();
    const parentRect = this.getParentRect();
    const popupIdx = this.getPopupIndex(ePopup);
    if (popupIdx !== -1) {
      const popup = this.popupList[popupIdx];
      popup.alignedToElement = eventSource;
    }
    const updatePosition = () => {
      let x = sourceRect.left - parentRect.left;
      if (alignSide === "right") {
        x -= ePopup.offsetWidth - sourceRect.width;
      }
      let y;
      if (position === "over") {
        y = sourceRect.top - parentRect.top;
        this.setAlignedStyles(ePopup, "over");
      } else {
        this.setAlignedStyles(ePopup, "under");
        const alignSide2 = this.shouldRenderUnderOrAbove(ePopup, sourceRect, parentRect, params.nudgeY || 0);
        if (alignSide2 === "under") {
          y = sourceRect.top - parentRect.top + sourceRect.height;
        } else {
          y = sourceRect.top - ePopup.offsetHeight - (nudgeY || 0) * 2 - parentRect.top;
        }
      }
      return { x, y };
    };
    this.positionPopup({
      ePopup,
      nudgeX,
      nudgeY,
      keepWithinBounds,
      updatePosition,
      postProcessCallback: () => this.callPostProcessPopup(type, ePopup, eventSource, null, column, rowNode)
    });
  }
  shouldRenderUnderOrAbove(ePopup, targetCompRect, parentRect, nudgeY) {
    const spaceAvailableUnder = parentRect.bottom - targetCompRect.bottom;
    const spaceAvailableAbove = targetCompRect.top - parentRect.top;
    const spaceRequired = ePopup.offsetHeight + nudgeY;
    if (spaceAvailableUnder > spaceRequired) {
      return "under";
    }
    if (spaceAvailableAbove > spaceRequired || spaceAvailableAbove > spaceAvailableUnder) {
      return "above";
    }
    return "under";
  }
  setAlignedStyles(ePopup, positioned) {
    const popupIdx = this.getPopupIndex(ePopup);
    if (popupIdx === -1) {
      return;
    }
    const popup = this.popupList[popupIdx];
    const { alignedToElement } = popup;
    if (!alignedToElement) {
      return;
    }
    const positions = ["right", "left", "over", "above", "under"];
    positions.forEach((position) => {
      alignedToElement.classList.remove(`ag-has-popup-positioned-${position}`);
      ePopup.classList.remove(`ag-popup-positioned-${position}`);
    });
    if (!positioned) {
      return;
    }
    alignedToElement.classList.add(`ag-has-popup-positioned-${positioned}`);
    ePopup.classList.add(`ag-popup-positioned-${positioned}`);
  }
  callPostProcessPopup(type, ePopup, eventSource, mouseEvent, column, rowNode) {
    const callback = this.gos.getCallback("postProcessPopup");
    if (callback) {
      const params = {
        column,
        rowNode,
        ePopup,
        type,
        eventSource,
        mouseEvent
      };
      callback(params);
    }
  }
  positionPopup(params) {
    const { ePopup, keepWithinBounds, nudgeX, nudgeY, skipObserver, updatePosition } = params;
    const lastSize = { width: 0, height: 0 };
    const updatePopupPosition = (fromResizeObserver = false) => {
      let { x, y } = updatePosition();
      if (fromResizeObserver && ePopup.clientWidth === lastSize.width && ePopup.clientHeight === lastSize.height) {
        return;
      }
      lastSize.width = ePopup.clientWidth;
      lastSize.height = ePopup.clientHeight;
      if (nudgeX) {
        x += nudgeX;
      }
      if (nudgeY) {
        y += nudgeY;
      }
      if (keepWithinBounds) {
        x = this.keepXYWithinBounds(ePopup, x, 1 /* horizontal */);
        y = this.keepXYWithinBounds(ePopup, y, 0 /* vertical */);
      }
      ePopup.style.left = `${x}px`;
      ePopup.style.top = `${y}px`;
      if (params.postProcessCallback) {
        params.postProcessCallback();
      }
    };
    updatePopupPosition();
    if (!skipObserver) {
      const resizeObserverDestroyFunc = this.resizeObserverService.observeResize(ePopup, () => updatePopupPosition(true));
      setTimeout(() => resizeObserverDestroyFunc(), PopupService.WAIT_FOR_POPUP_CONTENT_RESIZE);
    }
  }
  getActivePopups() {
    return this.popupList.map((popup) => popup.element);
  }
  getPopupList() {
    return this.popupList;
  }
  getParentRect() {
    const eDocument = this.gos.getDocument();
    let popupParent = this.getPopupParent();
    if (popupParent === eDocument.body) {
      popupParent = eDocument.documentElement;
    } else if (getComputedStyle(popupParent).position === "static") {
      popupParent = popupParent.offsetParent;
    }
    return getElementRectWithOffset(popupParent);
  }
  keepXYWithinBounds(ePopup, position, direction) {
    const isVertical = direction === 0 /* vertical */;
    const sizeProperty = isVertical ? "clientHeight" : "clientWidth";
    const anchorProperty = isVertical ? "top" : "left";
    const offsetProperty = isVertical ? "offsetHeight" : "offsetWidth";
    const scrollPositionProperty = isVertical ? "scrollTop" : "scrollLeft";
    const eDocument = this.gos.getDocument();
    const docElement = eDocument.documentElement;
    const popupParent = this.getPopupParent();
    const parentRect = popupParent.getBoundingClientRect();
    const documentRect = eDocument.documentElement.getBoundingClientRect();
    const isBody = popupParent === eDocument.body;
    const offsetSize = ePopup[offsetProperty];
    const getSize = isVertical ? getAbsoluteHeight : getAbsoluteWidth;
    let sizeOfParent = isBody ? getSize(docElement) + docElement[scrollPositionProperty] : popupParent[sizeProperty];
    if (isBody) {
      sizeOfParent -= Math.abs(documentRect[anchorProperty] - parentRect[anchorProperty]);
    }
    const max = sizeOfParent - offsetSize;
    return Math.min(Math.max(position, 0), Math.abs(max));
  }
  addPopup(params) {
    const eDocument = this.gos.getDocument();
    const { eChild, ariaLabel, alwaysOnTop, positionCallback, anchorToElement } = params;
    if (!eDocument) {
      console.warn("AG Grid: could not find the document, document is empty");
      return { hideFunc: () => {
      } };
    }
    const pos = this.getPopupIndex(eChild);
    if (pos !== -1) {
      const popup = this.popupList[pos];
      return { hideFunc: popup.hideFunc };
    }
    this.initialisePopupPosition(eChild);
    const wrapperEl = this.createPopupWrapper(eChild, ariaLabel, !!alwaysOnTop);
    const removeListeners = this.addEventListenersToPopup(__spreadProps(__spreadValues({}, params), { wrapperEl }));
    if (positionCallback) {
      positionCallback();
    }
    this.addPopupToPopupList(eChild, wrapperEl, removeListeners, anchorToElement);
    return {
      hideFunc: removeListeners
    };
  }
  initialisePopupPosition(element) {
    const ePopupParent = this.getPopupParent();
    const ePopupParentRect = ePopupParent.getBoundingClientRect();
    if (!exists(element.style.top)) {
      element.style.top = `${ePopupParentRect.top * -1}px`;
    }
    if (!exists(element.style.left)) {
      element.style.left = `${ePopupParentRect.left * -1}px`;
    }
  }
  createPopupWrapper(element, ariaLabel, alwaysOnTop) {
    const ePopupParent = this.getPopupParent();
    const eWrapper = document.createElement("div");
    const { allThemes } = this.environment.getTheme();
    if (allThemes.length) {
      eWrapper.classList.add(...allThemes);
    }
    eWrapper.classList.add("ag-popup");
    element.classList.add(
      this.gos.get("enableRtl") ? "ag-rtl" : "ag-ltr",
      "ag-popup-child"
    );
    if (!element.hasAttribute("role")) {
      setAriaRole(element, "dialog");
    }
    setAriaLabel(element, ariaLabel);
    eWrapper.appendChild(element);
    ePopupParent.appendChild(eWrapper);
    if (alwaysOnTop) {
      this.setAlwaysOnTop(element, true);
    } else {
      this.bringPopupToFront(element);
    }
    return eWrapper;
  }
  handleThemeChange() {
    const { allThemes } = this.environment.getTheme();
    for (const popup of this.popupList) {
      for (const className of Array.from(popup.wrapper.classList)) {
        if (className.startsWith("ag-theme-")) {
          popup.wrapper.classList.remove(className);
        }
      }
      if (allThemes.length) {
        popup.wrapper.classList.add(...allThemes);
      }
    }
  }
  addEventListenersToPopup(params) {
    const eDocument = this.gos.getDocument();
    const ePopupParent = this.getPopupParent();
    const { wrapperEl, eChild: popupEl, closedCallback, afterGuiAttached, closeOnEsc, modal } = params;
    let popupHidden = false;
    const hidePopupOnKeyboardEvent = (event) => {
      if (!wrapperEl.contains(this.gos.getActiveDomElement())) {
        return;
      }
      const key = event.key;
      if (key === KeyCode.ESCAPE && !isStopPropagationForAgGrid(event)) {
        removeListeners({ keyboardEvent: event });
      }
    };
    const hidePopupOnMouseEvent = (event) => removeListeners({ mouseEvent: event });
    const hidePopupOnTouchEvent = (event) => removeListeners({ touchEvent: event });
    const removeListeners = (popupParams = {}) => {
      const { mouseEvent, touchEvent, keyboardEvent, forceHide } = popupParams;
      if (!forceHide && // we don't hide popup if the event was on the child, or any
      // children of this child
      (this.isEventFromCurrentPopup({ mouseEvent, touchEvent }, popupEl) || // this method should only be called once. the client can have different
      // paths, each one wanting to close, so this method may be called multiple times.
      popupHidden)) {
        return;
      }
      popupHidden = true;
      ePopupParent.removeChild(wrapperEl);
      eDocument.removeEventListener("keydown", hidePopupOnKeyboardEvent);
      eDocument.removeEventListener("mousedown", hidePopupOnMouseEvent);
      eDocument.removeEventListener("touchstart", hidePopupOnTouchEvent);
      eDocument.removeEventListener("contextmenu", hidePopupOnMouseEvent);
      this.eventService.removeEventListener(Events.EVENT_DRAG_STARTED, hidePopupOnMouseEvent);
      if (closedCallback) {
        closedCallback(mouseEvent || touchEvent || keyboardEvent);
      }
      this.removePopupFromPopupList(popupEl);
    };
    if (afterGuiAttached) {
      afterGuiAttached({ hidePopup: removeListeners });
    }
    window.setTimeout(() => {
      if (closeOnEsc) {
        eDocument.addEventListener("keydown", hidePopupOnKeyboardEvent);
      }
      if (modal) {
        eDocument.addEventListener("mousedown", hidePopupOnMouseEvent);
        this.eventService.addEventListener(Events.EVENT_DRAG_STARTED, hidePopupOnMouseEvent);
        eDocument.addEventListener("touchstart", hidePopupOnTouchEvent);
        eDocument.addEventListener("contextmenu", hidePopupOnMouseEvent);
      }
    }, 0);
    return removeListeners;
  }
  addPopupToPopupList(element, wrapperEl, removeListeners, anchorToElement) {
    this.popupList.push({
      element,
      wrapper: wrapperEl,
      hideFunc: removeListeners,
      instanceId: instanceIdSeq++,
      isAnchored: !!anchorToElement
    });
    if (anchorToElement) {
      this.setPopupPositionRelatedToElement(element, anchorToElement);
    }
  }
  getPopupIndex(el) {
    return this.popupList.findIndex((p) => p.element === el);
  }
  setPopupPositionRelatedToElement(popupEl, relativeElement) {
    const popupIndex = this.getPopupIndex(popupEl);
    if (popupIndex === -1) {
      return;
    }
    const popup = this.popupList[popupIndex];
    if (popup.stopAnchoringPromise) {
      popup.stopAnchoringPromise.then((destroyFunc) => destroyFunc && destroyFunc());
    }
    popup.stopAnchoringPromise = void 0;
    popup.isAnchored = false;
    if (!relativeElement) {
      return;
    }
    const destroyPositionTracker = this.keepPopupPositionedRelativeTo({
      element: relativeElement,
      ePopup: popupEl,
      hidePopup: popup.hideFunc
    });
    popup.stopAnchoringPromise = destroyPositionTracker;
    popup.isAnchored = true;
    return destroyPositionTracker;
  }
  removePopupFromPopupList(element) {
    this.setAlignedStyles(element, null);
    this.setPopupPositionRelatedToElement(element, null);
    this.popupList = this.popupList.filter((p) => p.element !== element);
  }
  keepPopupPositionedRelativeTo(params) {
    const eParent = this.getPopupParent();
    const parentRect = eParent.getBoundingClientRect();
    const { element, ePopup } = params;
    const sourceRect = element.getBoundingClientRect();
    const initialDiffTop = parentRect.top - sourceRect.top;
    const initialDiffLeft = parentRect.left - sourceRect.left;
    let lastDiffTop = initialDiffTop;
    let lastDiffLeft = initialDiffLeft;
    const topPx = ePopup.style.top;
    const top = parseInt(topPx.substring(0, topPx.length - 1), 10);
    const leftPx = ePopup.style.left;
    const left = parseInt(leftPx.substring(0, leftPx.length - 1), 10);
    return new AgPromise((resolve) => {
      this.getFrameworkOverrides().setInterval(() => {
        const pRect = eParent.getBoundingClientRect();
        const sRect = element.getBoundingClientRect();
        const elementNotInDom = sRect.top == 0 && sRect.left == 0 && sRect.height == 0 && sRect.width == 0;
        if (elementNotInDom) {
          params.hidePopup();
          return;
        }
        const currentDiffTop = pRect.top - sRect.top;
        if (currentDiffTop != lastDiffTop) {
          const newTop = this.keepXYWithinBounds(ePopup, top + initialDiffTop - currentDiffTop, 0 /* vertical */);
          ePopup.style.top = `${newTop}px`;
        }
        lastDiffTop = currentDiffTop;
        const currentDiffLeft = pRect.left - sRect.left;
        if (currentDiffLeft != lastDiffLeft) {
          const newLeft = this.keepXYWithinBounds(ePopup, left + initialDiffLeft - currentDiffLeft, 1 /* horizontal */);
          ePopup.style.left = `${newLeft}px`;
        }
        lastDiffLeft = currentDiffLeft;
      }, 200).then((intervalId) => {
        const result = () => {
          if (intervalId != null) {
            window.clearInterval(intervalId);
          }
        };
        resolve(result);
      });
    });
  }
  hasAnchoredPopup() {
    return this.popupList.some((popup) => popup.isAnchored);
  }
  isEventFromCurrentPopup(params, target) {
    const { mouseEvent, touchEvent } = params;
    const event = mouseEvent ? mouseEvent : touchEvent;
    if (!event) {
      return false;
    }
    const indexOfThisChild = this.getPopupIndex(target);
    if (indexOfThisChild === -1) {
      return false;
    }
    for (let i = indexOfThisChild; i < this.popupList.length; i++) {
      const popup = this.popupList[i];
      if (isElementInEventPath(popup.element, event)) {
        return true;
      }
    }
    return this.isElementWithinCustomPopup(event.target);
  }
  isElementWithinCustomPopup(el) {
    const eDocument = this.gos.getDocument();
    while (el && el !== eDocument.body) {
      if (el.classList.contains("ag-custom-component-popup") || el.parentElement === null) {
        return true;
      }
      el = el.parentElement;
    }
    return false;
  }
  getWrapper(ePopup) {
    while (!ePopup.classList.contains("ag-popup") && ePopup.parentElement) {
      ePopup = ePopup.parentElement;
    }
    return ePopup.classList.contains("ag-popup") ? ePopup : null;
  }
  setAlwaysOnTop(ePopup, alwaysOnTop) {
    const eWrapper = this.getWrapper(ePopup);
    if (!eWrapper) {
      return;
    }
    eWrapper.classList.toggle("ag-always-on-top", !!alwaysOnTop);
    if (alwaysOnTop) {
      this.bringPopupToFront(eWrapper);
    }
  }
  bringPopupToFront(ePopup) {
    const parent = this.getPopupParent();
    const popupList = Array.prototype.slice.call(parent.querySelectorAll(".ag-popup"));
    const popupLen = popupList.length;
    const alwaysOnTopList = Array.prototype.slice.call(parent.querySelectorAll(".ag-popup.ag-always-on-top"));
    const onTopLength = alwaysOnTopList.length;
    const eWrapper = this.getWrapper(ePopup);
    if (!eWrapper || popupLen <= 1 || !parent.contains(ePopup)) {
      return;
    }
    const pos = popupList.indexOf(eWrapper);
    const innerEls = eWrapper.querySelectorAll("div");
    const innerElsScrollMap = [];
    innerEls.forEach((el) => {
      if (el.scrollTop !== 0) {
        innerElsScrollMap.push([el, el.scrollTop]);
      }
    });
    if (onTopLength) {
      const isPopupAlwaysOnTop = eWrapper.classList.contains("ag-always-on-top");
      if (isPopupAlwaysOnTop) {
        if (pos !== popupLen - 1) {
          last(alwaysOnTopList).insertAdjacentElement("afterend", eWrapper);
        }
      } else if (pos !== popupLen - onTopLength - 1) {
        alwaysOnTopList[0].insertAdjacentElement("beforebegin", eWrapper);
      }
    } else if (pos !== popupLen - 1) {
      last(popupList).insertAdjacentElement("afterend", eWrapper);
    }
    while (innerElsScrollMap.length) {
      const currentEl = innerElsScrollMap.pop();
      currentEl[0].scrollTop = currentEl[1];
    }
  }
};
PopupService.WAIT_FOR_POPUP_CONTENT_RESIZE = 200;
__decorateClass([
  Autowired("focusService")
], PopupService.prototype, "focusService", 2);
__decorateClass([
  Autowired("ctrlsService")
], PopupService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("resizeObserverService")
], PopupService.prototype, "resizeObserverService", 2);
__decorateClass([
  PostConstruct
], PopupService.prototype, "postConstruct", 1);
PopupService = __decorateClass([
  Bean("popupService")
], PopupService);

// community-modules/core/src/widgets/agAutocompleteRow.ts
var AgAutocompleteRow = class extends Component {
  constructor() {
    super(
      /* html */
      `
        <div class="ag-autocomplete-row" role="presentation">
            <div class="ag-autocomplete-row-label"></div>
        </div>`
    );
    this.hasHighlighting = false;
  }
  setState(value, selected) {
    this.value = value;
    this.render();
    this.updateSelected(selected);
  }
  updateSelected(selected) {
    this.addOrRemoveCssClass("ag-autocomplete-row-selected", selected);
  }
  setSearchString(searchString) {
    var _a;
    let keepHighlighting = false;
    if (exists(searchString)) {
      const index = (_a = this.value) == null ? void 0 : _a.toLocaleLowerCase().indexOf(searchString.toLocaleLowerCase());
      if (index >= 0) {
        keepHighlighting = true;
        this.hasHighlighting = true;
        const highlightEndIndex = index + searchString.length;
        const startPart = escapeString(this.value.slice(0, index));
        const highlightedPart = escapeString(this.value.slice(index, highlightEndIndex));
        const endPart = escapeString(this.value.slice(highlightEndIndex));
        this.getGui().lastElementChild.innerHTML = `${startPart}<b>${highlightedPart}</b>${endPart}`;
      }
    }
    if (!keepHighlighting && this.hasHighlighting) {
      this.hasHighlighting = false;
      this.render();
    }
  }
  render() {
    var _a;
    this.getGui().lastElementChild.innerHTML = (_a = escapeString(this.value)) != null ? _a : "&nbsp;";
  }
};

// community-modules/core/src/widgets/agAutocompleteList.ts
var _AgAutocompleteList = class _AgAutocompleteList extends PopupComponent {
  constructor(params) {
    super(_AgAutocompleteList.TEMPLATE);
    this.params = params;
    this.searchString = "";
  }
  destroy() {
    super.destroy();
  }
  init() {
    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.addManagedListener(virtualListGui, "click", () => this.params.onConfirmed());
    this.addManagedListener(virtualListGui, "mousemove", this.onMouseMove.bind(this));
    this.addManagedListener(virtualListGui, "mousedown", (e) => e.preventDefault());
    this.setSelectedValue(0);
  }
  onNavigationKeyDown(event, key) {
    event.preventDefault();
    const oldIndex = this.autocompleteEntries.indexOf(this.selectedValue);
    const newIndex = key === KeyCode.UP ? oldIndex - 1 : oldIndex + 1;
    this.checkSetSelectedValue(newIndex);
  }
  setSearch(searchString) {
    this.searchString = searchString;
    if (exists(searchString)) {
      this.runSearch();
    } else {
      this.autocompleteEntries = this.params.autocompleteEntries;
      this.virtualList.refresh();
      this.checkSetSelectedValue(0);
    }
    this.updateSearchInList();
  }
  runContainsSearch(searchString, searchStrings) {
    let topMatch;
    let topMatchStartsWithSearchString = false;
    const lowerCaseSearchString = searchString.toLocaleLowerCase();
    const allMatches = searchStrings.filter((string) => {
      const lowerCaseString = string.toLocaleLowerCase();
      const index = lowerCaseString.indexOf(lowerCaseSearchString);
      const startsWithSearchString = index === 0;
      const isMatch = index >= 0;
      if (isMatch && (!topMatch || !topMatchStartsWithSearchString && startsWithSearchString || topMatchStartsWithSearchString === startsWithSearchString && string.length < topMatch.length)) {
        topMatch = string;
        topMatchStartsWithSearchString = startsWithSearchString;
      }
      return isMatch;
    });
    if (!topMatch && allMatches.length) {
      topMatch = allMatches[0];
    }
    return { topMatch, allMatches };
  }
  runSearch() {
    var _a, _b;
    const { autocompleteEntries } = this.params;
    const searchStrings = autocompleteEntries.map((v) => {
      var _a2;
      return (_a2 = v.displayValue) != null ? _a2 : v.key;
    });
    let matchingStrings;
    let topSuggestion;
    if (this.params.useFuzzySearch) {
      matchingStrings = fuzzySuggestions(this.searchString, searchStrings, true).values;
      topSuggestion = matchingStrings.length ? matchingStrings[0] : void 0;
    } else {
      const containsMatches = this.runContainsSearch(this.searchString, searchStrings);
      matchingStrings = containsMatches.allMatches;
      topSuggestion = containsMatches.topMatch;
    }
    let filteredEntries = autocompleteEntries.filter(({ key, displayValue }) => matchingStrings.includes(displayValue != null ? displayValue : key));
    if (!filteredEntries.length && this.selectedValue && ((_b = (_a = this.params) == null ? void 0 : _a.forceLastSelection) == null ? void 0 : _b.call(_a, this.selectedValue, this.searchString))) {
      filteredEntries = [this.selectedValue];
    }
    this.autocompleteEntries = filteredEntries;
    this.virtualList.refresh();
    if (!topSuggestion) {
      return;
    }
    const topSuggestionIndex = matchingStrings.indexOf(topSuggestion);
    this.checkSetSelectedValue(topSuggestionIndex);
  }
  updateSearchInList() {
    this.virtualList.forEachRenderedRow((row) => row.setSearchString(this.searchString));
  }
  checkSetSelectedValue(index) {
    if (index >= 0 && index < this.autocompleteEntries.length) {
      this.setSelectedValue(index);
    }
  }
  setSelectedValue(index) {
    const value = this.autocompleteEntries[index];
    if (this.selectedValue === value) {
      return;
    }
    this.selectedValue = value;
    this.virtualList.ensureIndexVisible(index);
    this.virtualList.forEachRenderedRow((cmp, idx) => {
      cmp.updateSelected(index === idx);
    });
  }
  createRowComponent(value) {
    var _a;
    const row = new AgAutocompleteRow();
    this.getContext().createBean(row);
    row.setState((_a = value.displayValue) != null ? _a : value.key, value === this.selectedValue);
    return row;
  }
  onMouseMove(mouseEvent) {
    const rect = this.virtualList.getGui().getBoundingClientRect();
    const scrollTop = this.virtualList.getScrollTop();
    const mouseY = mouseEvent.clientY - rect.top + scrollTop;
    const row = Math.floor(mouseY / this.virtualList.getRowHeight());
    this.checkSetSelectedValue(row);
  }
  afterGuiAttached() {
    this.virtualList.refresh();
  }
  getSelectedValue() {
    var _a;
    if (!this.autocompleteEntries.length) {
      return null;
    }
    ;
    return (_a = this.selectedValue) != null ? _a : null;
  }
};
_AgAutocompleteList.TEMPLATE = /* html */
`<div class="ag-autocomplete-list-popup">
            <div ref="eList" class="ag-autocomplete-list"></div>
        <div>`;
__decorateClass([
  RefSelector("eList")
], _AgAutocompleteList.prototype, "eList", 2);
__decorateClass([
  PostConstruct
], _AgAutocompleteList.prototype, "init", 1);
var AgAutocompleteList = _AgAutocompleteList;

// community-modules/core/src/widgets/agAutocomplete.ts
var _AgAutocomplete = class _AgAutocomplete extends Component {
  constructor() {
    super(
      /* html */
      `
            <div class="ag-autocomplete" role="presentation">
                <ag-input-text-field ref="eAutocompleteInput"></ag-input-text-field>
            </div>`
    );
    this.isListOpen = false;
    this.lastPosition = 0;
    this.valid = true;
  }
  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.dispatchEvent({
      type: _AgAutocomplete.EVENT_VALUE_CHANGED,
      value
    });
    this.validate(value);
  }
  updateAutocompleteList(value) {
    var _a, _b, _c, _d;
    const autocompleteListParams = (_b = (_a = this.listGenerator) == null ? void 0 : _a.call(this, value, this.lastPosition)) != null ? _b : { enabled: false };
    if (!autocompleteListParams.type || autocompleteListParams.type !== ((_c = this.autocompleteListParams) == null ? void 0 : _c.type)) {
      if (this.isListOpen) {
        this.closeList();
      }
    }
    this.autocompleteListParams = autocompleteListParams;
    if ((_d = this.autocompleteListParams) == null ? void 0 : _d.enabled) {
      if (!this.isListOpen) {
        this.openList();
      }
      const { searchString } = this.autocompleteListParams;
      this.autocompleteList.setSearch(searchString != null ? searchString : "");
    } else {
      if (this.isListOpen) {
        this.closeList();
      }
    }
  }
  onKeyDown(event) {
    const key = event.key;
    this.updateLastPosition();
    switch (key) {
      case KeyCode.ENTER:
        this.onEnterKeyDown(event);
        break;
      case KeyCode.TAB:
        this.onTabKeyDown(event);
        break;
      case KeyCode.DOWN:
      case KeyCode.UP:
        this.onUpDownKeyDown(event, key);
        break;
      case KeyCode.LEFT:
      case KeyCode.RIGHT:
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        setTimeout(() => {
          this.updatePositionAndList();
        });
        break;
      case KeyCode.ESCAPE:
        this.onEscapeKeyDown(event);
        break;
      case KeyCode.SPACE:
        if (event.ctrlKey && !this.isListOpen) {
          event.preventDefault();
          this.forceOpenList();
        }
        break;
    }
  }
  confirmSelection() {
    var _a;
    const selectedValue = (_a = this.autocompleteList) == null ? void 0 : _a.getSelectedValue();
    if (selectedValue) {
      this.closeList();
      this.dispatchEvent({
        type: _AgAutocomplete.EVENT_OPTION_SELECTED,
        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) {
    var _a;
    event.preventDefault();
    if (!this.isListOpen) {
      this.forceOpenList();
    } else {
      (_a = this.autocompleteList) == null ? void 0 : _a.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() {
    var _a;
    this.updateLastPosition();
    this.updateAutocompleteList((_a = this.eAutocompleteInput.getValue()) != null ? _a : null);
  }
  setCaret(position, setFocus) {
    const eDocument = this.gos.getDocument();
    const activeEl = this.gos.getActiveDomElement();
    if (setFocus && (!activeEl || activeEl === eDocument.body)) {
      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() {
    var _a;
    this.lastPosition = (_a = this.eAutocompleteInput.getInputElement().selectionStart) != null ? _a : 0;
  }
  validate(value) {
    var _a;
    if (!this.validator) {
      return;
    }
    this.validationMessage = this.validator(value);
    this.eAutocompleteInput.getInputElement().setCustomValidity((_a = this.validationMessage) != null ? _a : "");
    this.valid = !this.validationMessage;
    this.dispatchEvent({
      type: _AgAutocomplete.EVENT_VALID_CHANGED,
      isValid: this.valid,
      validationMessage: this.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.popupService.addPopup({
      eChild: ePopupGui,
      anchorToElement: this.getGui(),
      positionCallback: () => this.popupService.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.dispatchEvent({
      type: _AgAutocomplete.EVENT_VALUE_CONFIRMED,
      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 != null ? 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;
  }
};
_AgAutocomplete.EVENT_VALUE_CHANGED = "eventValueChanged";
_AgAutocomplete.EVENT_VALUE_CONFIRMED = "eventValueConfirmed";
_AgAutocomplete.EVENT_OPTION_SELECTED = "eventOptionSelected";
_AgAutocomplete.EVENT_VALID_CHANGED = "eventValidChanged";
__decorateClass([
  Autowired("popupService")
], _AgAutocomplete.prototype, "popupService", 2);
__decorateClass([
  RefSelector("eAutocompleteInput")
], _AgAutocomplete.prototype, "eAutocompleteInput", 2);
__decorateClass([
  PostConstruct
], _AgAutocomplete.prototype, "postConstruct", 1);
var AgAutocomplete = _AgAutocomplete;

// community-modules/core/src/widgets/pillDragComp.ts
var _PillDragComp = class _PillDragComp extends Component {
  constructor(dragSourceDropTarget, ghost, horizontal, template) {
    super();
    this.dragSourceDropTarget = dragSourceDropTarget;
    this.ghost = ghost;
    this.horizontal = horizontal;
    this.template = template;
  }
  init() {
    var _a;
    this.setTemplate((_a = this.template) != null ? _a : _PillDragComp.TEMPLATE);
    const eGui = this.getGui();
    this.addElementClasses(eGui);
    this.addElementClasses(this.eDragHandle, "drag-handle");
    this.addElementClasses(this.eText, "text");
    this.addElementClasses(this.eButton, "button");
    this.eDragHandle.appendChild(createIconNoSpan("columnDrag", this.gos));
    this.eButton.appendChild(createIconNoSpan("cancel", this.gos));
    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.localeService.getLocaleTextFunc();
    const ariaInstructions = [this.getAriaDisplayName()];
    this.addAdditionalAriaInstructions(ariaInstructions, translate);
    setAriaLabel(this.getGui(), ariaInstructions.join(". "));
  }
  addAdditionalAriaInstructions(ariaInstructions, translate) {
    if (this.isRemovable()) {
      const deleteAria = translate("ariaDropZoneColumnComponentDescription", "Press DELETE to remove");
      ariaInstructions.push(deleteAria);
    }
  }
  setupTooltip() {
    const refresh = () => {
      const newTooltipText = this.getTooltip();
      this.setTooltip({ newTooltipText });
    };
    refresh();
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, refresh);
  }
  getDragSourceId() {
    return void 0;
  }
  getDefaultIconName() {
    return DragAndDropService.ICON_NOT_ALLOWED;
  }
  addDragSource() {
    const { dragAndDropService, 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()
    };
    dragAndDropService.addDragSource(dragSource, true);
    this.addDestroyFunc(() => dragAndDropService.removeDragSource(dragSource));
  }
  setupComponents() {
    this.setTextValue();
    this.setupRemove();
    if (this.ghost) {
      this.addCssClass("ag-column-drop-cell-ghost");
    }
  }
  isRemovable() {
    return true;
  }
  refreshRemove() {
    setDisplayed(this.eButton, this.isRemovable());
  }
  setupRemove() {
    this.refreshRemove();
    const agEvent = { type: _PillDragComp.EVENT_COLUMN_REMOVE };
    this.addGuiEventListener("keydown", (e) => this.onKeyDown(e));
    this.addManagedListener(this.eButton, "click", (mouseEvent) => {
      this.dispatchEvent(agEvent);
      mouseEvent.stopPropagation();
    });
    const touchListener = new TouchListener(this.eButton);
    this.addManagedListener(touchListener, TouchListener.EVENT_TAP, () => {
      this.dispatchEvent(agEvent);
    });
    this.addDestroyFunc(touchListener.destroy.bind(touchListener));
  }
  onKeyDown(e) {
    const isDelete = e.key === KeyCode.DELETE;
    if (isDelete) {
      if (this.isRemovable()) {
        e.preventDefault();
        this.dispatchEvent({ type: _PillDragComp.EVENT_COLUMN_REMOVE });
      }
    }
  }
  getDisplayValue() {
    return this.getDisplayName();
  }
  setTextValue() {
    const displayValue = this.getDisplayValue();
    const displayValueSanitised = escapeString(displayValue);
    this.eText.innerHTML = displayValueSanitised;
  }
  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;
  }
};
_PillDragComp.EVENT_COLUMN_REMOVE = "columnRemove";
_PillDragComp.TEMPLATE = /* html */
`<span role="option">
          <span ref="eDragHandle" class="ag-drag-handle ag-column-drop-cell-drag-handle" role="presentation"></span>
          <span ref="eText" class="ag-column-drop-cell-text" aria-hidden="true"></span>
          <span ref="eButton" class="ag-column-drop-cell-button" role="presentation"></span>
        </span>`;
__decorateClass([
  Autowired("dragAndDropService")
], _PillDragComp.prototype, "dragAndDropService", 2);
__decorateClass([
  RefSelector("eText")
], _PillDragComp.prototype, "eText", 2);
__decorateClass([
  RefSelector("eDragHandle")
], _PillDragComp.prototype, "eDragHandle", 2);
__decorateClass([
  RefSelector("eButton")
], _PillDragComp.prototype, "eButton", 2);
__decorateClass([
  PostConstruct
], _PillDragComp.prototype, "init", 1);
var PillDragComp = _PillDragComp;

// community-modules/core/src/widgets/pillDropZonePanel.ts
var _PillDropZonePanel = class _PillDropZonePanel extends Component {
  constructor(horizontal) {
    super(
      /* html */
      `<div class="ag-unselectable" role="presentation"></div>`
    );
    this.horizontal = horizontal;
    this.state = _PillDropZonePanel.STATE_NOT_DRAGGING;
    this.guiDestroyFunctions = [];
    this.childPillComponents = [];
    this.resizeEnabled = false;
    this.addElementClasses(this.getGui());
    this.ePillDropList = document.createElement("div");
    this.addElementClasses(this.ePillDropList, "list");
    setAriaRole(this.ePillDropList, "listbox");
  }
  isHorizontal() {
    return this.horizontal;
  }
  toggleResizable(resizable) {
    this.positionableFeature.setResizable(resizable ? { bottom: true } : false);
    this.resizeEnabled = resizable;
  }
  isSourceEventFromTarget(draggingEvent) {
    const { dropZoneTarget, dragSource } = draggingEvent;
    return dropZoneTarget.contains(dragSource.eElement);
  }
  destroy() {
    this.destroyGui();
    super.destroy();
  }
  destroyGui() {
    this.guiDestroyFunctions.forEach((func) => func());
    this.guiDestroyFunctions.length = 0;
    this.childPillComponents.length = 0;
    clearElement(this.getGui());
    clearElement(this.ePillDropList);
  }
  init(params) {
    this.params = params != null ? params : {};
    this.createManagedBean(new ManagedFocusFeature(
      this.getFocusableElement(),
      {
        handleKeyDown: this.handleKeyDown.bind(this)
      }
    ));
    this.setupDropTarget();
    this.positionableFeature = new PositionableFeature(this.getGui(), { minHeight: 100 });
    this.createManagedBean(this.positionableFeature);
    this.refreshGui();
    setAriaLabel(this.ePillDropList, this.getAriaLabel());
  }
  handleKeyDown(e) {
    const isVertical = !this.horizontal;
    let isNext = e.key === KeyCode.DOWN;
    let isPrevious = e.key === KeyCode.UP;
    if (!isVertical) {
      const isRtl = this.gos.get("enableRtl");
      isNext = !isRtl && e.key === KeyCode.RIGHT || isRtl && e.key === KeyCode.LEFT;
      isPrevious = !isRtl && e.key === KeyCode.LEFT || isRtl && e.key === KeyCode.RIGHT;
    }
    if (!isNext && !isPrevious) {
      return;
    }
    const el = this.focusService.findNextFocusableElement(
      this.getFocusableElement(),
      false,
      isPrevious
    );
    if (el) {
      e.preventDefault();
      el.focus();
    }
  }
  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),
      isInterestedIn: this.isInterestedIn.bind(this)
    };
    this.dragAndDropService.addDropTarget(this.dropTarget);
  }
  minimumAllowedNewInsertIndex() {
    return 0;
  }
  checkInsertIndex(draggingEvent) {
    const newIndex = this.getNewInsertIndex(draggingEvent);
    if (newIndex < 0) {
      return false;
    }
    const minimumAllowedIndex = this.minimumAllowedNewInsertIndex();
    const newAdjustedIndex = Math.max(minimumAllowedIndex, newIndex);
    const changed = newAdjustedIndex !== this.insertIndex;
    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 !== _PillDropZonePanel.STATE_NOT_DRAGGING) {
      return;
    }
    this.state = _PillDropZonePanel.STATE_REARRANGE_ITEMS;
    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(draggingEvent) {
  }
  onDragEnter(draggingEvent) {
    const dragItems = this.getItems(draggingEvent.dragSource.getDragItem());
    this.state = _PillDropZonePanel.STATE_NEW_ITEMS_IN;
    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 = _PillDropZonePanel.STATE_NOT_DRAGGING;
      return;
    }
    this.handleDragEnterEnd(draggingEvent);
    this.checkInsertIndex(draggingEvent);
    this.refreshGui();
  }
  isPotentialDndItems() {
    return existsAndNotEmpty(this.potentialDndItems);
  }
  handleDragLeaveEnd(draggingEvent) {
  }
  onDragLeave(draggingEvent) {
    if (this.state === _PillDropZonePanel.STATE_REARRANGE_ITEMS) {
      const items = this.getItems(draggingEvent.dragSource.getDragItem());
      this.removeItems(items);
    }
    if (this.isPotentialDndItems()) {
      this.handleDragLeaveEnd(draggingEvent);
      this.potentialDndItems = [];
      this.refreshGui();
    }
    this.state = _PillDropZonePanel.STATE_NOT_DRAGGING;
  }
  refreshOnDragStop() {
    return true;
  }
  onDragStop() {
    if (this.isPotentialDndItems()) {
      let success = false;
      if (this.state === _PillDropZonePanel.STATE_NEW_ITEMS_IN) {
        this.addItems(this.potentialDndItems);
        success = true;
      } else {
        success = this.rearrangeItems(this.potentialDndItems);
      }
      this.potentialDndItems = [];
      if (this.refreshOnDragStop() || !success) {
        this.refreshGui();
      }
    }
    this.state = _PillDropZonePanel.STATE_NOT_DRAGGING;
  }
  removeItems(itemsToRemove) {
    const newItemList = this.getExistingItems().filter((item) => !includes(itemsToRemove, 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) {
    const newItemList = this.getNonGhostItems().slice();
    insertArrayIntoArray(newItemList, itemsToAdd, this.insertIndex);
    if (areEqual(newItemList, this.getExistingItems())) {
      return false;
    }
    this.updateItems(newItemList);
    return true;
  }
  refreshGui() {
    const scrollTop = this.ePillDropList.scrollTop;
    const resizeEnabled = this.resizeEnabled;
    const focusedIndex = this.getFocusedItem();
    let alternateElement = this.focusService.findNextFocusableElement();
    if (!alternateElement) {
      alternateElement = this.focusService.findNextFocusableElement(void 0, false, true);
    }
    this.toggleResizable(false);
    this.destroyGui();
    this.addIconAndTitleToGui();
    this.addEmptyMessageToGui();
    this.addItemsToGui();
    if (!this.isHorizontal()) {
      this.ePillDropList.scrollTop = scrollTop;
    }
    if (resizeEnabled) {
      this.toggleResizable(resizeEnabled);
    }
    if (this.focusService.isKeyboardMode()) {
      this.restoreFocus(focusedIndex, alternateElement);
    }
  }
  getFocusedItem() {
    const eGui = this.getGui();
    const activeElement = this.gos.getActiveDomElement();
    if (!eGui.contains(activeElement)) {
      return -1;
    }
    const items = Array.from(eGui.querySelectorAll(".ag-column-drop-cell"));
    return items.indexOf(activeElement);
  }
  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) => !includes(this.potentialDndItems, 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() {
    this.childPillComponents.forEach((comp, idx) => {
      const eGui = comp.getGui();
      setAriaPosInSet(eGui, idx + 1);
      setAriaSetSize(eGui, this.childPillComponents.length);
    });
  }
  createItemComponent(item, ghost) {
    const itemComponent = this.createPillComponent(item, this.dropTarget, ghost, this.horizontal);
    itemComponent.addEventListener(PillDragComp.EVENT_COLUMN_REMOVE, this.removeItems.bind(this, [item]));
    this.context.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 = document.createElement("div");
    setAriaHidden(eTitleBar, true);
    this.addElementClasses(eTitleBar, "title-bar");
    this.addElementClasses(eGroupIcon, "icon");
    this.addOrRemoveCssClass("ag-column-drop-empty", this.isExistingItemsEmpty());
    eTitleBar.appendChild(eGroupIcon);
    if (!this.horizontal) {
      const eTitle = document.createElement("span");
      this.addElementClasses(eTitle, "title");
      eTitle.innerHTML = 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 = document.createElement("span");
    eMessage.innerHTML = emptyMessage;
    this.addElementClasses(eMessage, "empty-message");
    this.ePillDropList.appendChild(eMessage);
  }
  addArrow(eParent) {
    if (this.horizontal) {
      const enableRtl = this.gos.get("enableRtl");
      const icon = createIconNoSpan(enableRtl ? "smallLeft" : "smallRight", this.gos);
      this.addElementClasses(icon, "cell-separator");
      eParent.appendChild(icon);
    }
  }
};
_PillDropZonePanel.STATE_NOT_DRAGGING = "notDragging";
_PillDropZonePanel.STATE_NEW_ITEMS_IN = "newItemsIn";
_PillDropZonePanel.STATE_REARRANGE_ITEMS = "rearrangeItems";
__decorateClass([
  Autowired("focusService")
], _PillDropZonePanel.prototype, "focusService", 2);
__decorateClass([
  Autowired("dragAndDropService")
], _PillDropZonePanel.prototype, "dragAndDropService", 2);
var PillDropZonePanel = _PillDropZonePanel;

// community-modules/core/src/vanillaFrameworkOverrides.ts
var PASSIVE_EVENTS2 = ["touchstart", "touchend", "touchmove", "touchcancel"];
var VanillaFrameworkOverrides = class {
  constructor(frameworkName = "javascript") {
    this.frameworkName = frameworkName;
    this.renderingEngine = "vanilla";
    this.wrapIncoming = (callback) => callback();
    this.wrapOutgoing = (callback) => callback();
  }
  setInterval(action, timeout) {
    return new AgPromise((resolve) => {
      resolve(window.setInterval(action, timeout));
    });
  }
  // for Vanilla JS, we just add the event to the element
  addEventListener(element, type, listener, useCapture) {
    const isPassive = includes(PASSIVE_EVENTS2, type);
    element.addEventListener(type, listener, { capture: !!useCapture, passive: isPassive });
  }
  get shouldWrapOutgoing() {
    return false;
  }
  frameworkComponent(name) {
    return null;
  }
  isFrameworkComponent(comp) {
    return false;
  }
  getDocLink(path) {
    const framework = this.frameworkName === "solid" ? "react" : this.frameworkName;
    return `https://www.ag-grid.com/${framework}-data-grid${path ? `/${path}` : ""}`;
  }
};

// community-modules/core/src/cellNavigationService.ts
var CellNavigationService = class extends BeanStub {
  // returns null if no cell to focus on, ie at the end of the grid
  getNextCellToFocus(key, focusedCell, ctrlPressed = false) {
    if (ctrlPressed) {
      return this.getNextCellToFocusWithCtrlPressed(key, focusedCell);
    }
    return this.getNextCellToFocusWithoutCtrlPressed(key, focusedCell);
  }
  getNextCellToFocusWithCtrlPressed(key, focusedCell) {
    const upKey = key === KeyCode.UP;
    const downKey = key === KeyCode.DOWN;
    const leftKey = key === KeyCode.LEFT;
    let column;
    let rowIndex;
    if (upKey || downKey) {
      rowIndex = upKey ? this.paginationProxy.getPageFirstRow() : this.paginationProxy.getPageLastRow();
      column = focusedCell.column;
    } else {
      const allColumns = this.columnModel.getAllDisplayedColumns();
      const isRtl = this.gos.get("enableRtl");
      rowIndex = focusedCell.rowIndex;
      column = leftKey !== isRtl ? allColumns[0] : last(allColumns);
    }
    return {
      rowIndex,
      rowPinned: null,
      column
    };
  }
  getNextCellToFocusWithoutCtrlPressed(key, focusedCell) {
    let pointer = focusedCell;
    let finished = false;
    while (!finished) {
      switch (key) {
        case KeyCode.UP:
          pointer = this.getCellAbove(pointer);
          break;
        case KeyCode.DOWN:
          pointer = this.getCellBelow(pointer);
          break;
        case KeyCode.RIGHT:
          if (this.gos.get("enableRtl")) {
            pointer = this.getCellToLeft(pointer);
          } else {
            pointer = this.getCellToRight(pointer);
          }
          break;
        case KeyCode.LEFT:
          if (this.gos.get("enableRtl")) {
            pointer = this.getCellToRight(pointer);
          } else {
            pointer = this.getCellToLeft(pointer);
          }
          break;
        default:
          pointer = null;
          console.warn("AG Grid: unknown key for navigation " + key);
          break;
      }
      if (pointer) {
        finished = this.isCellGoodToFocusOn(pointer);
      } else {
        finished = true;
      }
    }
    return pointer;
  }
  isCellGoodToFocusOn(gridCell) {
    const column = gridCell.column;
    let rowNode;
    switch (gridCell.rowPinned) {
      case "top":
        rowNode = this.pinnedRowModel.getPinnedTopRow(gridCell.rowIndex);
        break;
      case "bottom":
        rowNode = this.pinnedRowModel.getPinnedBottomRow(gridCell.rowIndex);
        break;
      default:
        rowNode = this.rowModel.getRow(gridCell.rowIndex);
        break;
    }
    if (!rowNode) {
      return false;
    }
    const suppressNavigable = column.isSuppressNavigable(rowNode);
    return !suppressNavigable;
  }
  getCellToLeft(lastCell) {
    if (!lastCell) {
      return null;
    }
    const colToLeft = this.columnModel.getDisplayedColBefore(lastCell.column);
    if (!colToLeft) {
      return null;
    }
    return {
      rowIndex: lastCell.rowIndex,
      column: colToLeft,
      rowPinned: lastCell.rowPinned
    };
  }
  getCellToRight(lastCell) {
    if (!lastCell) {
      return null;
    }
    const colToRight = this.columnModel.getDisplayedColAfter(lastCell.column);
    if (!colToRight) {
      return null;
    }
    return {
      rowIndex: lastCell.rowIndex,
      column: colToRight,
      rowPinned: lastCell.rowPinned
    };
  }
  getRowBelow(rowPosition) {
    const index = rowPosition.rowIndex;
    const pinned = rowPosition.rowPinned;
    if (this.isLastRowInContainer(rowPosition)) {
      switch (pinned) {
        case "bottom":
          return null;
        case "top":
          if (this.rowModel.isRowsToRender()) {
            return { rowIndex: this.paginationProxy.getPageFirstRow(), rowPinned: null };
          }
          if (this.pinnedRowModel.isRowsToRender("bottom")) {
            return { rowIndex: 0, rowPinned: "bottom" };
          }
          return null;
        default:
          if (this.pinnedRowModel.isRowsToRender("bottom")) {
            return { rowIndex: 0, rowPinned: "bottom" };
          }
          return null;
      }
    }
    const rowNode = this.rowModel.getRow(rowPosition.rowIndex);
    const nextStickyPosition = this.getNextStickyPosition(rowNode);
    if (nextStickyPosition) {
      return nextStickyPosition;
    }
    return { rowIndex: index + 1, rowPinned: pinned };
  }
  getNextStickyPosition(rowNode, up) {
    if (!this.gos.isGroupRowsSticky() || !rowNode || !rowNode.sticky) {
      return;
    }
    const isTopCtrls = this.rowRenderer.getStickyTopRowCtrls().some((ctrl) => ctrl.getRowNode().rowIndex === rowNode.rowIndex);
    let stickyRowCtrls = [];
    if (isTopCtrls) {
      stickyRowCtrls = [...this.rowRenderer.getStickyTopRowCtrls()].sort(
        (a, b) => a.getRowNode().rowIndex - b.getRowNode().rowIndex
      );
    } else {
      stickyRowCtrls = [...this.rowRenderer.getStickyBottomRowCtrls()].sort(
        (a, b) => b.getRowNode().rowIndex - a.getRowNode().rowIndex
      );
    }
    const diff = up ? -1 : 1;
    const idx = stickyRowCtrls.findIndex((ctrl) => ctrl.getRowNode().rowIndex === rowNode.rowIndex);
    const nextCtrl = stickyRowCtrls[idx + diff];
    if (nextCtrl) {
      return { rowIndex: nextCtrl.getRowNode().rowIndex, rowPinned: null };
    }
  }
  getCellBelow(lastCell) {
    if (!lastCell) {
      return null;
    }
    const rowBelow = this.getRowBelow(lastCell);
    if (rowBelow) {
      return {
        rowIndex: rowBelow.rowIndex,
        column: lastCell.column,
        rowPinned: rowBelow.rowPinned
      };
    }
    return null;
  }
  isLastRowInContainer(rowPosition) {
    const pinned = rowPosition.rowPinned;
    const index = rowPosition.rowIndex;
    if (pinned === "top") {
      const lastTopIndex = this.pinnedRowModel.getPinnedTopRowData().length - 1;
      return lastTopIndex <= index;
    }
    if (pinned === "bottom") {
      const lastBottomIndex = this.pinnedRowModel.getPinnedBottomRowData().length - 1;
      return lastBottomIndex <= index;
    }
    const lastBodyIndex = this.paginationProxy.getPageLastRow();
    return lastBodyIndex <= index;
  }
  getRowAbove(rowPosition) {
    const index = rowPosition.rowIndex;
    const pinned = rowPosition.rowPinned;
    const isFirstRow = pinned ? index === 0 : index === this.paginationProxy.getPageFirstRow();
    if (isFirstRow) {
      if (pinned === "top") {
        return null;
      }
      if (!pinned) {
        if (this.pinnedRowModel.isRowsToRender("top")) {
          return this.getLastFloatingTopRow();
        }
        return null;
      }
      if (this.rowModel.isRowsToRender()) {
        return this.getLastBodyCell();
      }
      if (this.pinnedRowModel.isRowsToRender("top")) {
        return this.getLastFloatingTopRow();
      }
      return null;
    }
    const rowNode = this.rowModel.getRow(rowPosition.rowIndex);
    const nextStickyPosition = this.getNextStickyPosition(rowNode, true);
    if (nextStickyPosition) {
      return nextStickyPosition;
    }
    return { rowIndex: index - 1, rowPinned: pinned };
  }
  getCellAbove(lastCell) {
    if (!lastCell) {
      return null;
    }
    const rowAbove = this.getRowAbove({ rowIndex: lastCell.rowIndex, rowPinned: lastCell.rowPinned });
    if (rowAbove) {
      return {
        rowIndex: rowAbove.rowIndex,
        column: lastCell.column,
        rowPinned: rowAbove.rowPinned
      };
    }
    return null;
  }
  getLastBodyCell() {
    const lastBodyRow = this.paginationProxy.getPageLastRow();
    return { rowIndex: lastBodyRow, rowPinned: null };
  }
  getLastFloatingTopRow() {
    const lastFloatingRow = this.pinnedRowModel.getPinnedTopRowData().length - 1;
    return { rowIndex: lastFloatingRow, rowPinned: "top" };
  }
  getNextTabbedCell(gridCell, backwards) {
    if (backwards) {
      return this.getNextTabbedCellBackwards(gridCell);
    }
    return this.getNextTabbedCellForwards(gridCell);
  }
  getNextTabbedCellForwards(gridCell) {
    const displayedColumns = this.columnModel.getAllDisplayedColumns();
    let newRowIndex = gridCell.rowIndex;
    let newFloating = gridCell.rowPinned;
    let newColumn = this.columnModel.getDisplayedColAfter(gridCell.column);
    if (!newColumn) {
      newColumn = displayedColumns[0];
      const rowBelow = this.getRowBelow(gridCell);
      if (missing(rowBelow)) {
        return null;
      }
      if (!rowBelow.rowPinned && !this.paginationProxy.isRowInPage(rowBelow)) {
        return null;
      }
      newRowIndex = rowBelow ? rowBelow.rowIndex : null;
      newFloating = rowBelow ? rowBelow.rowPinned : null;
    }
    return { rowIndex: newRowIndex, column: newColumn, rowPinned: newFloating };
  }
  getNextTabbedCellBackwards(gridCell) {
    const displayedColumns = this.columnModel.getAllDisplayedColumns();
    let newRowIndex = gridCell.rowIndex;
    let newFloating = gridCell.rowPinned;
    let newColumn = this.columnModel.getDisplayedColBefore(gridCell.column);
    if (!newColumn) {
      newColumn = last(displayedColumns);
      const rowAbove = this.getRowAbove({ rowIndex: gridCell.rowIndex, rowPinned: gridCell.rowPinned });
      if (missing(rowAbove)) {
        return null;
      }
      if (!rowAbove.rowPinned && !this.paginationProxy.isRowInPage(rowAbove)) {
        return null;
      }
      newRowIndex = rowAbove ? rowAbove.rowIndex : null;
      newFloating = rowAbove ? rowAbove.rowPinned : null;
    }
    return { rowIndex: newRowIndex, column: newColumn, rowPinned: newFloating };
  }
};
__decorateClass([
  Autowired("columnModel")
], CellNavigationService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("rowModel")
], CellNavigationService.prototype, "rowModel", 2);
__decorateClass([
  Autowired("rowRenderer")
], CellNavigationService.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], CellNavigationService.prototype, "pinnedRowModel", 2);
__decorateClass([
  Autowired("paginationProxy")
], CellNavigationService.prototype, "paginationProxy", 2);
CellNavigationService = __decorateClass([
  Bean("cellNavigationService")
], CellNavigationService);

// community-modules/core/src/alignedGridsService.ts
var AlignedGridsService = class extends BeanStub {
  constructor() {
    super(...arguments);
    // flag to mark if we are consuming. to avoid cyclic events (ie other grid firing back to master
    // while processing a master event) we mark this if consuming an event, and if we are, then
    // we don't fire back any events.
    this.consuming = false;
  }
  setBeans(loggerFactory) {
    this.logger = loggerFactory.create("AlignedGridsService");
  }
  getAlignedGridApis() {
    var _a;
    let alignedGrids = (_a = this.gos.get("alignedGrids")) != null ? _a : [];
    const isCallbackConfig = typeof alignedGrids === "function";
    if (typeof alignedGrids === "function") {
      alignedGrids = alignedGrids();
    }
    const seeUrl = () => `See ${this.getFrameworkOverrides().getDocLink("aligned-grids")}`;
    const apis = alignedGrids.map((alignedGrid) => {
      var _a2;
      if (!alignedGrid) {
        errorOnce(`alignedGrids contains an undefined option.`);
        if (!isCallbackConfig) {
          errorOnce(`You may want to configure via a callback to avoid setup race conditions:
                     "alignedGrids: () => [linkedGrid]"`);
        }
        errorOnce(seeUrl());
        return;
      }
      if (alignedGrid instanceof GridApi) {
        return alignedGrid;
      }
      const refOrComp = alignedGrid;
      if ("current" in refOrComp) {
        return (_a2 = refOrComp.current) == null ? void 0 : _a2.api;
      } else {
        if (!refOrComp.api) {
          errorOnce(`alignedGrids - No api found on the linked grid. If you are passing gridOptions to alignedGrids since v31 this is no longer valid. ${seeUrl()}`);
        }
        return refOrComp.api;
      }
    }).filter((api) => !!api && !api.isDestroyed());
    return apis;
  }
  init() {
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_MOVED, this.fireColumnEvent.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VISIBLE, this.fireColumnEvent.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PINNED, this.fireColumnEvent.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_GROUP_OPENED, this.fireColumnEvent.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_RESIZED, this.fireColumnEvent.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_BODY_SCROLL, this.fireScrollEvent.bind(this));
  }
  // common logic across all the fire methods
  fireEvent(callback) {
    if (this.consuming) {
      return;
    }
    this.getAlignedGridApis().forEach((api) => {
      if (api.isDestroyed()) {
        return;
      }
      const alignedGridService = api.__getAlignedGridService();
      callback(alignedGridService);
    });
  }
  // common logic across all consume methods. very little common logic, however extracting
  // guarantees consistency across the methods.
  onEvent(callback) {
    this.consuming = true;
    callback();
    this.consuming = false;
  }
  fireColumnEvent(event) {
    this.fireEvent((alignedGridsService) => {
      alignedGridsService.onColumnEvent(event);
    });
  }
  fireScrollEvent(event) {
    if (event.direction !== "horizontal") {
      return;
    }
    this.fireEvent((alignedGridsService) => {
      alignedGridsService.onScrollEvent(event);
    });
  }
  onScrollEvent(event) {
    this.onEvent(() => {
      const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
      gridBodyCon.getScrollFeature().setHorizontalScrollPosition(event.left, true);
    });
  }
  getMasterColumns(event) {
    const result = [];
    if (event.columns) {
      event.columns.forEach((column) => {
        result.push(column);
      });
    } else if (event.column) {
      result.push(event.column);
    }
    return result;
  }
  getColumnIds(event) {
    const result = [];
    if (event.columns) {
      event.columns.forEach((column) => {
        result.push(column.getColId());
      });
    } else if (event.column) {
      result.push(event.column.getColId());
    }
    return result;
  }
  onColumnEvent(event) {
    this.onEvent(() => {
      switch (event.type) {
        case Events.EVENT_COLUMN_MOVED:
        case Events.EVENT_COLUMN_VISIBLE:
        case Events.EVENT_COLUMN_PINNED:
        case Events.EVENT_COLUMN_RESIZED:
          const colEvent = event;
          this.processColumnEvent(colEvent);
          break;
        case Events.EVENT_COLUMN_GROUP_OPENED:
          const groupOpenedEvent = event;
          this.processGroupOpenedEvent(groupOpenedEvent);
          break;
        case Events.EVENT_COLUMN_PIVOT_CHANGED:
          console.warn("AG Grid: pivoting is not supported with aligned grids. You can only use one of these features at a time in a grid.");
          break;
      }
    });
  }
  processGroupOpenedEvent(groupOpenedEvent) {
    groupOpenedEvent.columnGroups.forEach((masterGroup) => {
      let otherColumnGroup = null;
      if (masterGroup) {
        const groupId = masterGroup.getGroupId();
        otherColumnGroup = this.columnModel.getProvidedColumnGroup(groupId);
      }
      if (masterGroup && !otherColumnGroup) {
        return;
      }
      this.logger.log("onColumnEvent-> processing " + groupOpenedEvent + " expanded = " + masterGroup.isExpanded());
      this.columnModel.setColumnGroupOpened(otherColumnGroup, masterGroup.isExpanded(), "alignedGridChanged");
    });
  }
  processColumnEvent(colEvent) {
    var _a;
    const masterColumn = colEvent.column;
    let otherColumn = null;
    if (masterColumn) {
      otherColumn = this.columnModel.getPrimaryColumn(masterColumn.getColId());
    }
    if (masterColumn && !otherColumn) {
      return;
    }
    const masterColumns = this.getMasterColumns(colEvent);
    switch (colEvent.type) {
      case Events.EVENT_COLUMN_MOVED:
        {
          const movedEvent = colEvent;
          const srcColState = colEvent.api.getColumnState();
          const destColState = srcColState.map((s) => ({ colId: s.colId }));
          this.columnModel.applyColumnState(
            { state: destColState, applyOrder: true },
            "alignedGridChanged"
          );
          this.logger.log(`onColumnEvent-> processing ${colEvent.type} toIndex = ${movedEvent.toIndex}`);
        }
        break;
      case Events.EVENT_COLUMN_VISIBLE:
        {
          const visibleEvent = colEvent;
          const srcColState = colEvent.api.getColumnState();
          const destColState = srcColState.map((s) => ({ colId: s.colId, hide: s.hide }));
          this.columnModel.applyColumnState({ state: destColState }, "alignedGridChanged");
          this.logger.log(`onColumnEvent-> processing ${colEvent.type} visible = ${visibleEvent.visible}`);
        }
        break;
      case Events.EVENT_COLUMN_PINNED:
        {
          const pinnedEvent = colEvent;
          const srcColState = colEvent.api.getColumnState();
          const destColState = srcColState.map((s) => ({ colId: s.colId, pinned: s.pinned }));
          this.columnModel.applyColumnState({ state: destColState }, "alignedGridChanged");
          this.logger.log(`onColumnEvent-> processing ${colEvent.type} pinned = ${pinnedEvent.pinned}`);
        }
        break;
      case Events.EVENT_COLUMN_RESIZED:
        const resizedEvent = colEvent;
        const columnWidths = {};
        masterColumns.forEach((column) => {
          this.logger.log(`onColumnEvent-> processing ${colEvent.type} actualWidth = ${column.getActualWidth()}`);
          columnWidths[column.getId()] = { key: column.getColId(), newWidth: column.getActualWidth() };
        });
        (_a = resizedEvent.flexColumns) == null ? void 0 : _a.forEach((col) => {
          if (columnWidths[col.getId()]) {
            delete columnWidths[col.getId()];
          }
        });
        this.columnModel.setColumnWidths(Object.values(columnWidths), false, resizedEvent.finished, "alignedGridChanged");
        break;
    }
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    const isVerticalScrollShowing2 = gridBodyCon.isVerticalScrollShowing();
    this.getAlignedGridApis().forEach((api) => {
      api.setGridOption("alwaysShowVerticalScroll", isVerticalScrollShowing2);
    });
  }
};
__decorateClass([
  Autowired("columnModel")
], AlignedGridsService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("ctrlsService")
], AlignedGridsService.prototype, "ctrlsService", 2);
__decorateClass([
  __decorateParam(0, Qualifier("loggerFactory"))
], AlignedGridsService.prototype, "setBeans", 1);
__decorateClass([
  PostConstruct
], AlignedGridsService.prototype, "init", 1);
AlignedGridsService = __decorateClass([
  Bean("alignedGridsService")
], AlignedGridsService);

// community-modules/core/src/selectionService.ts
var SelectionService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.selectedNodes = /* @__PURE__ */ new Map();
    this.lastRowNode = null;
  }
  init() {
    this.rowSelection = this.gos.get("rowSelection");
    this.groupSelectsChildren = this.gos.get("groupSelectsChildren");
    this.addManagedPropertyListeners(["groupSelectsChildren", "rowSelection"], () => {
      this.groupSelectsChildren = this.gos.get("groupSelectsChildren");
      this.rowSelection = this.gos.get("rowSelection");
      this.deselectAllRowNodes({ source: "api" });
    });
    this.addManagedListener(this.eventService, Events.EVENT_ROW_SELECTED, this.onRowSelected.bind(this));
  }
  destroy() {
    super.destroy();
    this.resetNodes();
    this.lastRowNode = null;
  }
  isMultiselect() {
    return this.rowSelection === "multiple";
  }
  setNodesSelected(params) {
    var _a;
    const {
      newValue,
      clearSelection,
      suppressFinishActions,
      rangeSelect,
      nodes,
      event,
      source = "api"
    } = params;
    if (nodes.length === 0)
      return 0;
    if (nodes.length > 1 && !this.isMultiselect()) {
      console.warn(`AG Grid: cannot multi select while rowSelection='single'`);
      return 0;
    }
    const groupSelectsFiltered = this.groupSelectsChildren && params.groupSelectsFiltered === true;
    const filteredNodes = nodes.map((node) => node.footer ? node.sibling : node);
    if (rangeSelect) {
      if (nodes.length > 1) {
        console.warn("AG Grid: cannot range select while selecting multiple rows");
        return 0;
      }
      let toNode = null;
      if (source === "checkboxSelected" && newValue === false && this.lastRowNode) {
        if (this.lastRowNode.id) {
          toNode = this.lastRowNode;
        } else {
          this.lastRowNode = null;
        }
      }
      if (toNode == null) {
        toNode = this.getLastSelectedNode();
      }
      if (toNode) {
        const fromNode = filteredNodes[0];
        const newRowClicked = fromNode !== toNode;
        if (newRowClicked && this.isMultiselect()) {
          return this.selectRange(fromNode, toNode, newValue, source);
        }
      }
    }
    this.lastRowNode = newValue ? null : filteredNodes[0];
    let updatedCount = 0;
    for (let i = 0; i < filteredNodes.length; i++) {
      const node = filteredNodes[i];
      const skipThisNode = groupSelectsFiltered && node.group;
      if (!skipThisNode) {
        const thisNodeWasSelected = node.selectThisNode(newValue, event, source);
        if (thisNodeWasSelected) {
          updatedCount++;
        }
      }
      if (this.groupSelectsChildren && ((_a = node.childrenAfterGroup) == null ? void 0 : _a.length)) {
        updatedCount += this.selectChildren(node, newValue, groupSelectsFiltered, source);
      }
    }
    if (!suppressFinishActions) {
      const clearOtherNodes = newValue && (clearSelection || !this.isMultiselect());
      if (clearOtherNodes) {
        updatedCount += this.clearOtherNodes(filteredNodes[0], source);
      }
      if (updatedCount > 0) {
        this.updateGroupsFromChildrenSelections(source);
        const event2 = {
          type: Events.EVENT_SELECTION_CHANGED,
          source
        };
        this.eventService.dispatchEvent(event2);
      }
    }
    return updatedCount;
  }
  // selects all rows between this node and the last selected node (or the top if this is the first selection).
  // not to be mixed up with 'cell range selection' where you drag the mouse, this is row range selection, by
  // holding down 'shift'.
  selectRange(fromNode, toNode, value = true, source) {
    const nodesToSelect = this.rowModel.getNodesInRangeForSelection(fromNode, toNode);
    let updatedCount = 0;
    nodesToSelect.forEach((rowNode) => {
      if (rowNode.group && this.groupSelectsChildren) {
        return;
      }
      const nodeWasSelected = rowNode.selectThisNode(value, void 0, source);
      if (nodeWasSelected) {
        updatedCount++;
      }
    });
    this.updateGroupsFromChildrenSelections(source);
    const event = {
      type: Events.EVENT_SELECTION_CHANGED,
      source
    };
    this.eventService.dispatchEvent(event);
    return updatedCount;
  }
  selectChildren(node, newValue, groupSelectsFiltered, source) {
    const children = groupSelectsFiltered ? node.childrenAfterAggFilter : node.childrenAfterGroup;
    if (missing(children)) {
      return 0;
    }
    return this.setNodesSelected({
      newValue,
      clearSelection: false,
      suppressFinishActions: true,
      groupSelectsFiltered,
      source,
      nodes: children
    });
  }
  getLastSelectedNode() {
    const selectedKeys = Array.from(this.selectedNodes.keys());
    if (selectedKeys.length == 0) {
      return null;
    }
    const node = this.selectedNodes.get(last(selectedKeys));
    if (node) {
      return node;
    }
    return null;
  }
  getSelectedNodes() {
    const selectedNodes = [];
    this.selectedNodes.forEach((rowNode) => {
      if (rowNode) {
        selectedNodes.push(rowNode);
      }
    });
    return selectedNodes;
  }
  getSelectedRows() {
    const selectedRows = [];
    this.selectedNodes.forEach((rowNode) => {
      if (rowNode && rowNode.data) {
        selectedRows.push(rowNode.data);
      }
    });
    return selectedRows;
  }
  getSelectionCount() {
    return this.selectedNodes.size;
  }
  /**
   * This method is used by the CSRM to remove groups which are being disposed of,
   * events do not need fired in this case
   */
  filterFromSelection(predicate) {
    const newSelectedNodes = /* @__PURE__ */ new Map();
    this.selectedNodes.forEach((rowNode, key) => {
      const passesPredicate = rowNode && predicate(rowNode);
      if (passesPredicate) {
        newSelectedNodes.set(key, rowNode);
      }
    });
    this.selectedNodes = newSelectedNodes;
  }
  // should only be called if groupSelectsChildren=true
  updateGroupsFromChildrenSelections(source, changedPath) {
    if (!this.groupSelectsChildren) {
      return false;
    }
    if (this.rowModel.getType() !== "clientSide") {
      return false;
    }
    const clientSideRowModel = this.rowModel;
    const rootNode = clientSideRowModel.getRootNode();
    if (!changedPath) {
      changedPath = new ChangedPath(true, rootNode);
      changedPath.setInactive();
    }
    let selectionChanged = false;
    changedPath.forEachChangedNodeDepthFirst((rowNode) => {
      if (rowNode !== rootNode) {
        const selected = rowNode.calculateSelectedFromChildren();
        selectionChanged = rowNode.selectThisNode(selected === null ? false : selected, void 0, source) || selectionChanged;
      }
    });
    return selectionChanged;
  }
  clearOtherNodes(rowNodeToKeepSelected, source) {
    const groupsToRefresh = /* @__PURE__ */ new Map();
    let updatedCount = 0;
    this.selectedNodes.forEach((otherRowNode) => {
      if (otherRowNode && otherRowNode.id !== rowNodeToKeepSelected.id) {
        const rowNode = this.selectedNodes.get(otherRowNode.id);
        updatedCount += rowNode.setSelectedParams({
          newValue: false,
          clearSelection: false,
          suppressFinishActions: true,
          source
        });
        if (this.groupSelectsChildren && otherRowNode.parent) {
          groupsToRefresh.set(otherRowNode.parent.id, otherRowNode.parent);
        }
      }
    });
    groupsToRefresh.forEach((group) => {
      const selected = group.calculateSelectedFromChildren();
      group.selectThisNode(selected === null ? false : selected, void 0, source);
    });
    return updatedCount;
  }
  onRowSelected(event) {
    const rowNode = event.node;
    if (this.groupSelectsChildren && rowNode.group) {
      return;
    }
    if (rowNode.isSelected()) {
      this.selectedNodes.set(rowNode.id, rowNode);
    } else {
      this.selectedNodes.delete(rowNode.id);
    }
  }
  syncInRowNode(rowNode, oldNode) {
    this.syncInOldRowNode(rowNode, oldNode);
    this.syncInNewRowNode(rowNode);
  }
  // if the id has changed for the node, then this means the rowNode
  // is getting used for a different data item, which breaks
  // our selectedNodes, as the node now is mapped by the old id
  // which is inconsistent. so to keep the old node as selected,
  // we swap in the clone (with the old id and old data). this means
  // the oldNode is effectively a daemon we keep a reference to,
  // so if client calls api.getSelectedNodes(), it gets the daemon
  // in the result. when the client un-selects, the reference to the
  // daemon is removed. the daemon, because it's an oldNode, is not
  // used by the grid for rendering, it's a copy of what the node used
  // to be like before the id was changed.
  syncInOldRowNode(rowNode, oldNode) {
    const oldNodeHasDifferentId = exists(oldNode) && rowNode.id !== oldNode.id;
    if (oldNodeHasDifferentId && oldNode) {
      const id = oldNode.id;
      const oldNodeSelected = this.selectedNodes.get(id) == rowNode;
      if (oldNodeSelected) {
        this.selectedNodes.set(oldNode.id, oldNode);
      }
    }
  }
  syncInNewRowNode(rowNode) {
    if (this.selectedNodes.has(rowNode.id)) {
      rowNode.setSelectedInitialValue(true);
      this.selectedNodes.set(rowNode.id, rowNode);
    } else {
      rowNode.setSelectedInitialValue(false);
    }
  }
  reset(source) {
    const selectionCount = this.getSelectionCount();
    this.resetNodes();
    if (selectionCount) {
      const event = {
        type: Events.EVENT_SELECTION_CHANGED,
        source
      };
      this.eventService.dispatchEvent(event);
    }
  }
  resetNodes() {
    var _a;
    (_a = this.selectedNodes) == null ? void 0 : _a.clear();
  }
  // returns a list of all nodes at 'best cost' - a feature to be used
  // with groups / trees. if a group has all it's children selected,
  // then the group appears in the result, but not the children.
  // Designed for use with 'children' as the group selection type,
  // where groups don't actually appear in the selection normally.
  getBestCostNodeSelection() {
    if (this.rowModel.getType() !== "clientSide") {
      return;
    }
    const clientSideRowModel = this.rowModel;
    const topLevelNodes = clientSideRowModel.getTopLevelNodes();
    if (topLevelNodes === null) {
      return;
    }
    const result = [];
    function traverse(nodes) {
      for (let i = 0, l = nodes.length; i < l; i++) {
        const node = nodes[i];
        if (node.isSelected()) {
          result.push(node);
        } else {
          const maybeGroup = node;
          if (maybeGroup.group && maybeGroup.children) {
            traverse(maybeGroup.children);
          }
        }
      }
    }
    traverse(topLevelNodes);
    return result;
  }
  isEmpty() {
    let count = 0;
    this.selectedNodes.forEach((rowNode) => {
      if (rowNode) {
        count++;
      }
    });
    return count === 0;
  }
  deselectAllRowNodes(params) {
    const callback = (rowNode) => rowNode.selectThisNode(false, void 0, source);
    const rowModelClientSide = this.rowModel.getType() === "clientSide";
    const { source, justFiltered, justCurrentPage } = params;
    if (justCurrentPage || justFiltered) {
      if (!rowModelClientSide) {
        console.error("AG Grid: selecting just filtered only works when gridOptions.rowModelType='clientSide'");
        return;
      }
      this.getNodesToSelect(justFiltered, justCurrentPage).forEach(callback);
    } else {
      this.selectedNodes.forEach((rowNode) => {
        if (rowNode) {
          callback(rowNode);
        }
      });
      this.reset(source);
    }
    if (rowModelClientSide && this.groupSelectsChildren) {
      this.updateGroupsFromChildrenSelections(source);
    }
    const event = {
      type: Events.EVENT_SELECTION_CHANGED,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  getSelectedCounts(justFiltered, justCurrentPage) {
    let selectedCount = 0;
    let notSelectedCount = 0;
    const callback = (node) => {
      if (this.groupSelectsChildren && node.group) {
        return;
      }
      if (node.isSelected()) {
        selectedCount++;
      } else if (!node.selectable) {
      } else {
        notSelectedCount++;
      }
    };
    this.getNodesToSelect(justFiltered, justCurrentPage).forEach(callback);
    return { selectedCount, notSelectedCount };
  }
  getSelectAllState(justFiltered, justCurrentPage) {
    const { selectedCount, notSelectedCount } = this.getSelectedCounts(justFiltered, justCurrentPage);
    if (selectedCount === 0 && notSelectedCount === 0) {
      return false;
    }
    if (selectedCount > 0 && notSelectedCount > 0) {
      return null;
    }
    return selectedCount > 0;
  }
  hasNodesToSelect(justFiltered = false, justCurrentPage = false) {
    return this.getNodesToSelect(justFiltered, justCurrentPage).filter((node) => node.selectable).length > 0;
  }
  /**
   * @param justFiltered whether to just include nodes which have passed the filter
   * @param justCurrentPage whether to just include nodes on the current page
   * @returns all nodes including unselectable nodes which are the target of this selection attempt
   */
  getNodesToSelect(justFiltered = false, justCurrentPage = false) {
    if (this.rowModel.getType() !== "clientSide") {
      throw new Error(`selectAll only available when rowModelType='clientSide', ie not ${this.rowModel.getType()}`);
    }
    const nodes = [];
    if (justCurrentPage) {
      this.paginationProxy.forEachNodeOnPage((node) => {
        if (!node.group) {
          nodes.push(node);
          return;
        }
        if (!node.expanded) {
          const recursivelyAddChildren = (child) => {
            var _a;
            nodes.push(child);
            if ((_a = child.childrenAfterFilter) == null ? void 0 : _a.length) {
              child.childrenAfterFilter.forEach(recursivelyAddChildren);
            }
          };
          recursivelyAddChildren(node);
          return;
        }
        if (!this.groupSelectsChildren) {
          nodes.push(node);
        }
      });
      return nodes;
    }
    const clientSideRowModel = this.rowModel;
    if (justFiltered) {
      clientSideRowModel.forEachNodeAfterFilter((node) => {
        nodes.push(node);
      });
      return nodes;
    }
    clientSideRowModel.forEachNode((node) => {
      nodes.push(node);
    });
    return nodes;
  }
  selectAllRowNodes(params) {
    if (this.rowModel.getType() !== "clientSide") {
      throw new Error(`selectAll only available when rowModelType='clientSide', ie not ${this.rowModel.getType()}`);
    }
    const { source, justFiltered, justCurrentPage } = params;
    const callback = (rowNode) => rowNode.selectThisNode(true, void 0, source);
    this.getNodesToSelect(justFiltered, justCurrentPage).forEach(callback);
    if (this.rowModel.getType() === "clientSide" && this.groupSelectsChildren) {
      this.updateGroupsFromChildrenSelections(source);
    }
    const event = {
      type: Events.EVENT_SELECTION_CHANGED,
      source
    };
    this.eventService.dispatchEvent(event);
  }
  getSelectionState() {
    const selectedIds = [];
    this.selectedNodes.forEach((node) => {
      if (node == null ? void 0 : node.id) {
        selectedIds.push(node.id);
      }
    });
    return selectedIds.length ? selectedIds : null;
  }
  setSelectionState(state, source) {
    if (!Array.isArray(state)) {
      return;
    }
    const rowIds = new Set(state);
    const nodes = [];
    this.rowModel.forEachNode((node) => {
      if (rowIds.has(node.id)) {
        nodes.push(node);
      }
    });
    this.setNodesSelected({
      newValue: true,
      nodes,
      source
    });
  }
};
__decorateClass([
  Autowired("rowModel")
], SelectionService.prototype, "rowModel", 2);
__decorateClass([
  Autowired("paginationProxy")
], SelectionService.prototype, "paginationProxy", 2);
__decorateClass([
  PostConstruct
], SelectionService.prototype, "init", 1);
SelectionService = __decorateClass([
  Bean("selectionService")
], SelectionService);

// community-modules/core/src/columns/columnApi.ts
var ColumnApi = class {
  constructor(gridAp) {
    this.viaApi = (funcName, ...args) => {
      warnOnce(`Since v31, 'columnApi.${funcName}' is deprecated and moved to 'api.${funcName}'.`);
      return this.api[funcName](...args);
    };
    this.api = gridAp;
  }
  /** @deprecated v31 use `api.sizeColumnsToFit()` instead.   */
  sizeColumnsToFit(gridWidth) {
    this.viaApi("sizeColumnsToFit", gridWidth);
  }
  /** @deprecated v31 use `api.setColumnGroupOpened() instead. */
  setColumnGroupOpened(group, newValue) {
    this.viaApi("setColumnGroupOpened", group, newValue);
  }
  /** @deprecated v31 use `api.getColumnGroup() instead. */
  getColumnGroup(name, instanceId) {
    return this.viaApi("getColumnGroup", name, instanceId);
  }
  /** @deprecated v31 use `api.getProvidedColumnGroup() instead. */
  getProvidedColumnGroup(name) {
    return this.viaApi("getProvidedColumnGroup", name);
  }
  /** @deprecated v31 use `api.getDisplayNameForColumn() instead. */
  getDisplayNameForColumn(column, location) {
    return this.viaApi("getDisplayNameForColumn", column, location);
  }
  /** @deprecated v31 use `api.getDisplayNameForColumnGroup() instead. */
  getDisplayNameForColumnGroup(columnGroup, location) {
    return this.viaApi("getDisplayNameForColumnGroup", columnGroup, location);
  }
  /** @deprecated v31 use `api.getColumn() instead. */
  getColumn(key) {
    return this.viaApi("getColumn", key);
  }
  /** @deprecated v31 use `api.getColumns() instead. */
  getColumns() {
    return this.viaApi("getColumns");
  }
  /** @deprecated v31 use `api.applyColumnState() instead. */
  applyColumnState(params) {
    return this.viaApi("applyColumnState", params);
  }
  /** @deprecated v31 use `api.getColumnState() instead. */
  getColumnState() {
    return this.viaApi("getColumnState");
  }
  /** @deprecated v31 use `api.resetColumnState() instead. */
  resetColumnState() {
    this.viaApi("resetColumnState");
  }
  /** @deprecated v31 use `api.getColumnGroupState() instead. */
  getColumnGroupState() {
    return this.viaApi("getColumnGroupState");
  }
  /** @deprecated v31 use `api.setColumnGroupState() instead. */
  setColumnGroupState(stateItems) {
    this.viaApi("setColumnGroupState", stateItems);
  }
  /** @deprecated v31 use `api.resetColumnGroupState() instead. */
  resetColumnGroupState() {
    this.viaApi("resetColumnGroupState");
  }
  /** @deprecated v31 use `api.isPinning() instead. */
  isPinning() {
    return this.viaApi("isPinning");
  }
  /** @deprecated v31 use `api.isPinningLeft() instead. */
  isPinningLeft() {
    return this.viaApi("isPinningLeft");
  }
  /** @deprecated v31 use `api.isPinningRight() instead. */
  isPinningRight() {
    return this.viaApi("isPinningRight");
  }
  /** @deprecated v31 use `api.getDisplayedColAfter() instead. */
  getDisplayedColAfter(col) {
    return this.viaApi("getDisplayedColAfter", col);
  }
  /** @deprecated v31 use `api.getDisplayedColBefore() instead. */
  getDisplayedColBefore(col) {
    return this.viaApi("getDisplayedColBefore", col);
  }
  /** @deprecated v31 use `api.setColumnVisible() instead. */
  setColumnVisible(key, visible) {
    this.viaApi("setColumnVisible", key, visible);
  }
  /** @deprecated v31 use `api.setColumnsVisible() instead. */
  setColumnsVisible(keys2, visible) {
    this.viaApi("setColumnsVisible", keys2, visible);
  }
  /** @deprecated v31 use `api.setColumnPinned() instead. */
  setColumnPinned(key, pinned) {
    this.viaApi("setColumnPinned", key, pinned);
  }
  /** @deprecated v31 use `api.setColumnsPinned() instead. */
  setColumnsPinned(keys2, pinned) {
    this.viaApi("setColumnsPinned", keys2, pinned);
  }
  /** @deprecated v31 use `api.getAllGridColumns() instead. */
  getAllGridColumns() {
    return this.viaApi("getAllGridColumns");
  }
  /** @deprecated v31 use `api.getDisplayedLeftColumns() instead. */
  getDisplayedLeftColumns() {
    return this.viaApi("getDisplayedLeftColumns");
  }
  /** @deprecated v31 use `api.getDisplayedCenterColumns() instead. */
  getDisplayedCenterColumns() {
    return this.viaApi("getDisplayedCenterColumns");
  }
  /** @deprecated v31 use `api.getDisplayedRightColumns() instead. */
  getDisplayedRightColumns() {
    return this.viaApi("getDisplayedRightColumns");
  }
  /** @deprecated v31 use `api.getAllDisplayedColumns() instead. */
  getAllDisplayedColumns() {
    return this.viaApi("getAllDisplayedColumns");
  }
  /** @deprecated v31 use `api.getAllDisplayedVirtualColumns() instead. */
  getAllDisplayedVirtualColumns() {
    return this.viaApi("getAllDisplayedVirtualColumns");
  }
  /** @deprecated v31 use `api.moveColumn() instead. */
  moveColumn(key, toIndex) {
    this.viaApi("moveColumn", key, toIndex);
  }
  /** @deprecated v31 use `api.moveColumnByIndex() instead. */
  moveColumnByIndex(fromIndex, toIndex) {
    this.viaApi("moveColumnByIndex", fromIndex, toIndex);
  }
  /** @deprecated v31 use `api.moveColumns() instead. */
  moveColumns(columnsToMoveKeys, toIndex) {
    this.viaApi("moveColumns", columnsToMoveKeys, toIndex);
  }
  /** @deprecated v31 use `api.moveRowGroupColumn() instead. */
  moveRowGroupColumn(fromIndex, toIndex) {
    this.viaApi("moveRowGroupColumn", fromIndex, toIndex);
  }
  /** @deprecated v31 use `api.setColumnAggFunc() instead. */
  setColumnAggFunc(key, aggFunc) {
    this.viaApi("setColumnAggFunc", key, aggFunc);
  }
  /** @deprecated v31 use `api.setColumnWidth() instead. */
  setColumnWidth(key, newWidth, finished = true, source) {
    this.viaApi("setColumnWidth", key, newWidth, finished, source);
  }
  /** @deprecated v31 use `api.setColumnWidths() instead. */
  setColumnWidths(columnWidths, finished = true, source) {
    this.viaApi("setColumnWidths", columnWidths, finished, source);
  }
  /** @deprecated v31 use `api.setPivotMode() instead. */
  setPivotMode(pivotMode) {
    this.viaApi("setPivotMode", pivotMode);
  }
  /** @deprecated v31 use `api.isPivotMode() instead. */
  isPivotMode() {
    return this.viaApi("isPivotMode");
  }
  /** @deprecated v31 use `api.getPivotResultColumn() instead. */
  getPivotResultColumn(pivotKeys, valueColKey) {
    return this.viaApi("getPivotResultColumn", pivotKeys, valueColKey);
  }
  /** @deprecated v31 use `api.setValueColumns() instead. */
  setValueColumns(colKeys) {
    this.viaApi("setValueColumns", colKeys);
  }
  /** @deprecated v31 use `api.getValueColumns() instead. */
  getValueColumns() {
    return this.viaApi("getValueColumns");
  }
  /** @deprecated v31 use `api.removeValueColumn() instead. */
  removeValueColumn(colKey) {
    this.viaApi("removeValueColumn", colKey);
  }
  /** @deprecated v31 use `api.removeValueColumns() instead. */
  removeValueColumns(colKeys) {
    this.viaApi("removeValueColumns", colKeys);
  }
  /** @deprecated v31 use `api.addValueColumn() instead. */
  addValueColumn(colKey) {
    this.viaApi("addValueColumn", colKey);
  }
  /** @deprecated v31 use `api.addValueColumns() instead. */
  addValueColumns(colKeys) {
    this.viaApi("addValueColumns", colKeys);
  }
  /** @deprecated v31 use `api.setRowGroupColumns() instead. */
  setRowGroupColumns(colKeys) {
    this.viaApi("setRowGroupColumns", colKeys);
  }
  /** @deprecated v31 use `api.removeRowGroupColumn() instead. */
  removeRowGroupColumn(colKey) {
    this.viaApi("removeRowGroupColumn", colKey);
  }
  /** @deprecated v31 use `api.removeRowGroupColumns() instead. */
  removeRowGroupColumns(colKeys) {
    this.viaApi("removeRowGroupColumns", colKeys);
  }
  /** @deprecated v31 use `api.addRowGroupColumn() instead. */
  addRowGroupColumn(colKey) {
    this.viaApi("addRowGroupColumn", colKey);
  }
  /** @deprecated v31 use `api.addRowGroupColumns() instead. */
  addRowGroupColumns(colKeys) {
    this.viaApi("addRowGroupColumns", colKeys);
  }
  /** @deprecated v31 use `api.getRowGroupColumns() instead. */
  getRowGroupColumns() {
    return this.viaApi("getRowGroupColumns");
  }
  /** @deprecated v31 use `api.setPivotColumns() instead. */
  setPivotColumns(colKeys) {
    this.viaApi("setPivotColumns", colKeys);
  }
  /** @deprecated v31 use `api.removePivotColumn() instead. */
  removePivotColumn(colKey) {
    this.viaApi("removePivotColumn", colKey);
  }
  /** @deprecated v31 use `api.removePivotColumns() instead. */
  removePivotColumns(colKeys) {
    this.viaApi("removePivotColumns", colKeys);
  }
  /** @deprecated v31 use `api.addPivotColumn() instead. */
  addPivotColumn(colKey) {
    this.viaApi("addPivotColumn", colKey);
  }
  /** @deprecated v31 use `api.addPivotColumns() instead. */
  addPivotColumns(colKeys) {
    this.viaApi("addPivotColumns", colKeys);
  }
  /** @deprecated v31 use `api.getPivotColumns() instead. */
  getPivotColumns() {
    return this.viaApi("getPivotColumns");
  }
  /** @deprecated v31 use `api.getLeftDisplayedColumnGroups() instead. */
  getLeftDisplayedColumnGroups() {
    return this.viaApi("getLeftDisplayedColumnGroups");
  }
  /** @deprecated v31 use `api.getCenterDisplayedColumnGroups() instead. */
  getCenterDisplayedColumnGroups() {
    return this.viaApi("getCenterDisplayedColumnGroups");
  }
  /** @deprecated v31 use `api.getRightDisplayedColumnGroups() instead. */
  getRightDisplayedColumnGroups() {
    return this.viaApi("getRightDisplayedColumnGroups");
  }
  /** @deprecated v31 use `api.getAllDisplayedColumnGroups() instead. */
  getAllDisplayedColumnGroups() {
    return this.viaApi("getAllDisplayedColumnGroups");
  }
  /** @deprecated v31 use `api.autoSizeColumn() instead. */
  autoSizeColumn(key, skipHeader) {
    return this.viaApi("autoSizeColumn", key, skipHeader);
  }
  /** @deprecated v31 use `api.autoSizeColumns() instead. */
  autoSizeColumns(keys2, skipHeader) {
    this.viaApi("autoSizeColumns", keys2, skipHeader);
  }
  /** @deprecated v31 use `api.autoSizeAllColumns() instead. */
  autoSizeAllColumns(skipHeader) {
    this.viaApi("autoSizeAllColumns", skipHeader);
  }
  /** @deprecated v31 use `api.setPivotResultColumns() instead. */
  setPivotResultColumns(colDefs) {
    this.viaApi("setPivotResultColumns", colDefs);
  }
  /** @deprecated v31 use `api.getPivotResultColumns() instead. */
  getPivotResultColumns() {
    return this.viaApi("getPivotResultColumns");
  }
};
__decorateClass([
  Autowired("gridApi")
], ColumnApi.prototype, "api", 2);
ColumnApi = __decorateClass([
  Bean("columnApi")
], ColumnApi);

// community-modules/core/src/valueService/valueService.ts
var ValueService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.initialised = false;
    this.isSsrm = false;
  }
  init() {
    this.isSsrm = this.gos.isRowModelType("serverSide");
    this.cellExpressions = this.gos.get("enableCellExpressions");
    this.isTreeData = this.gos.get("treeData");
    this.initialised = true;
    const listener = (event) => this.callColumnCellValueChangedHandler(event);
    const async = this.gos.useAsyncEvents();
    this.eventService.addEventListener(Events.EVENT_CELL_VALUE_CHANGED, listener, async);
    this.addDestroyFunc(() => this.eventService.removeEventListener(Events.EVENT_CELL_VALUE_CHANGED, listener, async));
    this.addManagedPropertyListener("treeData", (propChange) => this.isTreeData = propChange.currentValue);
  }
  getValue(column, rowNode, forFilter = false, ignoreAggData = false) {
    if (!this.initialised) {
      this.init();
    }
    if (!rowNode) {
      return;
    }
    const colDef = column.getColDef();
    const field = colDef.field;
    const colId = column.getColId();
    const data = rowNode.data;
    let result;
    const groupDataExists = rowNode.groupData && rowNode.groupData[colId] !== void 0;
    const aggDataExists = !ignoreAggData && rowNode.aggData && rowNode.aggData[colId] !== void 0;
    const ignoreSsrmAggData = this.isSsrm && ignoreAggData && !!column.getColDef().aggFunc;
    const ssrmFooterGroupCol = this.isSsrm && rowNode.footer && rowNode.field && (column.getColDef().showRowGroup === true || column.getColDef().showRowGroup === rowNode.field);
    if (forFilter && colDef.filterValueGetter) {
      result = this.executeFilterValueGetter(colDef.filterValueGetter, data, column, rowNode);
    } else if (this.isTreeData && aggDataExists) {
      result = rowNode.aggData[colId];
    } else if (this.isTreeData && colDef.valueGetter) {
      result = this.executeValueGetter(colDef.valueGetter, data, column, rowNode);
    } else if (this.isTreeData && (field && data)) {
      result = getValueUsingField(data, field, column.isFieldContainsDots());
    } else if (groupDataExists) {
      result = rowNode.groupData[colId];
    } else if (aggDataExists) {
      result = rowNode.aggData[colId];
    } else if (colDef.valueGetter) {
      result = this.executeValueGetter(colDef.valueGetter, data, column, rowNode);
    } else if (ssrmFooterGroupCol) {
      result = getValueUsingField(data, rowNode.field, column.isFieldContainsDots());
    } else if (field && data && !ignoreSsrmAggData) {
      result = getValueUsingField(data, field, column.isFieldContainsDots());
    }
    if (this.cellExpressions && typeof result === "string" && result.indexOf("=") === 0) {
      const cellValueGetter = result.substring(1);
      result = this.executeValueGetter(cellValueGetter, data, column, rowNode);
    }
    if (result == null) {
      const openedGroup = this.getOpenedGroup(rowNode, column);
      if (openedGroup != null) {
        return openedGroup;
      }
    }
    return result;
  }
  parseValue(column, rowNode, newValue, oldValue) {
    const colDef = column.getColDef();
    const params = this.gos.addGridCommonParams({
      node: rowNode,
      data: rowNode == null ? void 0 : rowNode.data,
      oldValue,
      newValue,
      colDef,
      column
    });
    const valueParser = colDef.valueParser;
    if (exists(valueParser)) {
      if (typeof valueParser === "function") {
        return valueParser(params);
      }
      return this.expressionService.evaluate(valueParser, params);
    }
    return newValue;
  }
  formatValue(column, node, value, suppliedFormatter, useFormatterFromColumn = true) {
    let result = null;
    let formatter;
    const colDef = column.getColDef();
    if (suppliedFormatter) {
      formatter = suppliedFormatter;
    } else if (useFormatterFromColumn) {
      formatter = colDef.valueFormatter;
    }
    if (formatter) {
      const params = this.gos.addGridCommonParams({
        value,
        node,
        data: node ? node.data : null,
        colDef,
        column
      });
      if (typeof formatter === "function") {
        result = formatter(params);
      } else {
        result = this.expressionService.evaluate(formatter, params);
      }
    } else if (colDef.refData) {
      return colDef.refData[value] || "";
    }
    if (result == null && Array.isArray(value)) {
      result = value.join(", ");
    }
    return result;
  }
  getOpenedGroup(rowNode, column) {
    if (!this.gos.get("showOpenedGroup")) {
      return;
    }
    const colDef = column.getColDef();
    if (!colDef.showRowGroup) {
      return;
    }
    const showRowGroup = column.getColDef().showRowGroup;
    let pointer = rowNode.parent;
    while (pointer != null) {
      if (pointer.rowGroupColumn && (showRowGroup === true || showRowGroup === pointer.rowGroupColumn.getColId())) {
        return pointer.key;
      }
      pointer = pointer.parent;
    }
    return void 0;
  }
  /**
   * Sets the value of a GridCell
   * @param rowNode The `RowNode` to be updated
   * @param colKey The `Column` to be updated
   * @param newValue The new value to be set
   * @param eventSource The event source
   * @returns `True` if the value has been updated, otherwise`False`.
   */
  setValue(rowNode, colKey, newValue, eventSource) {
    const column = this.columnModel.getPrimaryColumn(colKey);
    if (!rowNode || !column) {
      return false;
    }
    if (missing(rowNode.data)) {
      rowNode.data = {};
    }
    const { field, valueSetter } = column.getColDef();
    if (missing(field) && missing(valueSetter)) {
      console.warn(`AG Grid: you need either field or valueSetter set on colDef for editing to work`);
      return false;
    }
    if (!this.dataTypeService.checkType(column, newValue)) {
      console.warn(`AG Grid: Data type of the new value does not match the cell data type of the column`);
      return false;
    }
    const params = this.gos.addGridCommonParams({
      node: rowNode,
      data: rowNode.data,
      oldValue: this.getValue(column, rowNode),
      newValue,
      colDef: column.getColDef(),
      column
    });
    params.newValue = newValue;
    let valueWasDifferent;
    if (exists(valueSetter)) {
      if (typeof valueSetter === "function") {
        valueWasDifferent = valueSetter(params);
      } else {
        valueWasDifferent = this.expressionService.evaluate(valueSetter, params);
      }
    } else {
      valueWasDifferent = this.setValueUsingField(rowNode.data, field, newValue, column.isFieldContainsDots());
    }
    if (valueWasDifferent === void 0) {
      valueWasDifferent = true;
    }
    if (!valueWasDifferent) {
      return false;
    }
    rowNode.resetQuickFilterAggregateText();
    this.valueCache.onDataChanged();
    params.newValue = this.getValue(column, rowNode);
    const event = {
      type: Events.EVENT_CELL_VALUE_CHANGED,
      event: null,
      rowIndex: rowNode.rowIndex,
      rowPinned: rowNode.rowPinned,
      column: params.column,
      api: params.api,
      columnApi: params.columnApi,
      colDef: params.colDef,
      context: params.context,
      data: rowNode.data,
      node: rowNode,
      oldValue: params.oldValue,
      newValue: params.newValue,
      value: params.newValue,
      source: eventSource
    };
    this.eventService.dispatchEvent(event);
    return true;
  }
  callColumnCellValueChangedHandler(event) {
    const onCellValueChanged = event.colDef.onCellValueChanged;
    if (typeof onCellValueChanged === "function") {
      this.getFrameworkOverrides().wrapOutgoing(() => {
        onCellValueChanged({
          node: event.node,
          data: event.data,
          oldValue: event.oldValue,
          newValue: event.newValue,
          colDef: event.colDef,
          column: event.column,
          api: event.api,
          columnApi: event.columnApi,
          context: event.context
        });
      });
    }
  }
  setValueUsingField(data, field, newValue, isFieldContainsDots) {
    if (!field) {
      return false;
    }
    let valuesAreSame = false;
    if (!isFieldContainsDots) {
      valuesAreSame = data[field] === newValue;
      if (!valuesAreSame) {
        data[field] = newValue;
      }
    } else {
      const fieldPieces = field.split(".");
      let currentObject = data;
      while (fieldPieces.length > 0 && currentObject) {
        const fieldPiece = fieldPieces.shift();
        if (fieldPieces.length === 0) {
          valuesAreSame = currentObject[fieldPiece] === newValue;
          if (!valuesAreSame) {
            currentObject[fieldPiece] = newValue;
          }
        } else {
          currentObject = currentObject[fieldPiece];
        }
      }
    }
    return !valuesAreSame;
  }
  executeFilterValueGetter(valueGetter, data, column, rowNode) {
    const params = this.gos.addGridCommonParams({
      data,
      node: rowNode,
      column,
      colDef: column.getColDef(),
      getValue: this.getValueCallback.bind(this, rowNode)
    });
    if (typeof valueGetter === "function") {
      return valueGetter(params);
    }
    return this.expressionService.evaluate(valueGetter, params);
  }
  executeValueGetter(valueGetter, data, column, rowNode) {
    const colId = column.getColId();
    const valueFromCache = this.valueCache.getValue(rowNode, colId);
    if (valueFromCache !== void 0) {
      return valueFromCache;
    }
    const params = this.gos.addGridCommonParams({
      data,
      node: rowNode,
      column,
      colDef: column.getColDef(),
      getValue: this.getValueCallback.bind(this, rowNode)
    });
    let result;
    if (typeof valueGetter === "function") {
      result = valueGetter(params);
    } else {
      result = this.expressionService.evaluate(valueGetter, params);
    }
    this.valueCache.setValue(rowNode, colId, result);
    return result;
  }
  getValueCallback(node, field) {
    const otherColumn = this.columnModel.getPrimaryColumn(field);
    if (otherColumn) {
      return this.getValue(otherColumn, node);
    }
    return null;
  }
  // used by row grouping and pivot, to get key for a row. col can be a pivot col or a row grouping col
  getKeyForNode(col, rowNode) {
    const value = this.getValue(col, rowNode);
    const keyCreator = col.getColDef().keyCreator;
    let result = value;
    if (keyCreator) {
      const keyParams = this.gos.addGridCommonParams({
        value,
        colDef: col.getColDef(),
        column: col,
        node: rowNode,
        data: rowNode.data
      });
      result = keyCreator(keyParams);
    }
    if (typeof result === "string" || result == null) {
      return result;
    }
    result = String(result);
    if (result === "[object Object]") {
      warnOnce("a column you are grouping or pivoting by has objects as values. If you want to group by complex objects then either a) use a colDef.keyCreator (se AG Grid docs) or b) to toString() on the object to return a key");
    }
    return result;
  }
};
__decorateClass([
  Autowired("expressionService")
], ValueService.prototype, "expressionService", 2);
__decorateClass([
  Autowired("columnModel")
], ValueService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("valueCache")
], ValueService.prototype, "valueCache", 2);
__decorateClass([
  Autowired("dataTypeService")
], ValueService.prototype, "dataTypeService", 2);
__decorateClass([
  PostConstruct
], ValueService.prototype, "init", 1);
ValueService = __decorateClass([
  Bean("valueService")
], ValueService);

// community-modules/core/src/valueService/expressionService.ts
var ExpressionService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.expressionToFunctionCache = {};
  }
  setBeans(loggerFactory) {
    this.logger = loggerFactory.create("ExpressionService");
  }
  evaluate(expression, params) {
    if (typeof expression === "string") {
      return this.evaluateExpression(expression, params);
    } else {
      console.error("AG Grid: value should be either a string or a function", expression);
    }
  }
  evaluateExpression(expression, params) {
    try {
      const javaScriptFunction = this.createExpressionFunction(expression);
      const result = javaScriptFunction(
        params.value,
        params.context,
        params.oldValue,
        params.newValue,
        params.value,
        params.node,
        params.data,
        params.colDef,
        params.rowIndex,
        params.api,
        params.columnApi,
        params.getValue,
        params.column,
        params.columnGroup
      );
      return result;
    } catch (e) {
      console.log("Processing of the expression failed");
      console.log("Expression = " + expression);
      console.log("Params =", params);
      console.log("Exception = " + e);
      return null;
    }
  }
  createExpressionFunction(expression) {
    if (this.expressionToFunctionCache[expression]) {
      return this.expressionToFunctionCache[expression];
    }
    const functionBody = this.createFunctionBody(expression);
    const theFunction = new Function("x, ctx, oldValue, newValue, value, node, data, colDef, rowIndex, api, columnApi, getValue, column, columnGroup", functionBody);
    this.expressionToFunctionCache[expression] = theFunction;
    return theFunction;
  }
  createFunctionBody(expression) {
    if (expression.indexOf("return") >= 0) {
      return expression;
    } else {
      return "return " + expression + ";";
    }
  }
};
__decorateClass([
  __decorateParam(0, Qualifier("loggerFactory"))
], ExpressionService.prototype, "setBeans", 1);
ExpressionService = __decorateClass([
  Bean("expressionService")
], ExpressionService);

// community-modules/core/src/logger.ts
var LoggerFactory = class extends BeanStub {
  setBeans(gos) {
    this.logging = gos.get("debug");
  }
  create(name) {
    return new Logger(name, this.isLogging.bind(this));
  }
  isLogging() {
    return this.logging;
  }
};
__decorateClass([
  __decorateParam(0, Qualifier("gridOptionsService"))
], LoggerFactory.prototype, "setBeans", 1);
LoggerFactory = __decorateClass([
  Bean("loggerFactory")
], LoggerFactory);
var Logger = class {
  constructor(name, isLoggingFunc) {
    this.name = name;
    this.isLoggingFunc = isLoggingFunc;
  }
  isLogging() {
    return this.isLoggingFunc();
  }
  log(message) {
    if (this.isLoggingFunc()) {
      console.log("AG Grid." + this.name + ": " + message);
    }
  }
};

// community-modules/core/src/gridComp/gridCtrl.ts
var GridCtrl = class extends BeanStub {
  setComp(view, eGridDiv, eGui) {
    this.view = view;
    this.eGridHostDiv = eGridDiv;
    this.eGui = eGui;
    this.eGui.setAttribute("grid-id", this.context.getGridId());
    this.dragAndDropService.addDropTarget({
      getContainer: () => this.eGui,
      isInterestedIn: (type) => type === 1 /* HeaderCell */ || type === 0 /* ToolPanel */,
      getIconName: () => DragAndDropService.ICON_NOT_ALLOWED
    });
    this.mouseEventService.stampTopLevelGridCompWithGridInstance(eGridDiv);
    this.createManagedBean(new LayoutFeature(this.view));
    this.addRtlSupport();
    const unsubscribeFromResize = this.resizeObserverService.observeResize(
      this.eGridHostDiv,
      this.onGridSizeChanged.bind(this)
    );
    this.addDestroyFunc(() => unsubscribeFromResize());
    this.ctrlsService.register("gridCtrl", this);
  }
  isDetailGrid() {
    var _a;
    const el = this.focusService.findTabbableParent(this.getGui());
    return ((_a = el == null ? void 0 : el.getAttribute("row-id")) == null ? void 0 : _a.startsWith("detail")) || false;
  }
  showDropZones() {
    return ModuleRegistry.__isRegistered("@ag-grid-enterprise/row-grouping" /* RowGroupingModule */, this.context.getGridId());
  }
  showSideBar() {
    return ModuleRegistry.__isRegistered("@ag-grid-enterprise/side-bar" /* SideBarModule */, this.context.getGridId());
  }
  showStatusBar() {
    return ModuleRegistry.__isRegistered("@ag-grid-enterprise/status-bar" /* StatusBarModule */, this.context.getGridId());
  }
  showWatermark() {
    return ModuleRegistry.__isRegistered("@ag-grid-enterprise/core" /* EnterpriseCoreModule */, this.context.getGridId());
  }
  onGridSizeChanged() {
    const event = {
      type: Events.EVENT_GRID_SIZE_CHANGED,
      clientWidth: this.eGridHostDiv.clientWidth,
      clientHeight: this.eGridHostDiv.clientHeight
    };
    this.eventService.dispatchEvent(event);
  }
  addRtlSupport() {
    const cssClass = this.gos.get("enableRtl") ? "ag-rtl" : "ag-ltr";
    this.view.setRtlClass(cssClass);
  }
  destroyGridUi() {
    this.view.destroyGridUi();
  }
  getGui() {
    return this.eGui;
  }
  setResizeCursor(on) {
    this.view.setCursor(on ? "ew-resize" : null);
  }
  disableUserSelect(on) {
    this.view.setUserSelect(on ? "none" : null);
  }
  focusNextInnerContainer(backwards) {
    const focusableContainers = this.view.getFocusableContainers();
    const activeEl = this.gos.getActiveDomElement();
    const idxWithFocus = focusableContainers.findIndex((container) => container.contains(activeEl));
    const nextIdx = idxWithFocus + (backwards ? -1 : 1);
    if (nextIdx <= 0 || nextIdx >= focusableContainers.length) {
      return false;
    }
    return this.focusService.focusInto(focusableContainers[nextIdx]);
  }
  focusInnerElement(fromBottom) {
    const focusableContainers = this.view.getFocusableContainers();
    const allColumns = this.columnModel.getAllDisplayedColumns();
    if (fromBottom) {
      if (focusableContainers.length > 1) {
        return this.focusService.focusInto(last(focusableContainers), true);
      }
      const lastColumn = last(allColumns);
      if (this.focusService.focusGridView(lastColumn, true)) {
        return true;
      }
    }
    if (this.gos.get("headerHeight") === 0 || this.gos.get("suppressHeaderFocus")) {
      if (this.focusService.focusGridView(allColumns[0])) {
        return true;
      }
      for (let i = 1; i < focusableContainers.length; i++) {
        if (this.focusService.focusInto(focusableContainers[i])) {
          return true;
        }
      }
      return false;
    }
    return this.focusService.focusFirstHeader();
  }
  forceFocusOutOfContainer(up = false) {
    this.view.forceFocusOutOfContainer(up);
  }
};
__decorateClass([
  Autowired("focusService")
], GridCtrl.prototype, "focusService", 2);
__decorateClass([
  Autowired("resizeObserverService")
], GridCtrl.prototype, "resizeObserverService", 2);
__decorateClass([
  Autowired("columnModel")
], GridCtrl.prototype, "columnModel", 2);
__decorateClass([
  Autowired("ctrlsService")
], GridCtrl.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("mouseEventService")
], GridCtrl.prototype, "mouseEventService", 2);
__decorateClass([
  Autowired("dragAndDropService")
], GridCtrl.prototype, "dragAndDropService", 2);

// community-modules/core/src/gridComp/gridComp.ts
var GridComp = class extends TabGuardComp {
  constructor(eGridDiv) {
    super();
    this.eGridDiv = eGridDiv;
  }
  postConstruct() {
    this.logger = this.loggerFactory.create("GridComp");
    const compProxy = {
      destroyGridUi: () => this.destroyBean(this),
      setRtlClass: (cssClass) => this.addCssClass(cssClass),
      forceFocusOutOfContainer: this.forceFocusOutOfContainer.bind(this),
      updateLayoutClasses: this.updateLayoutClasses.bind(this),
      getFocusableContainers: this.getFocusableContainers.bind(this),
      setUserSelect: (value) => {
        this.getGui().style.userSelect = value != null ? value : "";
        this.getGui().style.webkitUserSelect = value != null ? value : "";
      },
      setCursor: (value) => {
        this.getGui().style.cursor = value != null ? value : "";
      }
    };
    this.ctrl = this.createManagedBean(new GridCtrl());
    const template = this.createTemplate();
    this.setTemplate(template);
    this.ctrl.setComp(compProxy, this.eGridDiv, this.getGui());
    this.insertGridIntoDom();
    this.initialiseTabGuard({
      // we want to override the default behaviour to do nothing for onTabKeyDown
      onTabKeyDown: () => void 0,
      focusInnerElement: (fromBottom) => this.ctrl.focusInnerElement(fromBottom),
      forceFocusOutWhenTabGuardsAreEmpty: true
    });
  }
  insertGridIntoDom() {
    const eGui = this.getGui();
    this.eGridDiv.appendChild(eGui);
    this.addDestroyFunc(() => {
      this.eGridDiv.removeChild(eGui);
      this.logger.log("Grid removed from DOM");
    });
  }
  updateLayoutClasses(cssClass, params) {
    const eRootWrapperBodyClassList = this.eRootWrapperBody.classList;
    eRootWrapperBodyClassList.toggle("ag-layout-auto-height" /* AUTO_HEIGHT */, params.autoHeight);
    eRootWrapperBodyClassList.toggle("ag-layout-normal" /* NORMAL */, params.normal);
    eRootWrapperBodyClassList.toggle("ag-layout-print" /* PRINT */, params.print);
    this.addOrRemoveCssClass("ag-layout-auto-height" /* AUTO_HEIGHT */, params.autoHeight);
    this.addOrRemoveCssClass("ag-layout-normal" /* NORMAL */, params.normal);
    this.addOrRemoveCssClass("ag-layout-print" /* PRINT */, params.print);
  }
  createTemplate() {
    const dropZones = this.ctrl.showDropZones() ? "<ag-grid-header-drop-zones></ag-grid-header-drop-zones>" : "";
    const sideBar = this.ctrl.showSideBar() ? '<ag-side-bar ref="sideBar"></ag-side-bar>' : "";
    const statusBar = this.ctrl.showStatusBar() ? '<ag-status-bar ref="statusBar"></ag-status-bar>' : "";
    const watermark = this.ctrl.showWatermark() ? "<ag-watermark></ag-watermark>" : "";
    const template = (
      /* html */
      `<div class="ag-root-wrapper" role="presentation">
                ${dropZones}
                <div class="ag-root-wrapper-body" ref="rootWrapperBody" role="presentation">
                    <ag-grid-body ref="gridBody"></ag-grid-body>
                    ${sideBar}
                </div>
                ${statusBar}
                <ag-pagination></ag-pagination>
                ${watermark}
            </div>`
    );
    return template;
  }
  getFocusableElement() {
    return this.eRootWrapperBody;
  }
  getFocusableContainers() {
    const focusableContainers = [
      this.gridBodyComp.getGui()
    ];
    if (this.sideBarComp) {
      focusableContainers.push(
        this.sideBarComp.getGui()
      );
    }
    return focusableContainers.filter((el) => isVisible(el));
  }
};
__decorateClass([
  Autowired("loggerFactory")
], GridComp.prototype, "loggerFactory", 2);
__decorateClass([
  RefSelector("gridBody")
], GridComp.prototype, "gridBodyComp", 2);
__decorateClass([
  RefSelector("sideBar")
], GridComp.prototype, "sideBarComp", 2);
__decorateClass([
  RefSelector("rootWrapperBody")
], GridComp.prototype, "eRootWrapperBody", 2);
__decorateClass([
  PostConstruct
], GridComp.prototype, "postConstruct", 1);

// community-modules/core/src/sortController.ts
var SortController = class extends BeanStub {
  progressSort(column, multiSort, source) {
    const nextDirection = this.getNextSortDirection(column);
    this.setSortForColumn(column, nextDirection, multiSort, source);
  }
  setSortForColumn(column, sort, multiSort, source) {
    if (sort !== "asc" && sort !== "desc") {
      sort = null;
    }
    const isColumnsSortingCoupledToGroup = this.gos.isColumnsSortingCoupledToGroup();
    let columnsToUpdate = [column];
    if (isColumnsSortingCoupledToGroup) {
      if (column.getColDef().showRowGroup) {
        const rowGroupColumns = this.columnModel.getSourceColumnsForGroupColumn(column);
        const sortableRowGroupColumns = rowGroupColumns == null ? void 0 : rowGroupColumns.filter((col) => col.isSortable());
        if (sortableRowGroupColumns) {
          columnsToUpdate = [column, ...sortableRowGroupColumns];
        }
      }
    }
    columnsToUpdate.forEach((col) => col.setSort(sort, source));
    const doingMultiSort = (multiSort || this.gos.get("alwaysMultiSort")) && !this.gos.get("suppressMultiSort");
    const updatedColumns = [];
    if (!doingMultiSort) {
      const clearedColumns = this.clearSortBarTheseColumns(columnsToUpdate, source);
      updatedColumns.push(...clearedColumns);
    }
    this.updateSortIndex(column);
    updatedColumns.push(...columnsToUpdate);
    this.dispatchSortChangedEvents(source, updatedColumns);
  }
  updateSortIndex(lastColToChange) {
    const isCoupled = this.gos.isColumnsSortingCoupledToGroup();
    const groupParent = this.columnModel.getGroupDisplayColumnForGroup(lastColToChange.getId());
    const lastSortIndexCol = isCoupled ? groupParent || lastColToChange : lastColToChange;
    const allSortedCols = this.getColumnsWithSortingOrdered();
    this.columnModel.getPrimaryAndSecondaryAndAutoColumns().forEach((col) => col.setSortIndex(null));
    const allSortedColsWithoutChangesOrGroups = allSortedCols.filter((col) => {
      if (isCoupled && col.getColDef().showRowGroup) {
        return false;
      }
      return col !== lastSortIndexCol;
    });
    const sortedColsWithIndices = !!lastSortIndexCol.getSort() ? [...allSortedColsWithoutChangesOrGroups, lastSortIndexCol] : allSortedColsWithoutChangesOrGroups;
    sortedColsWithIndices.forEach((col, idx) => {
      col.setSortIndex(idx);
    });
  }
  // gets called by API, so if data changes, use can call this, which will end up
  // working out the sort order again of the rows.
  onSortChanged(source, columns) {
    this.dispatchSortChangedEvents(source, columns);
  }
  isSortActive() {
    const allCols = this.columnModel.getPrimaryAndSecondaryAndAutoColumns();
    const sortedCols = allCols.filter((column) => !!column.getSort());
    return sortedCols && sortedCols.length > 0;
  }
  dispatchSortChangedEvents(source, columns) {
    const event = {
      type: Events.EVENT_SORT_CHANGED,
      source
    };
    if (columns) {
      event.columns = columns;
    }
    this.eventService.dispatchEvent(event);
  }
  clearSortBarTheseColumns(columnsToSkip, source) {
    const clearedColumns = [];
    this.columnModel.getPrimaryAndSecondaryAndAutoColumns().forEach((columnToClear) => {
      if (!columnsToSkip.includes(columnToClear)) {
        if (!!columnToClear.getSort()) {
          clearedColumns.push(columnToClear);
        }
        columnToClear.setSort(void 0, source);
      }
    });
    return clearedColumns;
  }
  getNextSortDirection(column) {
    let sortingOrder;
    if (column.getColDef().sortingOrder) {
      sortingOrder = column.getColDef().sortingOrder;
    } else if (this.gos.get("sortingOrder")) {
      sortingOrder = this.gos.get("sortingOrder");
    } else {
      sortingOrder = SortController.DEFAULT_SORTING_ORDER;
    }
    if (!Array.isArray(sortingOrder) || sortingOrder.length <= 0) {
      console.warn(`AG Grid: sortingOrder must be an array with at least one element, currently it's ${sortingOrder}`);
      return null;
    }
    const currentIndex = sortingOrder.indexOf(column.getSort());
    const notInArray = currentIndex < 0;
    const lastItemInArray = currentIndex == sortingOrder.length - 1;
    let result;
    if (notInArray || lastItemInArray) {
      result = sortingOrder[0];
    } else {
      result = sortingOrder[currentIndex + 1];
    }
    if (SortController.DEFAULT_SORTING_ORDER.indexOf(result) < 0) {
      console.warn("AG Grid: invalid sort type " + result);
      return null;
    }
    return result;
  }
  /**
   * @returns a map of sort indexes for every sorted column, if groups sort primaries then they will have equivalent indices
   */
  getIndexedSortMap() {
    let allSortedCols = this.columnModel.getPrimaryAndSecondaryAndAutoColumns().filter((col) => !!col.getSort());
    if (this.columnModel.isPivotMode()) {
      const isSortingLinked = this.gos.isColumnsSortingCoupledToGroup();
      allSortedCols = allSortedCols.filter((col) => {
        const isAggregated = !!col.getAggFunc();
        const isSecondary = !col.isPrimary();
        const isGroup = isSortingLinked ? this.columnModel.getGroupDisplayColumnForGroup(col.getId()) : col.getColDef().showRowGroup;
        return isAggregated || isSecondary || isGroup;
      });
    }
    const sortedRowGroupCols = this.columnModel.getRowGroupColumns().filter((col) => !!col.getSort());
    const allColsIndexes = {};
    allSortedCols.forEach((col, index) => allColsIndexes[col.getId()] = index);
    allSortedCols.sort((a, b) => {
      const iA = a.getSortIndex();
      const iB = b.getSortIndex();
      if (iA != null && iB != null) {
        return iA - iB;
      } else if (iA == null && iB == null) {
        const posA = allColsIndexes[a.getId()];
        const posB = allColsIndexes[b.getId()];
        return posA > posB ? 1 : -1;
      } else if (iB == null) {
        return -1;
      } else {
        return 1;
      }
    });
    const isSortLinked = this.gos.isColumnsSortingCoupledToGroup() && !!sortedRowGroupCols.length;
    if (isSortLinked) {
      allSortedCols = [
        ...new Set(
          // if linked sorting, replace all columns with the display group column for index purposes, and ensure uniqueness
          allSortedCols.map((col) => {
            var _a;
            return (_a = this.columnModel.getGroupDisplayColumnForGroup(col.getId())) != null ? _a : col;
          })
        )
      ];
    }
    const indexMap = /* @__PURE__ */ new Map();
    allSortedCols.forEach((col, idx) => indexMap.set(col, idx));
    if (isSortLinked) {
      sortedRowGroupCols.forEach((col) => {
        const groupDisplayCol = this.columnModel.getGroupDisplayColumnForGroup(col.getId());
        indexMap.set(col, indexMap.get(groupDisplayCol));
      });
    }
    return indexMap;
  }
  getColumnsWithSortingOrdered() {
    return [...this.getIndexedSortMap().entries()].sort(([col1, idx1], [col2, idx2]) => idx1 - idx2).map(([col]) => col);
  }
  // used by server side row models, to sent sort to server
  getSortModel() {
    return this.getColumnsWithSortingOrdered().filter((column) => column.getSort()).map((column) => ({
      sort: column.getSort(),
      colId: column.getId()
    }));
  }
  getSortOptions() {
    return this.getColumnsWithSortingOrdered().filter((column) => column.getSort()).map((column) => ({
      sort: column.getSort(),
      column
    }));
  }
  canColumnDisplayMixedSort(column) {
    const isColumnSortCouplingActive = this.gos.isColumnsSortingCoupledToGroup();
    const isGroupDisplayColumn = !!column.getColDef().showRowGroup;
    return isColumnSortCouplingActive && isGroupDisplayColumn;
  }
  getDisplaySortForColumn(column) {
    const linkedColumns = this.columnModel.getSourceColumnsForGroupColumn(column);
    if (!this.canColumnDisplayMixedSort(column) || !(linkedColumns == null ? void 0 : linkedColumns.length)) {
      return column.getSort();
    }
    const columnHasUniqueData = column.getColDef().field != null || !!column.getColDef().valueGetter;
    const sortableColumns = columnHasUniqueData ? [column, ...linkedColumns] : linkedColumns;
    const firstSort = sortableColumns[0].getSort();
    const allMatch = sortableColumns.every((col) => col.getSort() == firstSort);
    if (!allMatch) {
      return "mixed";
    }
    return firstSort;
  }
  getDisplaySortIndexForColumn(column) {
    return this.getIndexedSortMap().get(column);
  }
};
SortController.DEFAULT_SORTING_ORDER = ["asc", "desc", null];
__decorateClass([
  Autowired("columnModel")
], SortController.prototype, "columnModel", 2);
SortController = __decorateClass([
  Bean("sortController")
], SortController);

// community-modules/core/src/focusService.ts
var FocusService = class extends BeanStub {
  static addKeyboardModeEvents(doc) {
    if (this.instanceCount > 0) {
      return;
    }
    doc.addEventListener("keydown", FocusService.toggleKeyboardMode);
    doc.addEventListener("mousedown", FocusService.toggleKeyboardMode);
  }
  static removeKeyboardModeEvents(doc) {
    if (this.instanceCount > 0)
      return;
    doc.addEventListener("keydown", FocusService.toggleKeyboardMode);
    doc.addEventListener("mousedown", FocusService.toggleKeyboardMode);
  }
  static toggleKeyboardMode(event) {
    const isKeyboardActive = FocusService.keyboardModeActive;
    const isKeyboardEvent = event.type === "keydown";
    if (isKeyboardEvent) {
      if (event.ctrlKey || event.metaKey || event.altKey) {
        return;
      }
    }
    if (isKeyboardActive === isKeyboardEvent) {
      return;
    }
    FocusService.keyboardModeActive = isKeyboardEvent;
  }
  static unregisterGridCompController(doc) {
    FocusService.removeKeyboardModeEvents(doc);
  }
  init() {
    const clearFocusedCellListener = this.clearFocusedCell.bind(this);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, clearFocusedCellListener);
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, this.onColumnEverythingChanged.bind(this));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_GROUP_OPENED, clearFocusedCellListener);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, clearFocusedCellListener);
    this.registerKeyboardFocusEvents();
    this.ctrlsService.whenReady((p) => {
      this.gridCtrl = p.gridCtrl;
    });
  }
  registerKeyboardFocusEvents() {
    const eDocument = this.gos.getDocument();
    FocusService.addKeyboardModeEvents(eDocument);
    FocusService.instanceCount++;
    this.addDestroyFunc(() => {
      FocusService.instanceCount--;
      FocusService.unregisterGridCompController(eDocument);
    });
  }
  onColumnEverythingChanged() {
    if (!this.focusedCellPosition) {
      return;
    }
    const col = this.focusedCellPosition.column;
    const colFromColumnModel = this.columnModel.getGridColumn(col.getId());
    if (col !== colFromColumnModel) {
      this.clearFocusedCell();
    }
  }
  isKeyboardMode() {
    return FocusService.keyboardModeActive;
  }
  // we check if the browser is focusing something, and if it is, and
  // it's the cell we think is focused, then return the cell. so this
  // methods returns the cell if a) we think it has focus and b) the
  // browser thinks it has focus. this then returns nothing if we
  // first focus a cell, then second click outside the grid, as then the
  // grid cell will still be focused as far as the grid is concerned,
  // however the browser focus will have moved somewhere else.
  getFocusCellToUseAfterRefresh() {
    if (this.gos.get("suppressFocusAfterRefresh") || !this.focusedCellPosition) {
      return null;
    }
    if (this.isDomDataMissingInHierarchy(this.gos.getActiveDomElement(), RowCtrl.DOM_DATA_KEY_ROW_CTRL)) {
      return null;
    }
    return this.focusedCellPosition;
  }
  getFocusHeaderToUseAfterRefresh() {
    if (this.gos.get("suppressFocusAfterRefresh") || !this.focusedHeaderPosition) {
      return null;
    }
    if (this.isDomDataMissingInHierarchy(this.gos.getActiveDomElement(), AbstractHeaderCellCtrl.DOM_DATA_KEY_HEADER_CTRL)) {
      return null;
    }
    return this.focusedHeaderPosition;
  }
  isDomDataMissingInHierarchy(eBrowserCell, key) {
    let ePointer = eBrowserCell;
    while (ePointer) {
      const data = this.gos.getDomData(ePointer, key);
      if (data) {
        return false;
      }
      ePointer = ePointer.parentNode;
    }
    return true;
  }
  getFocusedCell() {
    return this.focusedCellPosition;
  }
  shouldRestoreFocus(cell) {
    if (this.isCellRestoreFocused(cell)) {
      setTimeout(() => {
        this.restoredFocusedCellPosition = null;
      }, 0);
      return true;
    }
    return false;
  }
  isCellRestoreFocused(cellPosition) {
    if (this.restoredFocusedCellPosition == null) {
      return false;
    }
    return this.cellPositionUtils.equals(cellPosition, this.restoredFocusedCellPosition);
  }
  setRestoreFocusedCell(cellPosition) {
    if (this.getFrameworkOverrides().renderingEngine === "react") {
      this.restoredFocusedCellPosition = cellPosition;
    }
  }
  getFocusEventParams() {
    const { rowIndex, rowPinned, column } = this.focusedCellPosition;
    const params = {
      rowIndex,
      rowPinned,
      column,
      isFullWidthCell: false
    };
    const rowCtrl = this.rowRenderer.getRowByPosition({ rowIndex, rowPinned });
    if (rowCtrl) {
      params.isFullWidthCell = rowCtrl.isFullWidth();
    }
    return params;
  }
  clearFocusedCell() {
    this.restoredFocusedCellPosition = null;
    if (this.focusedCellPosition == null) {
      return;
    }
    const event = __spreadValues({
      type: Events.EVENT_CELL_FOCUS_CLEARED
    }, this.getFocusEventParams());
    this.focusedCellPosition = null;
    this.eventService.dispatchEvent(event);
  }
  setFocusedCell(params) {
    const {
      column,
      rowIndex,
      rowPinned,
      forceBrowserFocus = false,
      preventScrollOnBrowserFocus = false
    } = params;
    const gridColumn = this.columnModel.getGridColumn(column);
    if (!gridColumn) {
      this.focusedCellPosition = null;
      return;
    }
    this.focusedCellPosition = gridColumn ? {
      rowIndex,
      rowPinned: makeNull(rowPinned),
      column: gridColumn
    } : null;
    const event = __spreadProps(__spreadValues({
      type: Events.EVENT_CELL_FOCUSED
    }, this.getFocusEventParams()), {
      forceBrowserFocus,
      preventScrollOnBrowserFocus,
      floating: null
    });
    this.eventService.dispatchEvent(event);
  }
  isCellFocused(cellPosition) {
    if (this.focusedCellPosition == null) {
      return false;
    }
    return this.cellPositionUtils.equals(cellPosition, this.focusedCellPosition);
  }
  isRowNodeFocused(rowNode) {
    return this.isRowFocused(rowNode.rowIndex, rowNode.rowPinned);
  }
  isHeaderWrapperFocused(headerCtrl) {
    if (this.focusedHeaderPosition == null) {
      return false;
    }
    const column = headerCtrl.getColumnGroupChild();
    const headerRowIndex = headerCtrl.getRowIndex();
    const pinned = headerCtrl.getPinned();
    const { column: focusedColumn, headerRowIndex: focusedHeaderRowIndex } = this.focusedHeaderPosition;
    return column === focusedColumn && headerRowIndex === focusedHeaderRowIndex && pinned == focusedColumn.getPinned();
  }
  clearFocusedHeader() {
    this.focusedHeaderPosition = null;
  }
  getFocusedHeader() {
    return this.focusedHeaderPosition;
  }
  setFocusedHeader(headerRowIndex, column) {
    this.focusedHeaderPosition = { headerRowIndex, column };
  }
  focusHeaderPosition(params) {
    if (this.gos.get("suppressHeaderFocus")) {
      return false;
    }
    const { direction, fromTab, allowUserOverride, event, fromCell, rowWithoutSpanValue } = params;
    let { headerPosition } = params;
    if (fromCell && this.filterManager.isAdvancedFilterHeaderActive()) {
      return this.focusAdvancedFilter(headerPosition);
    }
    if (allowUserOverride) {
      const currentPosition = this.getFocusedHeader();
      const headerRowCount = this.headerNavigationService.getHeaderRowCount();
      if (fromTab) {
        const userFunc = this.gos.getCallback("tabToNextHeader");
        if (userFunc) {
          headerPosition = this.getHeaderPositionFromUserFunc({
            userFunc,
            direction,
            currentPosition,
            headerPosition,
            headerRowCount
          });
        }
      } else {
        const userFunc = this.gos.getCallback("navigateToNextHeader");
        if (userFunc && event) {
          const params2 = {
            key: event.key,
            previousHeaderPosition: currentPosition,
            nextHeaderPosition: headerPosition,
            headerRowCount,
            event
          };
          headerPosition = userFunc(params2);
        }
      }
    }
    if (!headerPosition) {
      return false;
    }
    return this.focusProvidedHeaderPosition({
      headerPosition,
      direction,
      event,
      fromCell,
      rowWithoutSpanValue
    });
  }
  focusHeaderPositionFromUserFunc(params) {
    if (this.gos.get("suppressHeaderFocus")) {
      return false;
    }
    const { userFunc, headerPosition, direction, event } = params;
    const currentPosition = this.getFocusedHeader();
    const headerRowCount = this.headerNavigationService.getHeaderRowCount();
    const newHeaderPosition = this.getHeaderPositionFromUserFunc({
      userFunc,
      direction,
      currentPosition,
      headerPosition,
      headerRowCount
    });
    return !!newHeaderPosition && this.focusProvidedHeaderPosition({
      headerPosition: newHeaderPosition,
      direction,
      event
    });
  }
  getHeaderPositionFromUserFunc(params) {
    const { userFunc, direction, currentPosition, headerPosition, headerRowCount } = params;
    const userFuncParams = {
      backwards: direction === "Before",
      previousHeaderPosition: currentPosition,
      nextHeaderPosition: headerPosition,
      headerRowCount
    };
    const userResult = userFunc(userFuncParams);
    if (userResult === true || userResult === null) {
      if (userResult === null) {
        warnOnce("Returning `null` from tabToNextHeader is deprecated. Return `true` to stay on the current header, or `false` to let the browser handle the tab behaviour.");
      }
      return currentPosition;
    }
    if (userResult === false) {
      return null;
    }
    return userResult;
  }
  focusProvidedHeaderPosition(params) {
    const { headerPosition, direction, fromCell, rowWithoutSpanValue, event } = params;
    if (headerPosition.headerRowIndex === -1) {
      if (this.filterManager.isAdvancedFilterHeaderActive()) {
        return this.focusAdvancedFilter(headerPosition);
      }
      return this.focusGridView(headerPosition.column);
    }
    this.headerNavigationService.scrollToColumn(headerPosition.column, direction);
    const headerRowContainerCtrl = this.ctrlsService.getHeaderRowContainerCtrl(headerPosition.column.getPinned());
    const focusSuccess = headerRowContainerCtrl.focusHeader(headerPosition.headerRowIndex, headerPosition.column, event);
    if (focusSuccess && (rowWithoutSpanValue != null || fromCell)) {
      this.headerNavigationService.setCurrentHeaderRowWithoutSpan(rowWithoutSpanValue != null ? rowWithoutSpanValue : -1);
    }
    return focusSuccess;
  }
  focusFirstHeader() {
    let firstColumn = this.columnModel.getAllDisplayedColumns()[0];
    if (!firstColumn) {
      return false;
    }
    if (firstColumn.getParent()) {
      firstColumn = this.columnModel.getColumnGroupAtLevel(firstColumn, 0);
    }
    const headerPosition = this.headerPositionUtils.getHeaderIndexToFocus(firstColumn, 0);
    return this.focusHeaderPosition({
      headerPosition,
      rowWithoutSpanValue: 0
    });
  }
  focusLastHeader(event) {
    const headerRowIndex = this.headerNavigationService.getHeaderRowCount() - 1;
    const column = last(this.columnModel.getAllDisplayedColumns());
    return this.focusHeaderPosition({
      headerPosition: { headerRowIndex, column },
      rowWithoutSpanValue: -1,
      event
    });
  }
  focusPreviousFromFirstCell(event) {
    if (this.filterManager.isAdvancedFilterHeaderActive()) {
      return this.focusAdvancedFilter(null);
    }
    return this.focusLastHeader(event);
  }
  isAnyCellFocused() {
    return !!this.focusedCellPosition;
  }
  isRowFocused(rowIndex, floating) {
    if (this.focusedCellPosition == null) {
      return false;
    }
    return this.focusedCellPosition.rowIndex === rowIndex && this.focusedCellPosition.rowPinned === makeNull(floating);
  }
  findFocusableElements(rootNode, exclude, onlyUnmanaged = false) {
    const focusableString = FOCUSABLE_SELECTOR;
    let excludeString = FOCUSABLE_EXCLUDE;
    if (exclude) {
      excludeString += ", " + exclude;
    }
    if (onlyUnmanaged) {
      excludeString += ', [tabindex="-1"]';
    }
    const nodes = Array.prototype.slice.apply(rootNode.querySelectorAll(focusableString)).filter((node) => {
      return isVisible(node);
    });
    const excludeNodes = Array.prototype.slice.apply(rootNode.querySelectorAll(excludeString));
    if (!excludeNodes.length) {
      return nodes;
    }
    const diff = (a, b) => a.filter((element) => b.indexOf(element) === -1);
    return diff(nodes, excludeNodes);
  }
  focusInto(rootNode, up = false, onlyUnmanaged = false) {
    const focusableElements = this.findFocusableElements(rootNode, null, onlyUnmanaged);
    const toFocus = up ? last(focusableElements) : focusableElements[0];
    if (toFocus) {
      toFocus.focus({ preventScroll: true });
      return true;
    }
    return false;
  }
  findFocusableElementBeforeTabGuard(rootNode, referenceElement) {
    if (!referenceElement) {
      return null;
    }
    const focusableElements = this.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("ag-tab-guard-top" /* TAB_GUARD_TOP */)) {
        lastTabGuardIndex = i;
        break;
      }
    }
    if (lastTabGuardIndex <= 0) {
      return null;
    }
    return focusableElements[lastTabGuardIndex - 1];
  }
  findNextFocusableElement(rootNode = this.eGridDiv, onlyManaged, backwards) {
    const focusable = this.findFocusableElements(rootNode, onlyManaged ? ':not([tabindex="-1"])' : null);
    const activeEl = this.gos.getActiveDomElement();
    let currentIndex;
    if (onlyManaged) {
      currentIndex = focusable.findIndex((el) => el.contains(activeEl));
    } else {
      currentIndex = focusable.indexOf(activeEl);
    }
    const nextIndex = currentIndex + (backwards ? -1 : 1);
    if (nextIndex < 0 || nextIndex >= focusable.length) {
      return null;
    }
    return focusable[nextIndex];
  }
  isTargetUnderManagedComponent(rootNode, target) {
    if (!target) {
      return false;
    }
    const managedContainers = rootNode.querySelectorAll(`.${ManagedFocusFeature.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;
  }
  findTabbableParent(node, limit = 5) {
    let counter = 0;
    while (node && getTabIndex(node) === null && ++counter <= limit) {
      node = node.parentElement;
    }
    if (getTabIndex(node) === null) {
      return null;
    }
    return node;
  }
  focusGridView(column, backwards) {
    var _a;
    if (this.gos.get("suppressCellFocus")) {
      if (backwards) {
        if (!this.gos.get("suppressHeaderFocus")) {
          return this.focusLastHeader();
        }
        return this.focusNextGridCoreContainer(true, true);
      }
      return this.focusNextGridCoreContainer(false);
    }
    const nextRow = backwards ? this.rowPositionUtils.getLastRow() : this.rowPositionUtils.getFirstRow();
    if (!nextRow) {
      return false;
    }
    const { rowIndex, rowPinned } = nextRow;
    const focusedHeader = this.getFocusedHeader();
    if (!column && focusedHeader) {
      column = focusedHeader.column;
    }
    if (rowIndex == null || !column) {
      return false;
    }
    this.navigationService.ensureCellVisible({ rowIndex, column, rowPinned });
    this.setFocusedCell({
      rowIndex,
      column,
      rowPinned: makeNull(rowPinned),
      forceBrowserFocus: true
    });
    (_a = this.rangeService) == null ? void 0 : _a.setRangeToCell({ rowIndex, rowPinned, column });
    return true;
  }
  focusNextGridCoreContainer(backwards, forceOut = false) {
    if (!forceOut && this.gridCtrl.focusNextInnerContainer(backwards)) {
      return true;
    }
    if (forceOut || !backwards && !this.gridCtrl.isDetailGrid()) {
      this.gridCtrl.forceFocusOutOfContainer(backwards);
    }
    return false;
  }
  focusAdvancedFilter(position) {
    var _a, _b;
    this.advancedFilterFocusColumn = position == null ? void 0 : position.column;
    return (_b = (_a = this.advancedFilterService) == null ? void 0 : _a.getCtrl().focusHeaderComp()) != null ? _b : false;
  }
  focusNextFromAdvancedFilter(backwards, forceFirstColumn) {
    var _a, _b;
    const column = (_b = forceFirstColumn ? void 0 : this.advancedFilterFocusColumn) != null ? _b : (_a = this.columnModel.getAllDisplayedColumns()) == null ? void 0 : _a[0];
    if (backwards) {
      return this.focusHeaderPosition({
        headerPosition: {
          column,
          headerRowIndex: this.headerNavigationService.getHeaderRowCount() - 1
        }
      });
    } else {
      return this.focusGridView(column);
    }
  }
  clearAdvancedFilterColumn() {
    this.advancedFilterFocusColumn = void 0;
  }
};
FocusService.keyboardModeActive = false;
FocusService.instanceCount = 0;
__decorateClass([
  Autowired("eGridDiv")
], FocusService.prototype, "eGridDiv", 2);
__decorateClass([
  Autowired("columnModel")
], FocusService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("headerNavigationService")
], FocusService.prototype, "headerNavigationService", 2);
__decorateClass([
  Autowired("headerPositionUtils")
], FocusService.prototype, "headerPositionUtils", 2);
__decorateClass([
  Autowired("rowRenderer")
], FocusService.prototype, "rowRenderer", 2);
__decorateClass([
  Autowired("rowPositionUtils")
], FocusService.prototype, "rowPositionUtils", 2);
__decorateClass([
  Autowired("cellPositionUtils")
], FocusService.prototype, "cellPositionUtils", 2);
__decorateClass([
  Autowired("navigationService")
], FocusService.prototype, "navigationService", 2);
__decorateClass([
  Autowired("ctrlsService")
], FocusService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("filterManager")
], FocusService.prototype, "filterManager", 2);
__decorateClass([
  Optional("rangeService")
], FocusService.prototype, "rangeService", 2);
__decorateClass([
  Optional("advancedFilterService")
], FocusService.prototype, "advancedFilterService", 2);
__decorateClass([
  PostConstruct
], FocusService.prototype, "init", 1);
FocusService = __decorateClass([
  Bean("focusService")
], FocusService);

// community-modules/core/src/rendering/columnHoverService.ts
var ColumnHoverService = class extends BeanStub {
  setMouseOver(columns) {
    this.selectedColumns = columns;
    const event = {
      type: Events.EVENT_COLUMN_HOVER_CHANGED
    };
    this.eventService.dispatchEvent(event);
  }
  clearMouseOver() {
    this.selectedColumns = null;
    const event = {
      type: Events.EVENT_COLUMN_HOVER_CHANGED
    };
    this.eventService.dispatchEvent(event);
  }
  isHovered(column) {
    return !!this.selectedColumns && this.selectedColumns.indexOf(column) >= 0;
  }
};
ColumnHoverService = __decorateClass([
  Bean("columnHoverService")
], ColumnHoverService);

// community-modules/core/src/rendering/columnAnimationService.ts
var ColumnAnimationService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.executeNextFuncs = [];
    this.executeLaterFuncs = [];
    this.active = false;
    this.suppressAnimation = false;
    this.animationThreadCount = 0;
  }
  postConstruct() {
    this.ctrlsService.whenReady((p) => this.gridBodyCtrl = p.gridBodyCtrl);
  }
  isActive() {
    return this.active && !this.suppressAnimation;
  }
  setSuppressAnimation(suppress) {
    this.suppressAnimation = suppress;
  }
  start() {
    if (this.active) {
      return;
    }
    if (this.gos.get("suppressColumnMoveAnimation")) {
      return;
    }
    if (this.gos.get("enableRtl")) {
      return;
    }
    this.ensureAnimationCssClassPresent();
    this.active = true;
  }
  finish() {
    if (!this.active) {
      return;
    }
    this.flush(() => {
      this.active = false;
    });
  }
  executeNextVMTurn(func) {
    if (this.active) {
      this.executeNextFuncs.push(func);
    } else {
      func();
    }
  }
  executeLaterVMTurn(func) {
    if (this.active) {
      this.executeLaterFuncs.push(func);
    } else {
      func();
    }
  }
  ensureAnimationCssClassPresent() {
    this.animationThreadCount++;
    const animationThreadCountCopy = this.animationThreadCount;
    this.gridBodyCtrl.setColumnMovingCss(true);
    this.executeLaterFuncs.push(() => {
      if (this.animationThreadCount === animationThreadCountCopy) {
        this.gridBodyCtrl.setColumnMovingCss(false);
      }
    });
  }
  flush(callback) {
    if (this.executeNextFuncs.length === 0 && this.executeLaterFuncs.length === 0) {
      callback();
      return;
    }
    const runFuncs = (queue) => {
      while (queue.length) {
        const func = queue.pop();
        if (func) {
          func();
        }
      }
    };
    this.getFrameworkOverrides().wrapIncoming(() => {
      window.setTimeout(() => runFuncs(this.executeNextFuncs), 0);
      window.setTimeout(() => {
        callback();
        runFuncs(this.executeLaterFuncs);
      }, 200);
    });
  }
};
__decorateClass([
  Autowired("ctrlsService")
], ColumnAnimationService.prototype, "ctrlsService", 2);
__decorateClass([
  PostConstruct
], ColumnAnimationService.prototype, "postConstruct", 1);
ColumnAnimationService = __decorateClass([
  Bean("columnAnimationService")
], ColumnAnimationService);

// community-modules/core/src/pagination/paginationAutoPageSizeService.ts
var PaginationAutoPageSizeService = class extends BeanStub {
  postConstruct() {
    this.ctrlsService.whenReady((p) => {
      this.centerRowsCtrl = p.center;
      this.addManagedListener(this.eventService, Events.EVENT_BODY_HEIGHT_CHANGED, this.checkPageSize.bind(this));
      this.addManagedListener(this.eventService, Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.checkPageSize.bind(this));
      this.addManagedPropertyListener("paginationAutoPageSize", this.onPaginationAutoSizeChanged.bind(this));
      this.checkPageSize();
    });
  }
  notActive() {
    return !this.gos.get("paginationAutoPageSize") || this.centerRowsCtrl == null;
  }
  onPaginationAutoSizeChanged() {
    if (this.notActive()) {
      this.paginationProxy.unsetAutoCalculatedPageSize();
    } else {
      this.checkPageSize();
    }
  }
  checkPageSize() {
    if (this.notActive()) {
      return;
    }
    const bodyHeight = this.centerRowsCtrl.getViewportSizeFeature().getBodyHeight();
    if (bodyHeight > 0) {
      const update = () => {
        const rowHeight = this.gos.getRowHeightAsNumber();
        const newPageSize = Math.floor(bodyHeight / rowHeight);
        this.paginationProxy.setPageSize(newPageSize, "autoCalculated");
      };
      if (!this.isBodyRendered) {
        update();
        this.isBodyRendered = true;
      } else {
        debounce(() => update(), 50)();
      }
    } else {
      this.isBodyRendered = false;
    }
  }
};
__decorateClass([
  Autowired("ctrlsService")
], PaginationAutoPageSizeService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("paginationProxy")
], PaginationAutoPageSizeService.prototype, "paginationProxy", 2);
__decorateClass([
  PostConstruct
], PaginationAutoPageSizeService.prototype, "postConstruct", 1);
PaginationAutoPageSizeService = __decorateClass([
  Bean("paginationAutoPageSizeService")
], PaginationAutoPageSizeService);

// community-modules/core/src/valueService/valueCache.ts
var ValueCache = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.cacheVersion = 0;
  }
  init() {
    this.active = this.gos.get("valueCache");
    this.neverExpires = this.gos.get("valueCacheNeverExpires");
  }
  onDataChanged() {
    if (this.neverExpires) {
      return;
    }
    this.expire();
  }
  expire() {
    this.cacheVersion++;
  }
  setValue(rowNode, colId, value) {
    if (this.active) {
      if (rowNode.__cacheVersion !== this.cacheVersion) {
        rowNode.__cacheVersion = this.cacheVersion;
        rowNode.__cacheData = {};
      }
      rowNode.__cacheData[colId] = value;
    }
  }
  getValue(rowNode, colId) {
    if (!this.active || rowNode.__cacheVersion !== this.cacheVersion) {
      return void 0;
    }
    return rowNode.__cacheData[colId];
  }
};
__decorateClass([
  PostConstruct
], ValueCache.prototype, "init", 1);
ValueCache = __decorateClass([
  Bean("valueCache")
], ValueCache);

// community-modules/core/src/valueService/changeDetectionService.ts
var SOURCE_PASTE = "paste";
var ChangeDetectionService = class extends BeanStub {
  init() {
    if (this.rowModel.getType() === "clientSide") {
      this.clientSideRowModel = this.rowModel;
    }
    this.addManagedListener(this.eventService, Events.EVENT_CELL_VALUE_CHANGED, this.onCellValueChanged.bind(this));
  }
  onCellValueChanged(event) {
    if (event.source === SOURCE_PASTE) {
      return;
    }
    this.doChangeDetection(event.node, event.column);
  }
  doChangeDetection(rowNode, column) {
    if (this.gos.get("suppressChangeDetection")) {
      return;
    }
    const nodesToRefresh = [rowNode];
    if (this.clientSideRowModel && !rowNode.isRowPinned()) {
      const onlyChangedColumns = this.gos.get("aggregateOnlyChangedColumns");
      const changedPath = new ChangedPath(onlyChangedColumns, this.clientSideRowModel.getRootNode());
      changedPath.addParentNode(rowNode.parent, [column]);
      this.clientSideRowModel.doAggregate(changedPath);
      changedPath.forEachChangedNodeDepthFirst((rowNode2) => {
        nodesToRefresh.push(rowNode2);
      });
    }
    this.rowRenderer.refreshCells({ rowNodes: nodesToRefresh });
  }
};
__decorateClass([
  Autowired("rowModel")
], ChangeDetectionService.prototype, "rowModel", 2);
__decorateClass([
  Autowired("rowRenderer")
], ChangeDetectionService.prototype, "rowRenderer", 2);
__decorateClass([
  PostConstruct
], ChangeDetectionService.prototype, "init", 1);
ChangeDetectionService = __decorateClass([
  Bean("changeDetectionService")
], ChangeDetectionService);

// community-modules/core/src/components/framework/agComponentUtils.ts
var AgComponentUtils = class extends BeanStub {
  adaptFunction(propertyName, jsCompFunc) {
    const metadata = this.componentMetadataProvider.retrieve(propertyName);
    if (metadata && metadata.functionAdapter) {
      return metadata.functionAdapter(jsCompFunc);
    }
    return null;
  }
  adaptCellRendererFunction(callback) {
    class Adapter {
      refresh(params) {
        return false;
      }
      getGui() {
        return this.eGui;
      }
      init(params) {
        const callbackResult = callback(params);
        const type = typeof callbackResult;
        if (type === "string" || type === "number" || type === "boolean") {
          this.eGui = loadTemplate("<span>" + callbackResult + "</span>");
          return;
        }
        if (callbackResult == null) {
          this.eGui = loadTemplate("<span></span>");
          return;
        }
        this.eGui = callbackResult;
      }
    }
    return Adapter;
  }
  doesImplementIComponent(candidate) {
    if (!candidate) {
      return false;
    }
    return candidate.prototype && "getGui" in candidate.prototype;
  }
};
__decorateClass([
  Autowired("componentMetadataProvider")
], AgComponentUtils.prototype, "componentMetadataProvider", 2);
AgComponentUtils = __decorateClass([
  Bean("agComponentUtils")
], AgComponentUtils);

// community-modules/core/src/components/framework/componentMetadataProvider.ts
var ComponentMetadataProvider = class extends BeanStub {
  postConstruct() {
    this.componentMetaData = {
      dateComponent: {
        mandatoryMethodList: ["getDate", "setDate"],
        optionalMethodList: ["afterGuiAttached", "setInputPlaceholder", "setInputAriaLabel", "setDisabled", "onParamsUpdated", "refresh"]
      },
      detailCellRenderer: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh"],
        functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)
      },
      headerComponent: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh"]
      },
      headerGroupComponent: {
        mandatoryMethodList: [],
        optionalMethodList: []
      },
      loadingCellRenderer: {
        mandatoryMethodList: [],
        optionalMethodList: [],
        functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)
      },
      loadingOverlayComponent: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh"]
      },
      noRowsOverlayComponent: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh"]
      },
      floatingFilterComponent: {
        mandatoryMethodList: ["onParentModelChanged"],
        optionalMethodList: ["afterGuiAttached", "onParamsUpdated", "refresh"]
      },
      cellRenderer: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh", "afterGuiAttached"],
        functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)
      },
      cellEditor: {
        mandatoryMethodList: ["getValue"],
        optionalMethodList: ["isPopup", "isCancelBeforeStart", "isCancelAfterEnd", "getPopupPosition", "focusIn", "focusOut", "afterGuiAttached", "refresh"]
      },
      innerRenderer: {
        mandatoryMethodList: [],
        optionalMethodList: ["afterGuiAttached"],
        functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)
      },
      fullWidthCellRenderer: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh", "afterGuiAttached"],
        functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)
      },
      groupRowRenderer: {
        mandatoryMethodList: [],
        optionalMethodList: ["afterGuiAttached"],
        functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)
      },
      filter: {
        mandatoryMethodList: ["isFilterActive", "doesFilterPass", "getModel", "setModel"],
        optionalMethodList: ["afterGuiAttached", "afterGuiDetached", "onNewRowsLoaded", "getModelAsString", "onFloatingFilterChanged", "onAnyFilterChanged", "refresh"]
      },
      statusPanel: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh"]
      },
      toolPanel: {
        mandatoryMethodList: [],
        optionalMethodList: ["refresh", "getState"]
      },
      tooltipComponent: {
        mandatoryMethodList: [],
        optionalMethodList: []
      },
      menuItem: {
        mandatoryMethodList: [],
        optionalMethodList: ["setActive", "select", "setExpanded", "configureDefaults"]
      }
    };
  }
  retrieve(name) {
    return this.componentMetaData[name];
  }
};
__decorateClass([
  Autowired("agComponentUtils")
], ComponentMetadataProvider.prototype, "agComponentUtils", 2);
__decorateClass([
  PostConstruct
], ComponentMetadataProvider.prototype, "postConstruct", 1);
ComponentMetadataProvider = __decorateClass([
  Bean("componentMetadataProvider")
], ComponentMetadataProvider);

// community-modules/core/src/environment.ts
var DEFAULT_ROW_HEIGHT = 25;
var MIN_COL_WIDTH = 10;
var MAT_GRID_SIZE = 8;
var BASE_GRID_SIZE = 4;
var BALHAM_GRID_SIZE = 4;
var ALPINE_GRID_SIZE = 6;
var QUARTZ_ICON_SIZE = 16;
var QUARTZ_FONT_SIZE = 14;
var QUARTZ_GRID_SIZE = 8;
var HARD_CODED_SIZES = {
  // this item is required for custom themes
  "ag-theme-custom": {
    headerHeight: 25,
    headerCellMinWidth: 24,
    listItemHeight: BASE_GRID_SIZE * 5,
    rowHeight: 25,
    chartMenuPanelWidth: 220
  },
  "ag-theme-material": {
    headerHeight: MAT_GRID_SIZE * 7,
    headerCellMinWidth: 48,
    listItemHeight: MAT_GRID_SIZE * 4,
    rowHeight: MAT_GRID_SIZE * 6,
    chartMenuPanelWidth: 240
  },
  "ag-theme-balham": {
    headerHeight: BALHAM_GRID_SIZE * 8,
    headerCellMinWidth: 24,
    listItemHeight: BALHAM_GRID_SIZE * 6,
    rowHeight: BALHAM_GRID_SIZE * 7,
    chartMenuPanelWidth: 220
  },
  "ag-theme-alpine": {
    headerHeight: ALPINE_GRID_SIZE * 8,
    headerCellMinWidth: 36,
    listItemHeight: ALPINE_GRID_SIZE * 4,
    rowHeight: ALPINE_GRID_SIZE * 7,
    chartMenuPanelWidth: 240
  },
  "ag-theme-quartz": {
    headerHeight: QUARTZ_FONT_SIZE + QUARTZ_GRID_SIZE * 4.25,
    headerCellMinWidth: 36,
    listItemHeight: QUARTZ_ICON_SIZE + QUARTZ_GRID_SIZE,
    rowHeight: QUARTZ_FONT_SIZE + QUARTZ_GRID_SIZE * 3.5,
    chartMenuPanelWidth: 260
  }
};
var SASS_PROPERTY_BUILDER = {
  headerHeight: ["ag-header-row"],
  headerCellMinWidth: ["ag-header-cell"],
  listItemHeight: ["ag-virtual-list-item"],
  rowHeight: ["ag-row"],
  chartMenuPanelWidth: ["ag-chart-docked-container"]
};
var Environment = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.calculatedSizes = {};
    this.calculatedTheme = null;
  }
  postConstruct() {
    var _a;
    const el = (_a = this.getTheme().el) != null ? _a : this.eGridDiv;
    this.addManagedPropertyListener("rowHeight", () => this.refreshRowHeightVariable());
    this.mutationObserver = new MutationObserver(() => {
      this.calculatedSizes = {};
      this.calculatedTheme = null;
      this.calculatedTheme = this.getTheme();
      this.fireGridStylesChangedEvent();
    });
    this.mutationObserver.observe(el || this.eGridDiv, {
      attributes: true,
      attributeFilter: ["class"]
    });
  }
  fireGridStylesChangedEvent() {
    const event = {
      type: Events.EVENT_GRID_STYLES_CHANGED
    };
    this.eventService.dispatchEvent(event);
  }
  getSassVariable(key) {
    const { themeFamily, el } = this.getTheme();
    if (!themeFamily || themeFamily.indexOf("ag-theme") !== 0) {
      return;
    }
    if (!this.calculatedSizes) {
      this.calculatedSizes = {};
    }
    if (!this.calculatedSizes[themeFamily]) {
      this.calculatedSizes[themeFamily] = {};
    }
    const size = this.calculatedSizes[themeFamily][key];
    if (size != null) {
      return size;
    }
    this.calculatedSizes[themeFamily][key] = this.calculateValueForSassProperty(key, themeFamily, el);
    return this.calculatedSizes[themeFamily][key];
  }
  calculateValueForSassProperty(property, theme, themeElement) {
    const useTheme = "ag-theme-" + (theme.match("material") ? "material" : theme.match("balham") ? "balham" : theme.match("alpine") ? "alpine" : "custom");
    const defaultValue = HARD_CODED_SIZES[useTheme][property];
    const eDocument = this.gos.getDocument();
    if (!themeElement) {
      themeElement = this.eGridDiv;
    }
    if (!SASS_PROPERTY_BUILDER[property]) {
      return defaultValue;
    }
    const classList = SASS_PROPERTY_BUILDER[property];
    const div = eDocument.createElement("div");
    const classesFromThemeElement = Array.from(themeElement.classList);
    div.classList.add(theme, ...classesFromThemeElement);
    div.style.position = "absolute";
    const el = classList.reduce((prevEl, currentClass) => {
      const currentDiv = eDocument.createElement("div");
      currentDiv.style.position = "static";
      currentDiv.classList.add(currentClass);
      prevEl.appendChild(currentDiv);
      return currentDiv;
    }, div);
    let calculatedValue = 0;
    if (eDocument.body) {
      eDocument.body.appendChild(div);
      const sizeName = property.toLowerCase().indexOf("height") !== -1 ? "height" : "width";
      calculatedValue = parseInt(window.getComputedStyle(el)[sizeName], 10);
      eDocument.body.removeChild(div);
    }
    return calculatedValue || defaultValue;
  }
  isThemeDark() {
    const { theme } = this.getTheme();
    return !!theme && theme.indexOf("dark") >= 0;
  }
  chartMenuPanelWidth() {
    return this.getSassVariable("chartMenuPanelWidth");
  }
  getTheme() {
    if (this.calculatedTheme) {
      return this.calculatedTheme;
    }
    const reg = /\bag-(material|(?:theme-([\w\-]*)))\b/g;
    let el = this.eGridDiv;
    let themeMatch = null;
    let allThemes = [];
    while (el) {
      themeMatch = reg.exec(el.className);
      if (!themeMatch) {
        el = el.parentElement || void 0;
      } else {
        const matched = el.className.match(reg);
        if (matched) {
          allThemes = matched;
        }
        break;
      }
    }
    if (!themeMatch) {
      return { allThemes };
    }
    const theme = themeMatch[0];
    this.calculatedTheme = { theme, el, themeFamily: theme.replace(/-dark$/, ""), allThemes };
    return this.calculatedTheme;
  }
  getFromTheme(defaultValue, sassVariableName) {
    var _a;
    return (_a = this.getSassVariable(sassVariableName)) != null ? _a : defaultValue;
  }
  getDefaultRowHeight() {
    return this.getFromTheme(DEFAULT_ROW_HEIGHT, "rowHeight");
  }
  getListItemHeight() {
    return this.getFromTheme(20, "listItemHeight");
  }
  refreshRowHeightVariable() {
    const oldRowHeight = this.eGridDiv.style.getPropertyValue("--ag-line-height").trim();
    const height = this.gos.get("rowHeight");
    if (height == null || isNaN(height) || !isFinite(height)) {
      if (oldRowHeight !== null) {
        this.eGridDiv.style.setProperty("--ag-line-height", null);
      }
      return -1;
    }
    const newRowHeight = `${height}px`;
    if (oldRowHeight != newRowHeight) {
      this.eGridDiv.style.setProperty("--ag-line-height", newRowHeight);
      return height;
    }
    return oldRowHeight != "" ? parseFloat(oldRowHeight) : -1;
  }
  getMinColWidth() {
    const measuredMin = this.getFromTheme(null, "headerCellMinWidth");
    return exists(measuredMin) ? Math.max(measuredMin, MIN_COL_WIDTH) : MIN_COL_WIDTH;
  }
  destroy() {
    this.calculatedSizes = null;
    if (this.mutationObserver) {
      this.mutationObserver.disconnect();
    }
    super.destroy();
  }
};
__decorateClass([
  Autowired("eGridDiv")
], Environment.prototype, "eGridDiv", 2);
__decorateClass([
  PostConstruct
], Environment.prototype, "postConstruct", 1);
Environment = __decorateClass([
  Bean("environment")
], Environment);

// community-modules/core/src/rendering/rowContainerHeightService.ts
var RowContainerHeightService = class extends BeanStub {
  constructor() {
    super(...arguments);
    // the scrollY position
    this.scrollY = 0;
    // how tall the body is
    this.uiBodyHeight = 0;
  }
  agWire(loggerFactory) {
    this.logger = loggerFactory.create("RowContainerHeightService");
  }
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_BODY_HEIGHT_CHANGED, this.updateOffset.bind(this));
    this.maxDivHeight = getMaxDivHeight();
    this.logger.log("maxDivHeight = " + this.maxDivHeight);
  }
  isStretching() {
    return this.stretching;
  }
  getDivStretchOffset() {
    return this.divStretchOffset;
  }
  updateOffset() {
    if (!this.stretching) {
      return;
    }
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    const newScrollY = gridBodyCon.getScrollFeature().getVScrollPosition().top;
    const newBodyHeight = this.getUiBodyHeight();
    const atLeastOneChanged = newScrollY !== this.scrollY || newBodyHeight !== this.uiBodyHeight;
    if (atLeastOneChanged) {
      this.scrollY = newScrollY;
      this.uiBodyHeight = newBodyHeight;
      this.calculateOffset();
    }
  }
  calculateOffset() {
    this.setUiContainerHeight(this.maxDivHeight);
    this.pixelsToShave = this.modelHeight - this.uiContainerHeight;
    this.maxScrollY = this.uiContainerHeight - this.uiBodyHeight;
    const scrollPercent = this.scrollY / this.maxScrollY;
    const divStretchOffset = scrollPercent * this.pixelsToShave;
    this.logger.log(`Div Stretch Offset = ${divStretchOffset} (${this.pixelsToShave} * ${scrollPercent})`);
    this.setDivStretchOffset(divStretchOffset);
  }
  setUiContainerHeight(height) {
    if (height !== this.uiContainerHeight) {
      this.uiContainerHeight = height;
      this.eventService.dispatchEvent({ type: Events.EVENT_ROW_CONTAINER_HEIGHT_CHANGED });
    }
  }
  clearOffset() {
    this.setUiContainerHeight(this.modelHeight);
    this.pixelsToShave = 0;
    this.setDivStretchOffset(0);
  }
  setDivStretchOffset(newOffset) {
    const newOffsetFloor = typeof newOffset === "number" ? Math.floor(newOffset) : null;
    if (this.divStretchOffset === newOffsetFloor) {
      return;
    }
    this.divStretchOffset = newOffsetFloor;
    this.eventService.dispatchEvent({ type: Events.EVENT_HEIGHT_SCALE_CHANGED });
  }
  setModelHeight(modelHeight) {
    this.modelHeight = modelHeight;
    this.stretching = modelHeight != null && this.maxDivHeight > 0 && modelHeight > this.maxDivHeight;
    if (this.stretching) {
      this.calculateOffset();
    } else {
      this.clearOffset();
    }
  }
  getUiContainerHeight() {
    return this.uiContainerHeight;
  }
  getRealPixelPosition(modelPixel) {
    return modelPixel - this.divStretchOffset;
  }
  getUiBodyHeight() {
    const gridBodyCon = this.ctrlsService.getGridBodyCtrl();
    const pos = gridBodyCon.getScrollFeature().getVScrollPosition();
    return pos.bottom - pos.top;
  }
  getScrollPositionForPixel(rowTop) {
    if (this.pixelsToShave <= 0) {
      return rowTop;
    }
    const modelMaxScroll = this.modelHeight - this.getUiBodyHeight();
    const scrollPercent = rowTop / modelMaxScroll;
    const scrollPixel = this.maxScrollY * scrollPercent;
    return scrollPixel;
  }
};
__decorateClass([
  Autowired("ctrlsService")
], RowContainerHeightService.prototype, "ctrlsService", 2);
__decorateClass([
  __decorateParam(0, Qualifier("loggerFactory"))
], RowContainerHeightService.prototype, "agWire", 1);
__decorateClass([
  PostConstruct
], RowContainerHeightService.prototype, "postConstruct", 1);
RowContainerHeightService = __decorateClass([
  Bean("rowContainerHeightService")
], RowContainerHeightService);

// community-modules/core/src/rowNodes/selectableService.ts
var SelectableService = class extends BeanStub {
  init() {
    this.addManagedPropertyListener("isRowSelectable", () => this.updateSelectable());
  }
  /**
   * Used by CSRM only, to update selectable state after group state changes.
   */
  updateSelectableAfterGrouping() {
    this.updateSelectable(true);
  }
  updateSelectable(skipLeafNodes = false) {
    const isRowSelecting = !!this.gos.get("rowSelection");
    const isRowSelectable = this.gos.get("isRowSelectable");
    if (!isRowSelecting || !isRowSelectable) {
      return;
    }
    const isGroupSelectsChildren = this.gos.get("groupSelectsChildren");
    const isCsrmGroupSelectsChildren = this.rowModel.getType() === "clientSide" && isGroupSelectsChildren;
    const nodesToDeselect = [];
    const nodeCallback = (node) => {
      if (skipLeafNodes && !node.group) {
        return;
      }
      if (isCsrmGroupSelectsChildren && node.group) {
        const hasSelectableChild = node.childrenAfterGroup.some((rowNode) => rowNode.selectable === true);
        node.setRowSelectable(hasSelectableChild, true);
        return;
      }
      const rowSelectable = isRowSelectable ? isRowSelectable(node) : true;
      node.setRowSelectable(rowSelectable, true);
      if (!rowSelectable && node.isSelected()) {
        nodesToDeselect.push(node);
      }
    };
    if (isCsrmGroupSelectsChildren) {
      const csrm = this.rowModel;
      const changedPath = new ChangedPath(false, csrm.getRootNode());
      changedPath.forEachChangedNodeDepthFirst(nodeCallback, true, true);
    } else {
      this.rowModel.forEachNode(nodeCallback);
    }
    if (nodesToDeselect.length) {
      this.selectionService.setNodesSelected({ nodes: nodesToDeselect, newValue: false, source: "selectableChanged" });
    }
    if (isCsrmGroupSelectsChildren && this.selectionService instanceof SelectionService) {
      this.selectionService.updateGroupsFromChildrenSelections("selectableChanged");
    }
  }
};
__decorateClass([
  Autowired("rowModel")
], SelectableService.prototype, "rowModel", 2);
__decorateClass([
  Autowired("selectionService")
], SelectableService.prototype, "selectionService", 2);
__decorateClass([
  PostConstruct
], SelectableService.prototype, "init", 1);
SelectableService = __decorateClass([
  Bean("selectableService")
], SelectableService);

// community-modules/core/src/pagination/paginationComp.ts
var PaginationComp = class extends Component {
  constructor() {
    super();
    this.previousAndFirstButtonsDisabled = false;
    this.nextButtonDisabled = false;
    this.lastButtonDisabled = false;
    this.areListenersSetup = false;
  }
  postConstruct() {
    const isRtl = this.gos.get("enableRtl");
    this.setTemplate(this.getTemplate());
    const { btFirst, btPrevious, btNext, btLast, pageSizeComp } = this;
    this.activateTabIndex([btFirst, btPrevious, btNext, btLast]);
    btFirst.insertAdjacentElement("afterbegin", createIconNoSpan(isRtl ? "last" : "first", this.gos));
    btPrevious.insertAdjacentElement("afterbegin", createIconNoSpan(isRtl ? "next" : "previous", this.gos));
    btNext.insertAdjacentElement("afterbegin", createIconNoSpan(isRtl ? "previous" : "next", this.gos));
    btLast.insertAdjacentElement("afterbegin", createIconNoSpan(isRtl ? "first" : "last", this.gos));
    this.addManagedPropertyListener("pagination", this.onPaginationChanged.bind(this));
    this.addManagedPropertyListener("suppressPaginationPanel", this.onPaginationChanged.bind(this));
    this.addManagedPropertyListeners(
      ["paginationPageSizeSelector", "paginationAutoPageSize", "suppressPaginationPanel"],
      () => this.onPageSizeRelatedOptionsChange()
    );
    this.pageSizeComp.toggleSelectDisplay(
      this.pageSizeComp.shouldShowPageSizeSelector()
    );
    this.onPaginationChanged();
  }
  onPaginationChanged() {
    const isPaging = this.gos.get("pagination");
    const paginationPanelEnabled = isPaging && !this.gos.get("suppressPaginationPanel");
    this.setDisplayed(paginationPanelEnabled);
    if (!paginationPanelEnabled) {
      return;
    }
    this.setupListeners();
    this.enableOrDisableButtons();
    this.updateRowLabels();
    this.setCurrentPageLabel();
    this.setTotalLabels();
    this.onPageSizeRelatedOptionsChange();
  }
  onPageSizeRelatedOptionsChange() {
    this.pageSizeComp.toggleSelectDisplay(
      this.pageSizeComp.shouldShowPageSizeSelector()
    );
  }
  setupListeners() {
    if (!this.areListenersSetup) {
      this.addManagedListener(this.eventService, Events.EVENT_PAGINATION_CHANGED, this.onPaginationChanged.bind(this));
      [
        { el: this.btFirst, fn: this.onBtFirst.bind(this) },
        { el: this.btPrevious, fn: this.onBtPrevious.bind(this) },
        { el: this.btNext, fn: this.onBtNext.bind(this) },
        { el: this.btLast, fn: this.onBtLast.bind(this) }
      ].forEach((item) => {
        const { el, fn } = item;
        this.addManagedListener(el, "click", fn);
        this.addManagedListener(el, "keydown", (e) => {
          if (e.key === KeyCode.ENTER || e.key === KeyCode.SPACE) {
            e.preventDefault();
            fn();
          }
        });
      });
      this.areListenersSetup = true;
    }
  }
  onBtFirst() {
    if (!this.previousAndFirstButtonsDisabled) {
      this.paginationProxy.goToFirstPage();
    }
  }
  setCurrentPageLabel() {
    const pagesExist = this.paginationProxy.getTotalPages() > 0;
    const currentPage = this.paginationProxy.getCurrentPage();
    const toDisplay = pagesExist ? currentPage + 1 : 0;
    this.lbCurrent.textContent = this.formatNumber(toDisplay);
  }
  formatNumber(value) {
    const userFunc = this.gos.getCallback("paginationNumberFormatter");
    if (userFunc) {
      const params = { value };
      return userFunc(params);
    }
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    const thousandSeparator = localeTextFunc("thousandSeparator", ",");
    const decimalSeparator = localeTextFunc("decimalSeparator", ".");
    return formatNumberCommas(value, thousandSeparator, decimalSeparator);
  }
  getTemplate() {
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    const strPage = localeTextFunc("page", "Page");
    const strTo = localeTextFunc("to", "to");
    const strOf = localeTextFunc("of", "of");
    const strFirst = localeTextFunc("firstPage", "First Page");
    const strPrevious = localeTextFunc("previousPage", "Previous Page");
    const strNext = localeTextFunc("nextPage", "Next Page");
    const strLast = localeTextFunc("lastPage", "Last Page");
    const compId = this.getCompId();
    return (
      /* html */
      `<div class="ag-paging-panel ag-unselectable" id="ag-${compId}">
                <ag-page-size-selector ref="pageSizeComp"></ag-page-size-selector>
                <span class="ag-paging-row-summary-panel" role="status">
                    <span id="ag-${compId}-first-row" ref="lbFirstRowOnPage" class="ag-paging-row-summary-panel-number"></span>
                    <span id="ag-${compId}-to">${strTo}</span>
                    <span id="ag-${compId}-last-row" ref="lbLastRowOnPage" class="ag-paging-row-summary-panel-number"></span>
                    <span id="ag-${compId}-of">${strOf}</span>
                    <span id="ag-${compId}-row-count" ref="lbRecordCount" class="ag-paging-row-summary-panel-number"></span>
                </span>
                <span class="ag-paging-page-summary-panel" role="presentation">
                    <div ref="btFirst" class="ag-button ag-paging-button" role="button" aria-label="${strFirst}"></div>
                    <div ref="btPrevious" class="ag-button ag-paging-button" role="button" aria-label="${strPrevious}"></div>
                    <span class="ag-paging-description" role="status">
                        <span id="ag-${compId}-start-page">${strPage}</span>
                        <span id="ag-${compId}-start-page-number" ref="lbCurrent" class="ag-paging-number"></span>
                        <span id="ag-${compId}-of-page">${strOf}</span>
                        <span id="ag-${compId}-of-page-number" ref="lbTotal" class="ag-paging-number"></span>
                    </span>
                    <div ref="btNext" class="ag-button ag-paging-button" role="button" aria-label="${strNext}"></div>
                    <div ref="btLast" class="ag-button ag-paging-button" role="button" aria-label="${strLast}"></div>
                </span>
            </div>`
    );
  }
  onBtNext() {
    if (!this.nextButtonDisabled) {
      this.paginationProxy.goToNextPage();
    }
  }
  onBtPrevious() {
    if (!this.previousAndFirstButtonsDisabled) {
      this.paginationProxy.goToPreviousPage();
    }
  }
  onBtLast() {
    if (!this.lastButtonDisabled) {
      this.paginationProxy.goToLastPage();
    }
  }
  enableOrDisableButtons() {
    const currentPage = this.paginationProxy.getCurrentPage();
    const maxRowFound = this.paginationProxy.isLastPageFound();
    const totalPages = this.paginationProxy.getTotalPages();
    this.previousAndFirstButtonsDisabled = currentPage === 0;
    this.toggleButtonDisabled(this.btFirst, this.previousAndFirstButtonsDisabled);
    this.toggleButtonDisabled(this.btPrevious, this.previousAndFirstButtonsDisabled);
    const zeroPagesToDisplay = this.isZeroPagesToDisplay();
    const onLastPage = currentPage === totalPages - 1;
    this.nextButtonDisabled = onLastPage || zeroPagesToDisplay;
    this.lastButtonDisabled = !maxRowFound || zeroPagesToDisplay || currentPage === totalPages - 1;
    this.toggleButtonDisabled(this.btNext, this.nextButtonDisabled);
    this.toggleButtonDisabled(this.btLast, this.lastButtonDisabled);
  }
  toggleButtonDisabled(button, disabled) {
    setAriaDisabled(button, disabled);
    button.classList.toggle("ag-disabled", disabled);
  }
  updateRowLabels() {
    const currentPage = this.paginationProxy.getCurrentPage();
    const pageSize = this.paginationProxy.getPageSize();
    const maxRowFound = this.paginationProxy.isLastPageFound();
    const rowCount = this.paginationProxy.isLastPageFound() ? this.paginationProxy.getMasterRowCount() : null;
    let startRow;
    let endRow;
    if (this.isZeroPagesToDisplay()) {
      startRow = endRow = 0;
    } else {
      startRow = pageSize * currentPage + 1;
      endRow = startRow + pageSize - 1;
      if (maxRowFound && endRow > rowCount) {
        endRow = rowCount;
      }
    }
    this.lbFirstRowOnPage.textContent = this.formatNumber(startRow);
    if (this.rowNodeBlockLoader.isLoading()) {
      const translate = this.localeService.getLocaleTextFunc();
      this.lbLastRowOnPage.innerHTML = translate("pageLastRowUnknown", "?");
    } else {
      this.lbLastRowOnPage.textContent = this.formatNumber(endRow);
    }
  }
  isZeroPagesToDisplay() {
    const maxRowFound = this.paginationProxy.isLastPageFound();
    const totalPages = this.paginationProxy.getTotalPages();
    return maxRowFound && totalPages === 0;
  }
  setTotalLabels() {
    const lastPageFound = this.paginationProxy.isLastPageFound();
    const totalPages = this.paginationProxy.getTotalPages();
    const rowCount = lastPageFound ? this.paginationProxy.getMasterRowCount() : null;
    if (rowCount === 1) {
      const firstRow = this.paginationProxy.getRow(0);
      const hiddenGroupRow = firstRow && firstRow.group && !(firstRow.groupData || firstRow.aggData);
      if (hiddenGroupRow) {
        this.setTotalLabelsToZero();
        return;
      }
    }
    if (lastPageFound) {
      this.lbTotal.textContent = this.formatNumber(totalPages);
      this.lbRecordCount.textContent = this.formatNumber(rowCount);
    } else {
      const moreText = this.localeService.getLocaleTextFunc()("more", "more");
      this.lbTotal.innerHTML = moreText;
      this.lbRecordCount.innerHTML = moreText;
    }
  }
  setTotalLabelsToZero() {
    this.lbFirstRowOnPage.textContent = this.formatNumber(0);
    this.lbCurrent.textContent = this.formatNumber(0);
    this.lbLastRowOnPage.textContent = this.formatNumber(0);
    this.lbTotal.textContent = this.formatNumber(0);
    this.lbRecordCount.textContent = this.formatNumber(0);
  }
};
__decorateClass([
  Autowired("paginationProxy")
], PaginationComp.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("rowNodeBlockLoader")
], PaginationComp.prototype, "rowNodeBlockLoader", 2);
__decorateClass([
  RefSelector("btFirst")
], PaginationComp.prototype, "btFirst", 2);
__decorateClass([
  RefSelector("btPrevious")
], PaginationComp.prototype, "btPrevious", 2);
__decorateClass([
  RefSelector("btNext")
], PaginationComp.prototype, "btNext", 2);
__decorateClass([
  RefSelector("btLast")
], PaginationComp.prototype, "btLast", 2);
__decorateClass([
  RefSelector("lbRecordCount")
], PaginationComp.prototype, "lbRecordCount", 2);
__decorateClass([
  RefSelector("lbFirstRowOnPage")
], PaginationComp.prototype, "lbFirstRowOnPage", 2);
__decorateClass([
  RefSelector("lbLastRowOnPage")
], PaginationComp.prototype, "lbLastRowOnPage", 2);
__decorateClass([
  RefSelector("lbCurrent")
], PaginationComp.prototype, "lbCurrent", 2);
__decorateClass([
  RefSelector("lbTotal")
], PaginationComp.prototype, "lbTotal", 2);
__decorateClass([
  RefSelector("pageSizeComp")
], PaginationComp.prototype, "pageSizeComp", 2);
__decorateClass([
  PostConstruct
], PaginationComp.prototype, "postConstruct", 1);

// community-modules/core/src/rendering/overlays/overlayWrapperComponent.ts
var _OverlayWrapperComponent = class _OverlayWrapperComponent extends Component {
  constructor() {
    super(_OverlayWrapperComponent.TEMPLATE);
    this.inProgress = false;
    this.destroyRequested = false;
  }
  updateLayoutClasses(cssClass, params) {
    const overlayWrapperClassList = this.eOverlayWrapper.classList;
    overlayWrapperClassList.toggle("ag-layout-auto-height" /* AUTO_HEIGHT */, params.autoHeight);
    overlayWrapperClassList.toggle("ag-layout-normal" /* NORMAL */, params.normal);
    overlayWrapperClassList.toggle("ag-layout-print" /* PRINT */, params.print);
  }
  postConstruct() {
    this.createManagedBean(new LayoutFeature(this));
    this.setDisplayed(false, { skipAriaHidden: true });
    this.overlayService.registerOverlayWrapperComp(this);
  }
  setWrapperTypeClass(overlayWrapperCssClass) {
    const overlayWrapperClassList = this.eOverlayWrapper.classList;
    if (this.activeOverlayWrapperCssClass) {
      overlayWrapperClassList.toggle(this.activeOverlayWrapperCssClass, false);
    }
    this.activeOverlayWrapperCssClass = overlayWrapperCssClass;
    overlayWrapperClassList.toggle(overlayWrapperCssClass, true);
  }
  showOverlay(overlayComp, overlayWrapperCssClass, updateListenerDestroyFunc) {
    if (this.inProgress) {
      return;
    }
    this.setWrapperTypeClass(overlayWrapperCssClass);
    this.destroyActiveOverlay();
    this.inProgress = true;
    if (overlayComp) {
      overlayComp.then((comp) => {
        this.inProgress = false;
        this.eOverlayWrapper.appendChild(comp.getGui());
        this.activeOverlay = comp;
        this.updateListenerDestroyFunc = updateListenerDestroyFunc;
        if (this.destroyRequested) {
          this.destroyRequested = false;
          this.destroyActiveOverlay();
        }
      });
    }
    this.setDisplayed(true, { skipAriaHidden: true });
  }
  destroyActiveOverlay() {
    var _a;
    if (this.inProgress) {
      this.destroyRequested = true;
      return;
    }
    if (!this.activeOverlay) {
      return;
    }
    this.activeOverlay = this.getContext().destroyBean(this.activeOverlay);
    (_a = this.updateListenerDestroyFunc) == null ? void 0 : _a.call(this);
    clearElement(this.eOverlayWrapper);
  }
  hideOverlay() {
    this.destroyActiveOverlay();
    this.setDisplayed(false, { skipAriaHidden: true });
  }
  destroy() {
    this.destroyActiveOverlay();
    super.destroy();
  }
};
// wrapping in outer div, and wrapper, is needed to center the loading icon
_OverlayWrapperComponent.TEMPLATE = /* html */
`
        <div class="ag-overlay" role="presentation">
            <div class="ag-overlay-panel" role="presentation">
                <div class="ag-overlay-wrapper" ref="eOverlayWrapper" role="presentation"></div>
            </div>
        </div>`;
__decorateClass([
  Autowired("overlayService")
], _OverlayWrapperComponent.prototype, "overlayService", 2);
__decorateClass([
  RefSelector("eOverlayWrapper")
], _OverlayWrapperComponent.prototype, "eOverlayWrapper", 2);
__decorateClass([
  PostConstruct
], _OverlayWrapperComponent.prototype, "postConstruct", 1);
var OverlayWrapperComponent = _OverlayWrapperComponent;

// community-modules/core/src/entities/rowPositionUtils.ts
var RowPositionUtils = class extends BeanStub {
  getFirstRow() {
    let rowIndex = 0;
    let rowPinned;
    if (this.pinnedRowModel.getPinnedTopRowCount()) {
      rowPinned = "top";
    } else if (this.rowModel.getRowCount()) {
      rowPinned = null;
      rowIndex = this.paginationProxy.getPageFirstRow();
    } else if (this.pinnedRowModel.getPinnedBottomRowCount()) {
      rowPinned = "bottom";
    }
    return rowPinned === void 0 ? null : { rowIndex, rowPinned };
  }
  getLastRow() {
    let rowIndex;
    let rowPinned = null;
    const pinnedBottomCount = this.pinnedRowModel.getPinnedBottomRowCount();
    const pinnedTopCount = this.pinnedRowModel.getPinnedTopRowCount();
    if (pinnedBottomCount) {
      rowPinned = "bottom";
      rowIndex = pinnedBottomCount - 1;
    } else if (this.rowModel.getRowCount()) {
      rowPinned = null;
      rowIndex = this.paginationProxy.getPageLastRow();
    } else if (pinnedTopCount) {
      rowPinned = "top";
      rowIndex = pinnedTopCount - 1;
    }
    return rowIndex === void 0 ? null : { rowIndex, rowPinned };
  }
  getRowNode(gridRow) {
    switch (gridRow.rowPinned) {
      case "top":
        return this.pinnedRowModel.getPinnedTopRowData()[gridRow.rowIndex];
      case "bottom":
        return this.pinnedRowModel.getPinnedBottomRowData()[gridRow.rowIndex];
      default:
        return this.rowModel.getRow(gridRow.rowIndex);
    }
  }
  sameRow(rowA, rowB) {
    if (!rowA && !rowB) {
      return true;
    }
    if (rowA && !rowB || !rowA && rowB) {
      return false;
    }
    return rowA.rowIndex === rowB.rowIndex && rowA.rowPinned == rowB.rowPinned;
  }
  // tests if this row selection is before the other row selection
  before(rowA, rowB) {
    switch (rowA.rowPinned) {
      case "top":
        if (rowB.rowPinned !== "top") {
          return true;
        }
        break;
      case "bottom":
        if (rowB.rowPinned !== "bottom") {
          return false;
        }
        break;
      default:
        if (exists(rowB.rowPinned)) {
          return rowB.rowPinned !== "top";
        }
        break;
    }
    return rowA.rowIndex < rowB.rowIndex;
  }
};
__decorateClass([
  Autowired("rowModel")
], RowPositionUtils.prototype, "rowModel", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], RowPositionUtils.prototype, "pinnedRowModel", 2);
__decorateClass([
  Autowired("paginationProxy")
], RowPositionUtils.prototype, "paginationProxy", 2);
RowPositionUtils = __decorateClass([
  Bean("rowPositionUtils")
], RowPositionUtils);

// community-modules/core/src/entities/cellPositionUtils.ts
var CellPositionUtils = class extends BeanStub {
  createId(cellPosition) {
    const { rowIndex, rowPinned, column } = cellPosition;
    return this.createIdFromValues({ rowIndex, column, rowPinned });
  }
  createIdFromValues(cellPosition) {
    const { rowIndex, rowPinned, column } = cellPosition;
    return `${rowIndex}.${rowPinned == null ? "null" : rowPinned}.${column.getId()}`;
  }
  equals(cellA, cellB) {
    const colsMatch = cellA.column === cellB.column;
    const floatingMatch = cellA.rowPinned === cellB.rowPinned;
    const indexMatch = cellA.rowIndex === cellB.rowIndex;
    return colsMatch && floatingMatch && indexMatch;
  }
};
CellPositionUtils = __decorateClass([
  Bean("cellPositionUtils")
], CellPositionUtils);

// community-modules/core/src/undoRedo/undoRedoStack.ts
var UndoRedoAction = class {
  constructor(cellValueChanges) {
    this.cellValueChanges = cellValueChanges;
  }
};
var RangeUndoRedoAction = class extends UndoRedoAction {
  constructor(cellValueChanges, initialRange, finalRange, ranges) {
    super(cellValueChanges);
    this.initialRange = initialRange;
    this.finalRange = finalRange;
    this.ranges = ranges;
  }
};
var _UndoRedoStack = class _UndoRedoStack {
  constructor(maxStackSize) {
    this.actionStack = [];
    this.maxStackSize = maxStackSize ? maxStackSize : _UndoRedoStack.DEFAULT_STACK_SIZE;
    this.actionStack = new Array(this.maxStackSize);
  }
  pop() {
    return this.actionStack.pop();
  }
  push(item) {
    const shouldAddActions = item.cellValueChanges && item.cellValueChanges.length > 0;
    if (!shouldAddActions) {
      return;
    }
    if (this.actionStack.length === this.maxStackSize) {
      this.actionStack.shift();
    }
    this.actionStack.push(item);
  }
  clear() {
    this.actionStack = [];
  }
  getCurrentStackSize() {
    return this.actionStack.length;
  }
};
_UndoRedoStack.DEFAULT_STACK_SIZE = 10;
var UndoRedoStack = _UndoRedoStack;

// community-modules/core/src/undoRedo/undoRedoService.ts
var UndoRedoService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.cellValueChanges = [];
    this.activeCellEdit = null;
    this.activeRowEdit = null;
    this.isPasting = false;
    this.isRangeInAction = false;
    this.onCellValueChanged = (event) => {
      const eventCell = { column: event.column, rowIndex: event.rowIndex, rowPinned: event.rowPinned };
      const isCellEditing = this.activeCellEdit !== null && this.cellPositionUtils.equals(this.activeCellEdit, eventCell);
      const isRowEditing = this.activeRowEdit !== null && this.rowPositionUtils.sameRow(this.activeRowEdit, eventCell);
      const shouldCaptureAction = isCellEditing || isRowEditing || this.isPasting || this.isRangeInAction;
      if (!shouldCaptureAction) {
        return;
      }
      const { rowPinned, rowIndex, column, oldValue, value } = event;
      const cellValueChange = {
        rowPinned,
        rowIndex,
        columnId: column.getColId(),
        newValue: value,
        oldValue
      };
      this.cellValueChanges.push(cellValueChange);
    };
    this.clearStacks = () => {
      this.undoStack.clear();
      this.redoStack.clear();
    };
  }
  init() {
    if (!this.gos.get("undoRedoCellEditing")) {
      return;
    }
    const undoRedoLimit = this.gos.get("undoRedoCellEditingLimit");
    if (undoRedoLimit <= 0) {
      return;
    }
    this.undoStack = new UndoRedoStack(undoRedoLimit);
    this.redoStack = new UndoRedoStack(undoRedoLimit);
    this.addRowEditingListeners();
    this.addCellEditingListeners();
    this.addPasteListeners();
    this.addFillListeners();
    this.addCellKeyListeners();
    this.addManagedListener(this.eventService, Events.EVENT_CELL_VALUE_CHANGED, this.onCellValueChanged);
    this.addManagedListener(this.eventService, Events.EVENT_MODEL_UPDATED, (e) => {
      if (!e.keepUndoRedoStack) {
        this.clearStacks();
      }
    });
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, this.clearStacks);
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, this.clearStacks);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_GROUP_OPENED, this.clearStacks);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.clearStacks);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_MOVED, this.clearStacks);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PINNED, this.clearStacks);
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VISIBLE, this.clearStacks);
    this.addManagedListener(this.eventService, Events.EVENT_ROW_DRAG_END, this.clearStacks);
    this.ctrlsService.whenReady((p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
    });
  }
  getCurrentUndoStackSize() {
    return this.undoStack ? this.undoStack.getCurrentStackSize() : 0;
  }
  getCurrentRedoStackSize() {
    return this.redoStack ? this.redoStack.getCurrentStackSize() : 0;
  }
  undo(source) {
    const startEvent = {
      type: Events.EVENT_UNDO_STARTED,
      source
    };
    this.eventService.dispatchEvent(startEvent);
    const operationPerformed = this.undoRedo(this.undoStack, this.redoStack, "initialRange", "oldValue", "undo");
    const endEvent = {
      type: Events.EVENT_UNDO_ENDED,
      source,
      operationPerformed
    };
    this.eventService.dispatchEvent(endEvent);
  }
  redo(source) {
    const startEvent = {
      type: Events.EVENT_REDO_STARTED,
      source
    };
    this.eventService.dispatchEvent(startEvent);
    const operationPerformed = this.undoRedo(this.redoStack, this.undoStack, "finalRange", "newValue", "redo");
    const endEvent = {
      type: Events.EVENT_REDO_ENDED,
      source,
      operationPerformed
    };
    this.eventService.dispatchEvent(endEvent);
  }
  undoRedo(undoRedoStack, opposingUndoRedoStack, rangeProperty, cellValueChangeProperty, source) {
    if (!undoRedoStack) {
      return false;
    }
    const undoRedoAction = undoRedoStack.pop();
    if (!undoRedoAction || !undoRedoAction.cellValueChanges) {
      return false;
    }
    this.processAction(undoRedoAction, (cellValueChange) => cellValueChange[cellValueChangeProperty], source);
    if (undoRedoAction instanceof RangeUndoRedoAction) {
      this.processRange(this.rangeService, undoRedoAction.ranges || [undoRedoAction[rangeProperty]]);
    } else {
      this.processCell(undoRedoAction.cellValueChanges);
    }
    opposingUndoRedoStack.push(undoRedoAction);
    return true;
  }
  processAction(action, valueExtractor, source) {
    action.cellValueChanges.forEach((cellValueChange) => {
      const { rowIndex, rowPinned, columnId } = cellValueChange;
      const rowPosition = { rowIndex, rowPinned };
      const currentRow = this.rowPositionUtils.getRowNode(rowPosition);
      if (!currentRow.displayed) {
        return;
      }
      currentRow.setDataValue(columnId, valueExtractor(cellValueChange), source);
    });
  }
  processRange(rangeService, ranges) {
    let lastFocusedCell;
    rangeService.removeAllCellRanges(true);
    ranges.forEach((range, idx) => {
      if (!range) {
        return;
      }
      const startRow = range.startRow;
      const endRow = range.endRow;
      if (idx === ranges.length - 1) {
        lastFocusedCell = {
          rowPinned: startRow.rowPinned,
          rowIndex: startRow.rowIndex,
          columnId: range.startColumn.getColId()
        };
        this.setLastFocusedCell(lastFocusedCell);
      }
      const cellRangeParams = {
        rowStartIndex: startRow.rowIndex,
        rowStartPinned: startRow.rowPinned,
        rowEndIndex: endRow.rowIndex,
        rowEndPinned: endRow.rowPinned,
        columnStart: range.startColumn,
        columns: range.columns
      };
      rangeService.addCellRange(cellRangeParams);
    });
  }
  processCell(cellValueChanges) {
    const cellValueChange = cellValueChanges[0];
    const { rowIndex, rowPinned } = cellValueChange;
    const rowPosition = { rowIndex, rowPinned };
    const row = this.rowPositionUtils.getRowNode(rowPosition);
    const lastFocusedCell = {
      rowPinned: cellValueChange.rowPinned,
      rowIndex: row.rowIndex,
      columnId: cellValueChange.columnId
    };
    this.setLastFocusedCell(lastFocusedCell, this.rangeService);
  }
  setLastFocusedCell(lastFocusedCell, rangeService) {
    const { rowIndex, columnId, rowPinned } = lastFocusedCell;
    const scrollFeature = this.gridBodyCtrl.getScrollFeature();
    const column = this.columnModel.getGridColumn(columnId);
    if (!column) {
      return;
    }
    scrollFeature.ensureIndexVisible(rowIndex);
    scrollFeature.ensureColumnVisible(column);
    const cellPosition = { rowIndex, column, rowPinned };
    this.focusService.setFocusedCell(__spreadProps(__spreadValues({}, cellPosition), { forceBrowserFocus: true }));
    rangeService == null ? void 0 : rangeService.setRangeToCell(cellPosition);
  }
  addRowEditingListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_ROW_EDITING_STARTED, (e) => {
      this.activeRowEdit = { rowIndex: e.rowIndex, rowPinned: e.rowPinned };
    });
    this.addManagedListener(this.eventService, Events.EVENT_ROW_EDITING_STOPPED, () => {
      const action = new UndoRedoAction(this.cellValueChanges);
      this.pushActionsToUndoStack(action);
      this.activeRowEdit = null;
    });
  }
  addCellEditingListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_CELL_EDITING_STARTED, (e) => {
      this.activeCellEdit = { column: e.column, rowIndex: e.rowIndex, rowPinned: e.rowPinned };
    });
    this.addManagedListener(this.eventService, Events.EVENT_CELL_EDITING_STOPPED, (e) => {
      this.activeCellEdit = null;
      const shouldPushAction = e.valueChanged && !this.activeRowEdit && !this.isPasting && !this.isRangeInAction;
      if (shouldPushAction) {
        const action = new UndoRedoAction(this.cellValueChanges);
        this.pushActionsToUndoStack(action);
      }
    });
  }
  addPasteListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_PASTE_START, () => {
      this.isPasting = true;
    });
    this.addManagedListener(this.eventService, Events.EVENT_PASTE_END, () => {
      const action = new UndoRedoAction(this.cellValueChanges);
      this.pushActionsToUndoStack(action);
      this.isPasting = false;
    });
  }
  addFillListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_FILL_START, () => {
      this.isRangeInAction = true;
    });
    this.addManagedListener(this.eventService, Events.EVENT_FILL_END, (event) => {
      const action = new RangeUndoRedoAction(this.cellValueChanges, event.initialRange, event.finalRange);
      this.pushActionsToUndoStack(action);
      this.isRangeInAction = false;
    });
  }
  addCellKeyListeners() {
    this.addManagedListener(this.eventService, Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_START, () => {
      this.isRangeInAction = true;
    });
    this.addManagedListener(this.eventService, Events.EVENT_KEY_SHORTCUT_CHANGED_CELL_END, () => {
      let action;
      if (this.rangeService && this.gos.get("enableRangeSelection")) {
        action = new RangeUndoRedoAction(this.cellValueChanges, void 0, void 0, [...this.rangeService.getCellRanges()]);
      } else {
        action = new UndoRedoAction(this.cellValueChanges);
      }
      this.pushActionsToUndoStack(action);
      this.isRangeInAction = false;
    });
  }
  pushActionsToUndoStack(action) {
    this.undoStack.push(action);
    this.cellValueChanges = [];
    this.redoStack.clear();
  }
};
__decorateClass([
  Autowired("focusService")
], UndoRedoService.prototype, "focusService", 2);
__decorateClass([
  Autowired("ctrlsService")
], UndoRedoService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("cellPositionUtils")
], UndoRedoService.prototype, "cellPositionUtils", 2);
__decorateClass([
  Autowired("rowPositionUtils")
], UndoRedoService.prototype, "rowPositionUtils", 2);
__decorateClass([
  Autowired("columnModel")
], UndoRedoService.prototype, "columnModel", 2);
__decorateClass([
  Optional("rangeService")
], UndoRedoService.prototype, "rangeService", 2);
__decorateClass([
  PostConstruct
], UndoRedoService.prototype, "init", 1);
UndoRedoService = __decorateClass([
  Bean("undoRedoService")
], UndoRedoService);

// community-modules/core/src/headerRendering/common/headerPosition.ts
var HeaderPositionUtils = class extends BeanStub {
  findHeader(focusedHeader, direction) {
    let nextColumn;
    let getColMethod;
    if (focusedHeader.column instanceof ColumnGroup) {
      nextColumn = this.columnModel.getDisplayedGroupAtDirection(focusedHeader.column, direction);
    } else {
      getColMethod = `getDisplayedCol${direction}`;
      nextColumn = this.columnModel[getColMethod](focusedHeader.column);
    }
    if (!nextColumn) {
      return;
    }
    let { headerRowIndex } = focusedHeader;
    if (this.getHeaderRowType(headerRowIndex) !== "filter" /* FLOATING_FILTER */) {
      const columnsInPath = [nextColumn];
      while (nextColumn.getParent()) {
        nextColumn = nextColumn.getParent();
        columnsInPath.push(nextColumn);
      }
      nextColumn = columnsInPath[columnsInPath.length - 1 - headerRowIndex];
    }
    const { column, headerRowIndex: indexToFocus } = this.getHeaderIndexToFocus(nextColumn, headerRowIndex);
    return {
      column,
      headerRowIndex: indexToFocus
    };
  }
  getHeaderIndexToFocus(column, currentIndex) {
    let nextColumn;
    if (column instanceof ColumnGroup && this.isAnyChildSpanningHeaderHeight(column) && column.isPadding()) {
      const targetColumn = column;
      nextColumn = targetColumn.getLeafColumns()[0];
      let col = nextColumn;
      while (col !== targetColumn) {
        currentIndex++;
        col = col.getParent();
      }
    }
    return {
      column: nextColumn || column,
      headerRowIndex: currentIndex
    };
  }
  isAnyChildSpanningHeaderHeight(columnGroup) {
    if (!columnGroup) {
      return false;
    }
    return columnGroup.getLeafColumns().some((col) => col.isSpanHeaderHeight());
  }
  getColumnVisibleParent(currentColumn, currentIndex) {
    const currentRowType = this.getHeaderRowType(currentIndex);
    const isFloatingFilter = currentRowType === "filter" /* FLOATING_FILTER */;
    const isColumn = currentRowType === "column" /* COLUMN */;
    let nextFocusColumn = isFloatingFilter ? currentColumn : currentColumn.getParent();
    let nextRow = currentIndex - 1;
    let headerRowIndexWithoutSpan = nextRow;
    if (isColumn && this.isAnyChildSpanningHeaderHeight(currentColumn.getParent())) {
      while (nextFocusColumn && nextFocusColumn.isPadding()) {
        nextFocusColumn = nextFocusColumn.getParent();
        nextRow--;
      }
      headerRowIndexWithoutSpan = nextRow;
      if (nextRow < 0) {
        nextFocusColumn = currentColumn;
        nextRow = currentIndex;
        headerRowIndexWithoutSpan = void 0;
      }
    }
    return { column: nextFocusColumn, headerRowIndex: nextRow, headerRowIndexWithoutSpan };
  }
  getColumnVisibleChild(column, currentIndex, direction = "After") {
    const currentRowType = this.getHeaderRowType(currentIndex);
    let nextFocusColumn = column;
    let nextRow = currentIndex + 1;
    let headerRowIndexWithoutSpan = nextRow;
    if (currentRowType === "group" /* COLUMN_GROUP */) {
      const leafColumns = column.getDisplayedLeafColumns();
      const leafColumn = direction === "After" ? leafColumns[0] : last(leafColumns);
      const columnsInTheWay = [];
      let currentColumn = leafColumn;
      while (currentColumn.getParent() !== column) {
        currentColumn = currentColumn.getParent();
        columnsInTheWay.push(currentColumn);
      }
      nextFocusColumn = leafColumn;
      if (leafColumn.isSpanHeaderHeight()) {
        for (let i = columnsInTheWay.length - 1; i >= 0; i--) {
          const colToFocus = columnsInTheWay[i];
          if (!colToFocus.isPadding()) {
            nextFocusColumn = colToFocus;
            break;
          }
          nextRow++;
        }
      } else {
        nextFocusColumn = last(columnsInTheWay);
        if (!nextFocusColumn) {
          nextFocusColumn = leafColumn;
        }
      }
    }
    return { column: nextFocusColumn, headerRowIndex: nextRow, headerRowIndexWithoutSpan };
  }
  getHeaderRowType(rowIndex) {
    const centerHeaderContainer = this.ctrlsService.getHeaderRowContainerCtrl();
    if (centerHeaderContainer) {
      return centerHeaderContainer.getRowType(rowIndex);
    }
  }
  findColAtEdgeForHeaderRow(level, position) {
    const displayedColumns = this.columnModel.getAllDisplayedColumns();
    const column = displayedColumns[position === "start" ? 0 : displayedColumns.length - 1];
    if (!column) {
      return;
    }
    const childContainer = this.ctrlsService.getHeaderRowContainerCtrl(column.getPinned());
    const type = childContainer.getRowType(level);
    if (type == "group" /* COLUMN_GROUP */) {
      const columnGroup = this.columnModel.getColumnGroupAtLevel(column, level);
      return {
        headerRowIndex: level,
        column: columnGroup
      };
    }
    return {
      // if type==null, means the header level didn't exist
      headerRowIndex: type == null ? -1 : level,
      column
    };
  }
};
__decorateClass([
  Autowired("columnModel")
], HeaderPositionUtils.prototype, "columnModel", 2);
__decorateClass([
  Autowired("ctrlsService")
], HeaderPositionUtils.prototype, "ctrlsService", 2);
HeaderPositionUtils = __decorateClass([
  Bean("headerPositionUtils")
], HeaderPositionUtils);

// community-modules/core/src/columns/columnDefFactory.ts
var ColumnDefFactory = class {
  buildColumnDefs(cols, rowGroupColumns, pivotColumns) {
    const res = [];
    const colGroupDefs = {};
    cols.forEach((col) => {
      const colDef = this.createDefFromColumn(col, rowGroupColumns, pivotColumns);
      let addToResult = true;
      let childDef = colDef;
      let pointer = col.getOriginalParent();
      let lastPointer = null;
      while (pointer) {
        let parentDef = null;
        if (pointer.isPadding()) {
          pointer = pointer.getOriginalParent();
          continue;
        }
        const existingParentDef = colGroupDefs[pointer.getGroupId()];
        if (existingParentDef) {
          existingParentDef.children.push(childDef);
          addToResult = false;
          break;
        }
        parentDef = this.createDefFromGroup(pointer);
        if (parentDef) {
          parentDef.children = [childDef];
          colGroupDefs[parentDef.groupId] = parentDef;
          childDef = parentDef;
          pointer = pointer.getOriginalParent();
        }
        if (pointer != null && lastPointer === pointer) {
          addToResult = false;
          break;
        }
        lastPointer = pointer;
      }
      if (addToResult) {
        res.push(childDef);
      }
    });
    return res;
  }
  createDefFromGroup(group) {
    const defCloned = deepCloneDefinition(group.getColGroupDef(), ["children"]);
    if (defCloned) {
      defCloned.groupId = group.getGroupId();
    }
    return defCloned;
  }
  createDefFromColumn(col, rowGroupColumns, pivotColumns) {
    const colDefCloned = deepCloneDefinition(col.getColDef());
    colDefCloned.colId = col.getColId();
    colDefCloned.width = col.getActualWidth();
    colDefCloned.rowGroup = col.isRowGroupActive();
    colDefCloned.rowGroupIndex = col.isRowGroupActive() ? rowGroupColumns.indexOf(col) : null;
    colDefCloned.pivot = col.isPivotActive();
    colDefCloned.pivotIndex = col.isPivotActive() ? pivotColumns.indexOf(col) : null;
    colDefCloned.aggFunc = col.isValueActive() ? col.getAggFunc() : null;
    colDefCloned.hide = col.isVisible() ? void 0 : true;
    colDefCloned.pinned = col.isPinned() ? col.getPinned() : null;
    colDefCloned.sort = col.getSort() ? col.getSort() : null;
    colDefCloned.sortIndex = col.getSortIndex() != null ? col.getSortIndex() : null;
    return colDefCloned;
  }
};
ColumnDefFactory = __decorateClass([
  Bean("columnDefFactory")
], ColumnDefFactory);

// community-modules/core/src/rendering/row/rowCssClassCalculator.ts
var RowCssClassCalculator = class {
  getInitialRowClasses(params) {
    const classes = [];
    if (exists(params.extraCssClass)) {
      classes.push(params.extraCssClass);
    }
    classes.push("ag-row");
    classes.push(params.rowFocused ? "ag-row-focus" : "ag-row-no-focus");
    if (params.fadeRowIn) {
      classes.push("ag-opacity-zero");
    }
    classes.push(params.rowIsEven ? "ag-row-even" : "ag-row-odd");
    if (params.rowNode.isRowPinned()) {
      classes.push("ag-row-pinned");
    }
    if (params.rowNode.isSelected()) {
      classes.push("ag-row-selected");
    }
    if (params.rowNode.footer) {
      classes.push("ag-row-footer");
    }
    classes.push("ag-row-level-" + params.rowLevel);
    if (params.rowNode.stub) {
      classes.push("ag-row-loading");
    }
    if (params.fullWidthRow) {
      classes.push("ag-full-width-row");
    }
    if (params.expandable) {
      classes.push("ag-row-group");
      classes.push(params.rowNode.expanded ? "ag-row-group-expanded" : "ag-row-group-contracted");
    }
    if (params.rowNode.dragging) {
      classes.push("ag-row-dragging");
    }
    pushAll(classes, this.processClassesFromGridOptions(params.rowNode));
    pushAll(classes, this.preProcessRowClassRules(params.rowNode));
    classes.push(params.printLayout ? "ag-row-position-relative" : "ag-row-position-absolute");
    if (params.firstRowOnPage) {
      classes.push("ag-row-first");
    }
    if (params.lastRowOnPage) {
      classes.push("ag-row-last");
    }
    if (params.fullWidthRow) {
      if (params.pinned === "left") {
        classes.push("ag-cell-last-left-pinned");
      }
      if (params.pinned === "right") {
        classes.push("ag-cell-first-right-pinned");
      }
    }
    return classes;
  }
  processClassesFromGridOptions(rowNode) {
    const res = [];
    const process = (rowCls) => {
      if (typeof rowCls === "string") {
        res.push(rowCls);
      } else if (Array.isArray(rowCls)) {
        rowCls.forEach((e) => res.push(e));
      }
    };
    const rowClass = this.gos.get("rowClass");
    if (rowClass) {
      if (typeof rowClass === "function") {
        console.warn("AG Grid: rowClass should not be a function, please use getRowClass instead");
        return [];
      }
      process(rowClass);
    }
    const rowClassFunc = this.gos.getCallback("getRowClass");
    if (rowClassFunc) {
      const params = {
        data: rowNode.data,
        node: rowNode,
        rowIndex: rowNode.rowIndex
      };
      const rowClassFuncResult = rowClassFunc(params);
      process(rowClassFuncResult);
    }
    return res;
  }
  preProcessRowClassRules(rowNode) {
    const res = [];
    this.processRowClassRules(
      rowNode,
      (className) => {
        res.push(className);
      },
      (className) => {
      }
    );
    return res;
  }
  processRowClassRules(rowNode, onApplicableClass, onNotApplicableClass) {
    const rowClassParams = this.gos.addGridCommonParams({
      data: rowNode.data,
      node: rowNode,
      rowIndex: rowNode.rowIndex
    });
    this.stylingService.processClassRules(
      void 0,
      this.gos.get("rowClassRules"),
      rowClassParams,
      onApplicableClass,
      onNotApplicableClass
    );
  }
  calculateRowLevel(rowNode) {
    if (rowNode.group) {
      return rowNode.level;
    }
    return rowNode.parent ? rowNode.parent.level + 1 : 0;
  }
};
__decorateClass([
  Autowired("stylingService")
], RowCssClassCalculator.prototype, "stylingService", 2);
__decorateClass([
  Autowired("gridOptionsService")
], RowCssClassCalculator.prototype, "gos", 2);
RowCssClassCalculator = __decorateClass([
  Bean("rowCssClassCalculator")
], RowCssClassCalculator);

// community-modules/core/src/rowNodes/rowNodeSorter.ts
var RowNodeSorter = class extends BeanStub {
  init() {
    this.isAccentedSort = this.gos.get("accentedSort");
    this.primaryColumnsSortGroups = this.gos.isColumnsSortingCoupledToGroup();
    this.addManagedPropertyListener("accentedSort", (propChange) => this.isAccentedSort = propChange.currentValue);
    this.addManagedPropertyListener("autoGroupColumnDef", () => this.primaryColumnsSortGroups = this.gos.isColumnsSortingCoupledToGroup());
  }
  doFullSort(rowNodes, sortOptions) {
    const mapper = (rowNode, pos) => ({ currentPos: pos, rowNode });
    const sortedRowNodes = rowNodes.map(mapper);
    sortedRowNodes.sort(this.compareRowNodes.bind(this, sortOptions));
    return sortedRowNodes.map((item) => item.rowNode);
  }
  compareRowNodes(sortOptions, sortedNodeA, sortedNodeB) {
    const nodeA = sortedNodeA.rowNode;
    const nodeB = sortedNodeB.rowNode;
    for (let i = 0, len = sortOptions.length; i < len; i++) {
      const sortOption = sortOptions[i];
      const isDescending = sortOption.sort === "desc";
      const valueA = this.getValue(nodeA, sortOption.column);
      const valueB = this.getValue(nodeB, sortOption.column);
      let comparatorResult;
      const providedComparator = this.getComparator(sortOption, nodeA);
      if (providedComparator) {
        comparatorResult = providedComparator(valueA, valueB, nodeA, nodeB, isDescending);
      } else {
        comparatorResult = _.defaultComparator(valueA, valueB, this.isAccentedSort);
      }
      const validResult = !isNaN(comparatorResult);
      if (validResult && comparatorResult !== 0) {
        return sortOption.sort === "asc" ? comparatorResult : comparatorResult * -1;
      }
    }
    return sortedNodeA.currentPos - sortedNodeB.currentPos;
  }
  getComparator(sortOption, rowNode) {
    const column = sortOption.column;
    const comparatorOnCol = column.getColDef().comparator;
    if (comparatorOnCol != null) {
      return comparatorOnCol;
    }
    if (!column.getColDef().showRowGroup) {
      return;
    }
    const groupLeafField = !rowNode.group && column.getColDef().field;
    if (!groupLeafField) {
      return;
    }
    const primaryColumn = this.columnModel.getPrimaryColumn(groupLeafField);
    if (!primaryColumn) {
      return;
    }
    return primaryColumn.getColDef().comparator;
  }
  getValue(node, column) {
    var _a, _b;
    if (!this.primaryColumnsSortGroups) {
      return this.valueService.getValue(column, node, false, false);
    }
    const isNodeGroupedAtLevel = node.rowGroupColumn === column;
    if (isNodeGroupedAtLevel) {
      const isGroupRows = this.gos.isGroupUseEntireRow(this.columnModel.isPivotActive());
      if (isGroupRows) {
        const leafChild = (_a = node.allLeafChildren) == null ? void 0 : _a[0];
        if (leafChild) {
          return this.valueService.getValue(column, leafChild, false, false);
        }
        return void 0;
      }
      const displayCol = this.columnModel.getGroupDisplayColumnForGroup(column.getId());
      if (!displayCol) {
        return void 0;
      }
      return (_b = node.groupData) == null ? void 0 : _b[displayCol.getId()];
    }
    if (node.group && column.getColDef().showRowGroup) {
      return void 0;
    }
    return this.valueService.getValue(column, node, false, false);
  }
};
__decorateClass([
  Autowired("valueService")
], RowNodeSorter.prototype, "valueService", 2);
__decorateClass([
  Autowired("columnModel")
], RowNodeSorter.prototype, "columnModel", 2);
__decorateClass([
  PostConstruct
], RowNodeSorter.prototype, "init", 1);
RowNodeSorter = __decorateClass([
  Bean("rowNodeSorter")
], RowNodeSorter);

// community-modules/core/src/ctrlsService.ts
var CtrlsService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.params = {};
    this.ready = false;
    this.readyCallbacks = [];
  }
  checkReady() {
    const params = this.params;
    this.ready = params.gridCtrl != null && params.gridBodyCtrl != null && params.center != null && params.left != null && params.right != null && params.bottomCenter != null && params.bottomLeft != null && params.bottomRight != null && params.topCenter != null && params.topLeft != null && params.topRight != null && params.stickyTopCenter != null && params.stickyTopLeft != null && params.stickyTopRight != null && params.stickyBottomCenter != null && params.stickyBottomLeft != null && params.stickyBottomRight != null && params.centerHeader != null && params.leftHeader != null && params.rightHeader != null && params.fakeHScrollComp != null && params.fakeVScrollComp != null && params.gridHeaderCtrl != null;
    if (this.ready) {
      this.readyCallbacks.forEach((c) => c(params));
      this.readyCallbacks.length = 0;
    }
  }
  whenReady(callback) {
    if (this.ready) {
      callback(this.params);
    } else {
      this.readyCallbacks.push(callback);
    }
  }
  register(ctrlType, ctrl) {
    this.params[ctrlType] = ctrl;
    this.checkReady();
  }
  registerHeaderContainer(ctrl, pinned) {
    switch (pinned) {
      case "left":
        this.params.leftHeader = ctrl;
        break;
      case "right":
        this.params.rightHeader = ctrl;
        break;
      default:
        this.params.centerHeader = ctrl;
        break;
    }
    this.checkReady();
  }
  get(ctrlType) {
    return this.params[ctrlType];
  }
  getParams() {
    return this.params;
  }
  getGridBodyCtrl() {
    return this.params.gridBodyCtrl;
  }
  getHeaderRowContainerCtrls() {
    return [this.params.leftHeader, this.params.rightHeader, this.params.centerHeader];
  }
  getHeaderRowContainerCtrl(pinned) {
    switch (pinned) {
      case "left":
        return this.params.leftHeader;
      case "right":
        return this.params.rightHeader;
      default:
        return this.params.centerHeader;
    }
  }
};
CtrlsService.NAME = "ctrlsService";
CtrlsService = __decorateClass([
  Bean(CtrlsService.NAME)
], CtrlsService);

// community-modules/core/src/ctrlsFactory.ts
var CtrlsFactory = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.registry = {};
  }
  register(meta) {
    this.registry[meta.controllerName] = meta.controllerClass;
  }
  getInstance(name) {
    const ControllerClass = this.registry[name];
    if (ControllerClass == null) {
      return void 0;
    }
    return new ControllerClass();
  }
};
CtrlsFactory = __decorateClass([
  Bean("ctrlsFactory")
], CtrlsFactory);

// community-modules/core/src/gridBodyComp/abstractFakeScrollComp.ts
var AbstractFakeScrollComp = class extends Component {
  constructor(template, direction) {
    super(template);
    this.direction = direction;
    this.hideTimeout = null;
  }
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this));
    this.onScrollVisibilityChanged();
    this.addOrRemoveCssClass("ag-apple-scrollbar", isMacOsUserAgent() || isIOSUserAgent());
  }
  initialiseInvisibleScrollbar() {
    if (this.invisibleScrollbar !== void 0) {
      return;
    }
    this.invisibleScrollbar = isInvisibleScrollbar();
    if (this.invisibleScrollbar) {
      this.hideAndShowInvisibleScrollAsNeeded();
      this.addActiveListenerToggles();
    }
  }
  addActiveListenerToggles() {
    const activateEvents = ["mouseenter", "mousedown", "touchstart"];
    const deactivateEvents = ["mouseleave", "touchend"];
    const eGui = this.getGui();
    activateEvents.forEach(
      (eventName) => this.addManagedListener(
        eGui,
        eventName,
        () => this.addOrRemoveCssClass("ag-scrollbar-active", true)
      )
    );
    deactivateEvents.forEach(
      (eventName) => this.addManagedListener(
        eGui,
        eventName,
        () => this.addOrRemoveCssClass("ag-scrollbar-active", false)
      )
    );
  }
  onScrollVisibilityChanged() {
    if (this.invisibleScrollbar === void 0) {
      this.initialiseInvisibleScrollbar();
    }
    this.animationFrameService.requestAnimationFrame(() => this.setScrollVisible());
  }
  hideAndShowInvisibleScrollAsNeeded() {
    this.addManagedListener(this.eventService, Events.EVENT_BODY_SCROLL, (params) => {
      if (params.direction === this.direction) {
        if (this.hideTimeout !== null) {
          window.clearTimeout(this.hideTimeout);
          this.hideTimeout = null;
        }
        this.addOrRemoveCssClass("ag-scrollbar-scrolling", true);
      }
    });
    this.addManagedListener(this.eventService, Events.EVENT_BODY_SCROLL_END, () => {
      this.hideTimeout = window.setTimeout(() => {
        this.addOrRemoveCssClass("ag-scrollbar-scrolling", false);
        this.hideTimeout = null;
      }, 400);
    });
  }
  attemptSettingScrollPosition(value) {
    const viewport = this.getViewport();
    waitUntil(() => isVisible(viewport), () => this.setScrollPosition(value), 100);
  }
  getViewport() {
    return this.eViewport;
  }
  getContainer() {
    return this.eContainer;
  }
  onScrollCallback(fn) {
    this.addManagedListener(this.getViewport(), "scroll", fn);
  }
};
__decorateClass([
  RefSelector("eViewport")
], AbstractFakeScrollComp.prototype, "eViewport", 2);
__decorateClass([
  RefSelector("eContainer")
], AbstractFakeScrollComp.prototype, "eContainer", 2);
__decorateClass([
  Autowired("scrollVisibleService")
], AbstractFakeScrollComp.prototype, "scrollVisibleService", 2);
__decorateClass([
  Autowired("ctrlsService")
], AbstractFakeScrollComp.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("animationFrameService")
], AbstractFakeScrollComp.prototype, "animationFrameService", 2);

// community-modules/core/src/gridBodyComp/fakeHScrollComp.ts
var _FakeHScrollComp = class _FakeHScrollComp extends AbstractFakeScrollComp {
  constructor() {
    super(_FakeHScrollComp.TEMPLATE, "horizontal");
  }
  postConstruct() {
    super.postConstruct();
    const spacerWidthsListener = this.setFakeHScrollSpacerWidths.bind(this);
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, spacerWidthsListener);
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, spacerWidthsListener);
    this.addManagedListener(this.eventService, Events.EVENT_PINNED_ROW_DATA_CHANGED, this.onPinnedRowDataChanged.bind(this));
    this.addManagedPropertyListener("domLayout", spacerWidthsListener);
    this.ctrlsService.register("fakeHScrollComp", this);
    this.createManagedBean(new CenterWidthFeature((width) => this.eContainer.style.width = `${width}px`));
    this.addManagedPropertyListeners(["suppressHorizontalScroll"], this.onScrollVisibilityChanged.bind(this));
  }
  initialiseInvisibleScrollbar() {
    if (this.invisibleScrollbar !== void 0) {
      return;
    }
    this.enableRtl = this.gos.get("enableRtl");
    super.initialiseInvisibleScrollbar();
    if (this.invisibleScrollbar) {
      this.refreshCompBottom();
    }
  }
  onPinnedRowDataChanged() {
    this.refreshCompBottom();
  }
  refreshCompBottom() {
    if (!this.invisibleScrollbar) {
      return;
    }
    const bottomPinnedHeight = this.pinnedRowModel.getPinnedBottomTotalHeight();
    this.getGui().style.bottom = `${bottomPinnedHeight}px`;
  }
  onScrollVisibilityChanged() {
    super.onScrollVisibilityChanged();
    this.setFakeHScrollSpacerWidths();
  }
  setFakeHScrollSpacerWidths() {
    const vScrollShowing = this.scrollVisibleService.isVerticalScrollShowing();
    let rightSpacing = this.columnModel.getDisplayedColumnsRightWidth();
    const scrollOnRight = !this.enableRtl && vScrollShowing;
    const scrollbarWidth = this.gos.getScrollbarWidth();
    if (scrollOnRight) {
      rightSpacing += scrollbarWidth;
    }
    setFixedWidth(this.eRightSpacer, rightSpacing);
    this.eRightSpacer.classList.toggle("ag-scroller-corner", rightSpacing <= scrollbarWidth);
    let leftSpacing = this.columnModel.getDisplayedColumnsLeftWidth();
    const scrollOnLeft = this.enableRtl && vScrollShowing;
    if (scrollOnLeft) {
      leftSpacing += scrollbarWidth;
    }
    setFixedWidth(this.eLeftSpacer, leftSpacing);
    this.eLeftSpacer.classList.toggle("ag-scroller-corner", leftSpacing <= scrollbarWidth);
  }
  setScrollVisible() {
    const hScrollShowing = this.scrollVisibleService.isHorizontalScrollShowing();
    const invisibleScrollbar2 = this.invisibleScrollbar;
    const isSuppressHorizontalScroll = this.gos.get("suppressHorizontalScroll");
    const scrollbarWidth = hScrollShowing ? this.gos.getScrollbarWidth() || 0 : 0;
    const adjustedScrollbarWidth = scrollbarWidth === 0 && invisibleScrollbar2 ? 16 : scrollbarWidth;
    const scrollContainerSize = !isSuppressHorizontalScroll ? adjustedScrollbarWidth : 0;
    this.addOrRemoveCssClass("ag-scrollbar-invisible", invisibleScrollbar2);
    setFixedHeight(this.getGui(), scrollContainerSize);
    setFixedHeight(this.eViewport, scrollContainerSize);
    setFixedHeight(this.eContainer, scrollContainerSize);
    this.setDisplayed(hScrollShowing, { skipAriaHidden: true });
  }
  getScrollPosition() {
    return getScrollLeft(this.getViewport(), this.enableRtl);
  }
  setScrollPosition(value) {
    if (!isVisible(this.getViewport())) {
      this.attemptSettingScrollPosition(value);
    }
    setScrollLeft(this.getViewport(), value, this.enableRtl);
  }
};
_FakeHScrollComp.TEMPLATE = /* html */
`<div class="ag-body-horizontal-scroll" aria-hidden="true">
            <div class="ag-horizontal-left-spacer" ref="eLeftSpacer"></div>
            <div class="ag-body-horizontal-scroll-viewport" ref="eViewport">
                <div class="ag-body-horizontal-scroll-container" ref="eContainer"></div>
            </div>
            <div class="ag-horizontal-right-spacer" ref="eRightSpacer"></div>
        </div>`;
__decorateClass([
  RefSelector("eLeftSpacer")
], _FakeHScrollComp.prototype, "eLeftSpacer", 2);
__decorateClass([
  RefSelector("eRightSpacer")
], _FakeHScrollComp.prototype, "eRightSpacer", 2);
__decorateClass([
  Autowired("columnModel")
], _FakeHScrollComp.prototype, "columnModel", 2);
__decorateClass([
  Autowired("pinnedRowModel")
], _FakeHScrollComp.prototype, "pinnedRowModel", 2);
__decorateClass([
  PostConstruct
], _FakeHScrollComp.prototype, "postConstruct", 1);
var FakeHScrollComp = _FakeHScrollComp;

// community-modules/core/src/gridBodyComp/pinnedWidthService.ts
var PinnedWidthService = class extends BeanStub {
  postConstruct() {
    const listener = this.checkContainerWidths.bind(this);
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_CHANGED, listener);
    this.addManagedListener(this.eventService, Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED, listener);
    this.addManagedPropertyListener("domLayout", listener);
  }
  checkContainerWidths() {
    const printLayout = this.gos.isDomLayout("print");
    const newLeftWidth = printLayout ? 0 : this.columnModel.getDisplayedColumnsLeftWidth();
    const newRightWidth = printLayout ? 0 : this.columnModel.getDisplayedColumnsRightWidth();
    if (newLeftWidth != this.leftWidth) {
      this.leftWidth = newLeftWidth;
      this.eventService.dispatchEvent({ type: Events.EVENT_LEFT_PINNED_WIDTH_CHANGED });
    }
    if (newRightWidth != this.rightWidth) {
      this.rightWidth = newRightWidth;
      this.eventService.dispatchEvent({ type: Events.EVENT_RIGHT_PINNED_WIDTH_CHANGED });
    }
  }
  getPinnedRightWidth() {
    return this.rightWidth;
  }
  getPinnedLeftWidth() {
    return this.leftWidth;
  }
};
__decorateClass([
  Autowired("columnModel")
], PinnedWidthService.prototype, "columnModel", 2);
__decorateClass([
  PostConstruct
], PinnedWidthService.prototype, "postConstruct", 1);
PinnedWidthService = __decorateClass([
  Bean("pinnedWidthService")
], PinnedWidthService);

// community-modules/core/src/entities/rowNodeEventThrottle.ts
var RowNodeEventThrottle = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.events = [];
  }
  postConstruct() {
    if (this.rowModel.getType() == "clientSide") {
      this.clientSideRowModel = this.rowModel;
    }
  }
  // because the user can call rowNode.setExpanded() many times in one VM turn,
  // we throttle the calls to ClientSideRowModel using animationFrameService. 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 ).
  dispatchExpanded(event, forceSync) {
    if (this.clientSideRowModel == null) {
      this.eventService.dispatchEvent(event);
      return;
    }
    this.events.push(event);
    const func = () => {
      if (this.clientSideRowModel) {
        this.clientSideRowModel.onRowGroupOpened();
      }
      this.events.forEach((e) => this.eventService.dispatchEvent(e));
      this.events = [];
    };
    if (forceSync) {
      func();
    } else {
      if (this.dispatchExpandedDebounced == null) {
        this.dispatchExpandedDebounced = this.animationFrameService.debounce(func);
      }
      this.dispatchExpandedDebounced();
    }
  }
};
__decorateClass([
  Autowired("animationFrameService")
], RowNodeEventThrottle.prototype, "animationFrameService", 2);
__decorateClass([
  Autowired("rowModel")
], RowNodeEventThrottle.prototype, "rowModel", 2);
__decorateClass([
  PostConstruct
], RowNodeEventThrottle.prototype, "postConstruct", 1);
RowNodeEventThrottle = __decorateClass([
  Bean("rowNodeEventThrottle")
], RowNodeEventThrottle);

// community-modules/core/src/validation/rules/colDefValidations.ts
var COLUMN_DEFINITION_DEPRECATIONS = {
  columnsMenuParams: { version: "31.1", message: "Use `columnChooserParams` instead." },
  suppressMenu: { version: "31.1", message: "Use `suppressHeaderMenuButton` instead." },
  suppressCellFlash: { version: "31.2", message: "Use `enableCellChangeFlash={false}` in the ColDef" },
  dndSource: { version: "31.2", message: "This feature has been replaced by `Row Dragging to an External DropZone`." },
  dndSourceOnRowDrag: { version: "31.2", message: "This feature has been replaced by `Row Dragging to an External DropZone`." }
};
var CSRM_REQUIRES_ROW_GROUP_MODULE = (_options, gridOptions) => {
  var _a;
  if (((_a = gridOptions.rowModelType) != null ? _a : "clientSide") === "clientSide") {
    return { module: "@ag-grid-enterprise/row-grouping" /* RowGroupingModule */ };
  }
  return null;
};
var COLUMN_DEFINITION_VALIDATIONS = {
  // supported on all row models, but need module for client side.
  enableRowGroup: CSRM_REQUIRES_ROW_GROUP_MODULE,
  rowGroup: CSRM_REQUIRES_ROW_GROUP_MODULE,
  rowGroupIndex: CSRM_REQUIRES_ROW_GROUP_MODULE,
  enablePivot: CSRM_REQUIRES_ROW_GROUP_MODULE,
  enableValue: CSRM_REQUIRES_ROW_GROUP_MODULE,
  pivot: CSRM_REQUIRES_ROW_GROUP_MODULE,
  pivotIndex: CSRM_REQUIRES_ROW_GROUP_MODULE,
  aggFunc: CSRM_REQUIRES_ROW_GROUP_MODULE,
  cellEditor: (options) => {
    if (options.cellEditor === "agRichSelect" || options.cellEditor === "agRichSelectCellEditor") {
      return { module: "@ag-grid-enterprise/rich-select" /* RichSelectModule */ };
    }
    return null;
  },
  menuTabs: (options) => {
    var _a;
    const enterpriseMenuTabs = ["columnsMenuTab", "generalMenuTab"];
    if ((_a = options.menuTabs) == null ? void 0 : _a.some((tab) => enterpriseMenuTabs.includes(tab))) {
      return {
        module: "@ag-grid-enterprise/menu" /* MenuModule */
      };
    }
    return null;
  },
  columnsMenuParams: {
    module: ["@ag-grid-enterprise/menu" /* MenuModule */, "@ag-grid-enterprise/column-tool-panel" /* ColumnsToolPanelModule */]
  },
  columnChooserParams: {
    module: ["@ag-grid-enterprise/menu" /* MenuModule */, "@ag-grid-enterprise/column-tool-panel" /* ColumnsToolPanelModule */]
  },
  headerCheckboxSelection: {
    supportedRowModels: ["clientSide", "serverSide"],
    dependencies: (_options, { rowSelection }) => rowSelection === "multiple" ? null : "headerCheckboxSelection is only supported with rowSelection=multiple"
  },
  headerCheckboxSelectionFilteredOnly: {
    supportedRowModels: ["clientSide"],
    dependencies: (_options, { rowSelection }) => rowSelection === "multiple" ? null : "headerCheckboxSelectionFilteredOnly is only supported with rowSelection=multiple"
  },
  headerCheckboxSelectionCurrentPageOnly: {
    supportedRowModels: ["clientSide"],
    dependencies: (_options, { rowSelection }) => rowSelection === "multiple" ? null : "headerCheckboxSelectionCurrentPageOnly is only supported with rowSelection=multiple"
  },
  children: () => COL_DEF_VALIDATORS
};
var colDefPropertyMap = {
  headerName: void 0,
  columnGroupShow: void 0,
  headerClass: void 0,
  toolPanelClass: void 0,
  headerValueGetter: void 0,
  pivotKeys: void 0,
  groupId: void 0,
  colId: void 0,
  sort: void 0,
  initialSort: void 0,
  field: void 0,
  type: void 0,
  cellDataType: void 0,
  tooltipComponent: void 0,
  tooltipField: void 0,
  headerTooltip: void 0,
  cellClass: void 0,
  showRowGroup: void 0,
  filter: void 0,
  initialAggFunc: void 0,
  defaultAggFunc: void 0,
  aggFunc: void 0,
  pinned: void 0,
  initialPinned: void 0,
  chartDataType: void 0,
  cellAriaRole: void 0,
  cellEditorPopupPosition: void 0,
  headerGroupComponent: void 0,
  headerGroupComponentParams: void 0,
  cellStyle: void 0,
  cellRenderer: void 0,
  cellRendererParams: void 0,
  cellEditor: void 0,
  cellEditorParams: void 0,
  filterParams: void 0,
  pivotValueColumn: void 0,
  headerComponent: void 0,
  headerComponentParams: void 0,
  floatingFilterComponent: void 0,
  floatingFilterComponentParams: void 0,
  tooltipComponentParams: void 0,
  refData: void 0,
  columnsMenuParams: void 0,
  columnChooserParams: void 0,
  children: void 0,
  sortingOrder: void 0,
  allowedAggFuncs: void 0,
  menuTabs: void 0,
  pivotTotalColumnIds: void 0,
  cellClassRules: void 0,
  icons: void 0,
  sortIndex: void 0,
  initialSortIndex: void 0,
  flex: void 0,
  initialFlex: void 0,
  width: void 0,
  initialWidth: void 0,
  minWidth: void 0,
  maxWidth: void 0,
  rowGroupIndex: void 0,
  initialRowGroupIndex: void 0,
  pivotIndex: void 0,
  initialPivotIndex: void 0,
  suppressCellFlash: void 0,
  suppressColumnsToolPanel: void 0,
  suppressFiltersToolPanel: void 0,
  openByDefault: void 0,
  marryChildren: void 0,
  suppressStickyLabel: void 0,
  hide: void 0,
  initialHide: void 0,
  rowGroup: void 0,
  initialRowGroup: void 0,
  pivot: void 0,
  initialPivot: void 0,
  checkboxSelection: void 0,
  showDisabledCheckboxes: void 0,
  headerCheckboxSelection: void 0,
  headerCheckboxSelectionFilteredOnly: void 0,
  headerCheckboxSelectionCurrentPageOnly: void 0,
  suppressMenu: void 0,
  suppressHeaderMenuButton: void 0,
  suppressMovable: void 0,
  lockPosition: void 0,
  lockVisible: void 0,
  lockPinned: void 0,
  unSortIcon: void 0,
  suppressSizeToFit: void 0,
  suppressAutoSize: void 0,
  enableRowGroup: void 0,
  enablePivot: void 0,
  enableValue: void 0,
  editable: void 0,
  suppressPaste: void 0,
  suppressNavigable: void 0,
  enableCellChangeFlash: void 0,
  rowDrag: void 0,
  dndSource: void 0,
  autoHeight: void 0,
  wrapText: void 0,
  sortable: void 0,
  resizable: void 0,
  singleClickEdit: void 0,
  floatingFilter: void 0,
  cellEditorPopup: void 0,
  suppressFillHandle: void 0,
  wrapHeaderText: void 0,
  autoHeaderHeight: void 0,
  dndSourceOnRowDrag: void 0,
  valueGetter: void 0,
  valueSetter: void 0,
  filterValueGetter: void 0,
  keyCreator: void 0,
  valueFormatter: void 0,
  valueParser: void 0,
  comparator: void 0,
  equals: void 0,
  pivotComparator: void 0,
  suppressKeyboardEvent: void 0,
  suppressHeaderKeyboardEvent: void 0,
  colSpan: void 0,
  rowSpan: void 0,
  getQuickFilterText: void 0,
  onCellValueChanged: void 0,
  onCellClicked: void 0,
  onCellDoubleClicked: void 0,
  onCellContextMenu: void 0,
  rowDragText: void 0,
  tooltipValueGetter: void 0,
  cellRendererSelector: void 0,
  cellEditorSelector: void 0,
  suppressSpanHeaderHeight: void 0,
  useValueFormatterForExport: void 0,
  useValueParserForImport: void 0,
  mainMenuItems: void 0,
  contextMenuItems: void 0,
  suppressFloatingFilterButton: void 0,
  suppressHeaderFilterButton: void 0,
  suppressHeaderContextMenu: void 0,
  loadingCellRenderer: void 0,
  loadingCellRendererParams: void 0,
  loadingCellRendererSelector: void 0
};
var ALL_PROPERTIES = Object.keys(colDefPropertyMap);
var COL_DEF_VALIDATORS = {
  objectName: "colDef",
  allProperties: ALL_PROPERTIES,
  docsUrl: "column-properties/",
  deprecations: COLUMN_DEFINITION_DEPRECATIONS,
  validations: COLUMN_DEFINITION_VALIDATIONS
};

// community-modules/core/src/validation/rules/gridOptionsValidations.ts
var GRID_OPTION_DEPRECATIONS = {
  enableChartToolPanelsButton: { version: "29" },
  functionsPassive: { version: "29.2" },
  onColumnRowGroupChangeRequest: { version: "29.2" },
  onColumnPivotChangeRequest: { version: "29.2" },
  onColumnValueChangeRequest: { version: "29.2" },
  onColumnAggFuncChangeRequest: { version: "29.2" },
  serverSideFilterAllLevels: { version: "30", message: "All server-side group levels are now filtered by default. This can be toggled using `serverSideOnlyRefreshFilteredGroups`." },
  suppressAggAtRootLevel: { version: "30", message: "The root level aggregation is now suppressed by default. This can be toggled using  `alwaysAggregateAtRootLevel`." },
  excludeHiddenColumnsFromQuickFilter: { version: "30", message: "Hidden columns are now excluded from the Quick Filter by default. This can be toggled using `includeHiddenColumnsInQuickFilter`." },
  enterMovesDown: { version: "30", renamed: "enterNavigatesVertically" },
  enterMovesDownAfterEdit: { version: "30", renamed: "enterNavigatesVerticallyAfterEdit" },
  suppressParentsInRowNodes: { version: "30.2", message: "Using suppressParentsInRowNodes is no longer recommended. To serialize nodes it is now recommended to instead remove the parent node reference before serialization." },
  advancedFilterModel: { version: "31", message: "Use `initialState.filter.advancedFilterModel` instead." },
  suppressAsyncEvents: { version: "31", message: "Events should be handled asynchronously." },
  cellFadeDelay: { version: "31.1", renamed: "cellFadeDuration" },
  cellFlashDelay: { version: "31.1", renamed: "cellFlashDuration" },
  suppressServerSideInfiniteScroll: { version: "31.1" },
  serverSideSortOnServer: { version: "31.1" },
  serverSideFilterOnServer: { version: "31.1" },
  enableCellChangeFlash: { version: "31.2", message: "Use `enableCellChangeFlash` in the `ColDef` or `defaultColDef` for all columns." },
  groupIncludeFooter: { version: "31.3", message: "Use `groupTotalRow` instead." },
  groupIncludeTotalFooter: { version: "31.3", message: "Use `grandTotalRow` instead." }
};
var GRID_OPTION_DEFAULTS = {
  suppressContextMenu: false,
  preventDefaultOnContextMenu: false,
  allowContextMenuWithControlKey: false,
  suppressMenuHide: false,
  enableBrowserTooltips: false,
  tooltipTrigger: "hover",
  tooltipShowDelay: 2e3,
  tooltipHideDelay: 1e4,
  tooltipMouseTrack: false,
  tooltipShowMode: "standard",
  tooltipInteraction: false,
  copyHeadersToClipboard: false,
  copyGroupHeadersToClipboard: false,
  clipboardDelimiter: "	",
  suppressCopyRowsToClipboard: false,
  suppressCopySingleCellRanges: false,
  suppressLastEmptyLineOnPaste: false,
  suppressClipboardPaste: false,
  suppressClipboardApi: false,
  suppressCutToClipboard: false,
  maintainColumnOrder: false,
  suppressFieldDotNotation: false,
  allowDragFromColumnsToolPanel: false,
  suppressMovableColumns: false,
  suppressColumnMoveAnimation: false,
  suppressDragLeaveHidesColumns: false,
  suppressRowGroupHidesColumns: false,
  suppressAutoSize: false,
  autoSizePadding: 20,
  skipHeaderOnAutoSize: false,
  singleClickEdit: false,
  suppressClickEdit: false,
  readOnlyEdit: false,
  stopEditingWhenCellsLoseFocus: false,
  enterNavigatesVertically: false,
  enterNavigatesVerticallyAfterEdit: false,
  enableCellEditingOnBackspace: false,
  undoRedoCellEditing: false,
  undoRedoCellEditingLimit: 10,
  suppressCsvExport: false,
  suppressExcelExport: false,
  cacheQuickFilter: false,
  includeHiddenColumnsInQuickFilter: false,
  excludeChildrenWhenTreeDataFiltering: false,
  enableAdvancedFilter: false,
  includeHiddenColumnsInAdvancedFilter: false,
  enableCharts: false,
  suppressChartToolPanelsButton: false,
  masterDetail: false,
  keepDetailRows: false,
  keepDetailRowsCount: 10,
  detailRowAutoHeight: false,
  tabIndex: 0,
  rowBuffer: 10,
  valueCache: false,
  valueCacheNeverExpires: false,
  enableCellExpressions: false,
  suppressTouch: false,
  suppressFocusAfterRefresh: false,
  suppressAsyncEvents: false,
  suppressBrowserResizeObserver: false,
  suppressPropertyNamesCheck: false,
  suppressChangeDetection: false,
  debug: false,
  suppressLoadingOverlay: false,
  suppressNoRowsOverlay: false,
  pagination: false,
  paginationPageSize: 100,
  paginationPageSizeSelector: true,
  paginationAutoPageSize: false,
  paginateChildRows: false,
  suppressPaginationPanel: false,
  pivotMode: false,
  pivotPanelShow: "never",
  pivotDefaultExpanded: 0,
  pivotSuppressAutoColumn: false,
  suppressExpandablePivotGroups: false,
  functionsReadOnly: false,
  suppressAggFuncInHeader: false,
  alwaysAggregateAtRootLevel: false,
  aggregateOnlyChangedColumns: false,
  suppressAggFilteredOnly: false,
  removePivotHeaderRowWhenSingleValueColumn: false,
  animateRows: true,
  enableCellChangeFlash: false,
  cellFlashDelay: 500,
  cellFlashDuration: 500,
  cellFadeDelay: 1e3,
  cellFadeDuration: 1e3,
  allowShowChangeAfterFilter: false,
  domLayout: "normal",
  ensureDomOrder: false,
  enableRtl: false,
  suppressColumnVirtualisation: false,
  suppressMaxRenderedRowRestriction: false,
  suppressRowVirtualisation: false,
  rowDragManaged: false,
  suppressRowDrag: false,
  suppressMoveWhenRowDragging: false,
  rowDragEntireRow: false,
  rowDragMultiRow: false,
  embedFullWidthRows: false,
  groupDisplayType: "singleColumn",
  groupDefaultExpanded: 0,
  groupMaintainOrder: false,
  groupSelectsChildren: false,
  groupIncludeTotalFooter: false,
  groupSuppressBlankHeader: false,
  groupSelectsFiltered: false,
  showOpenedGroup: false,
  groupRemoveSingleChildren: false,
  groupRemoveLowestSingleChildren: false,
  groupHideOpenParents: false,
  groupAllowUnbalanced: false,
  rowGroupPanelShow: "never",
  suppressMakeColumnVisibleAfterUnGroup: false,
  treeData: false,
  rowGroupPanelSuppressSort: false,
  suppressGroupRowsSticky: false,
  rowModelType: "clientSide",
  asyncTransactionWaitMillis: 50,
  suppressModelUpdateAfterUpdateTransaction: false,
  cacheOverflowSize: 1,
  infiniteInitialRowCount: 1,
  serverSideInitialRowCount: 1,
  suppressServerSideInfiniteScroll: false,
  cacheBlockSize: 100,
  maxBlocksInCache: -1,
  maxConcurrentDatasourceRequests: 2,
  blockLoadDebounceMillis: 0,
  purgeClosedRowNodes: false,
  serverSideSortAllLevels: false,
  serverSideOnlyRefreshFilteredGroups: false,
  serverSideSortOnServer: false,
  serverSideFilterOnServer: false,
  serverSidePivotResultFieldSeparator: "_",
  viewportRowModelPageSize: 5,
  viewportRowModelBufferSize: 5,
  alwaysShowHorizontalScroll: false,
  alwaysShowVerticalScroll: false,
  debounceVerticalScrollbar: false,
  suppressHorizontalScroll: false,
  suppressScrollOnNewData: false,
  suppressScrollWhenPopupsAreOpen: false,
  suppressAnimationFrame: false,
  suppressMiddleClickScrolls: false,
  suppressPreventDefaultOnMouseWheel: false,
  rowMultiSelectWithClick: false,
  suppressRowDeselection: false,
  suppressRowClickSelection: false,
  suppressCellFocus: false,
  suppressHeaderFocus: false,
  suppressMultiRangeSelection: false,
  enableCellTextSelection: false,
  enableRangeSelection: false,
  enableRangeHandle: false,
  enableFillHandle: false,
  fillHandleDirection: "xy",
  suppressClearOnFillReduction: false,
  accentedSort: false,
  unSortIcon: false,
  suppressMultiSort: false,
  alwaysMultiSort: false,
  suppressMaintainUnsortedOrder: false,
  suppressRowHoverHighlight: false,
  suppressRowTransform: false,
  columnHoverHighlight: false,
  deltaSort: false,
  enableGroupEdit: false,
  suppressGroupMaintainValueType: false,
  functionsPassive: false,
  groupLockGroupColumns: 0,
  serverSideEnableClientSideSort: false,
  suppressServerSideFullWidthLoadingRow: false,
  pivotMaxGeneratedColumns: -1
};
var GRID_OPTION_VALIDATIONS = {
  sideBar: { module: "@ag-grid-enterprise/side-bar" /* SideBarModule */ },
  statusBar: { module: "@ag-grid-enterprise/status-bar" /* StatusBarModule */ },
  enableCharts: { module: "@ag-grid-enterprise/charts" /* GridChartsModule */ },
  getMainMenuItems: { module: "@ag-grid-enterprise/menu" /* MenuModule */ },
  getContextMenuItems: { module: "@ag-grid-enterprise/menu" /* MenuModule */ },
  allowContextMenuWithControlKey: { module: "@ag-grid-enterprise/menu" /* MenuModule */ },
  enableAdvancedFilter: { module: "@ag-grid-enterprise/advanced-filter" /* AdvancedFilterModule */ },
  treeData: {
    supportedRowModels: ["clientSide", "serverSide"],
    module: "@ag-grid-enterprise/row-grouping" /* RowGroupingModule */,
    dependencies: (options) => {
      var _a;
      const rowModel = (_a = options.rowModelType) != null ? _a : "clientSide";
      switch (rowModel) {
        case "clientSide":
          const csrmWarning = `treeData requires 'getDataPath' in the ${rowModel} row model.`;
          return options.getDataPath ? null : csrmWarning;
        case "serverSide":
          const ssrmWarning = `treeData requires 'isServerSideGroup' and 'getServerSideGroupKey' in the ${rowModel} row model.`;
          return options.isServerSideGroup && options.getServerSideGroupKey ? null : ssrmWarning;
      }
      return null;
    }
  },
  masterDetail: { module: "@ag-grid-enterprise/master-detail" /* MasterDetailModule */ },
  enableRangeSelection: { module: "@ag-grid-enterprise/range-selection" /* RangeSelectionModule */ },
  enableRangeHandle: {
    dependencies: {
      enableRangeSelection: [true]
    }
  },
  enableFillHandle: {
    dependencies: {
      enableRangeSelection: [true]
    }
  },
  groupDefaultExpanded: {
    supportedRowModels: ["clientSide"]
  },
  groupIncludeFooter: {
    supportedRowModels: ["clientSide", "serverSide"],
    dependencies: (options) => {
      var _a;
      const rowModel = (_a = options.rowModelType) != null ? _a : "clientSide";
      switch (rowModel) {
        case "clientSide":
          return null;
        case "serverSide":
          const warning = "groupIncludeFooter is not supported alongside suppressServerSideInfiniteScroll";
          return options.suppressServerSideInfiniteScroll ? warning : null;
      }
      return null;
    }
  },
  groupIncludeTotalFooter: {
    supportedRowModels: ["clientSide"]
  },
  groupRemoveSingleChildren: {
    dependencies: {
      groupHideOpenParents: [void 0, false],
      groupRemoveLowestSingleChildren: [void 0, false]
    }
  },
  groupRemoveLowestSingleChildren: {
    dependencies: {
      groupHideOpenParents: [void 0, false],
      groupRemoveSingleChildren: [void 0, false]
    }
  },
  groupSelectsChildren: {
    dependencies: {
      rowSelection: ["multiple"]
    }
  },
  suppressParentsInRowNodes: {
    dependencies: {
      groupSelectsChildren: [void 0, false]
    }
  },
  viewportDatasource: {
    supportedRowModels: ["viewport"],
    module: "@ag-grid-enterprise/viewport-row-model" /* ViewportRowModelModule */
  },
  serverSideDatasource: {
    supportedRowModels: ["serverSide"],
    module: "@ag-grid-enterprise/server-side-row-model" /* ServerSideRowModelModule */
  },
  cacheBlockSize: {
    supportedRowModels: ["serverSide", "infinite"]
  },
  datasource: {
    supportedRowModels: ["infinite"],
    module: "@ag-grid-community/infinite-row-model" /* InfiniteRowModelModule */
  },
  rowData: {
    supportedRowModels: ["clientSide"],
    module: "@ag-grid-community/client-side-row-model" /* ClientSideRowModelModule */
  },
  columnDefs: () => COL_DEF_VALIDATORS,
  defaultColDef: () => COL_DEF_VALIDATORS,
  defaultColGroupDef: () => COL_DEF_VALIDATORS,
  autoGroupColumnDef: () => COL_DEF_VALIDATORS
};
var GRID_OPTIONS_VALIDATORS = {
  objectName: "gridOptions",
  allProperties: [
    ...PropertyKeys.ALL_PROPERTIES,
    ...ComponentUtil.EVENT_CALLBACKS
  ],
  propertyExceptions: ["api", "columnApi"],
  docsUrl: "grid-options/",
  deprecations: GRID_OPTION_DEPRECATIONS,
  validations: GRID_OPTION_VALIDATIONS
};

// community-modules/core/src/gridOptionsService.ts
var GridOptionsService = class {
  constructor() {
    this.destroyed = false;
    this.domDataKey = "__AG_" + Math.random().toString();
    this.propertyEventService = new EventService();
    // responsible for calling the onXXX functions on gridOptions
    // It forces events defined in GridOptionsService.alwaysSyncGlobalEvents to be fired synchronously.
    // This is required for events such as GridPreDestroyed.
    // Other events can be fired asynchronously or synchronously depending on config.
    this.globalEventHandlerFactory = (restrictToSyncOnly) => {
      return (eventName, event) => {
        if (this.destroyed) {
          return;
        }
        const alwaysSync = ALWAYS_SYNC_GLOBAL_EVENTS.has(eventName);
        if (alwaysSync && !restrictToSyncOnly || !alwaysSync && restrictToSyncOnly) {
          return;
        }
        const eventHandlerName = ComponentUtil.getCallbackForEvent(eventName);
        const eventHandler = this.gridOptions[eventHandlerName];
        if (typeof eventHandler === "function") {
          this.frameworkOverrides.wrapOutgoing(() => {
            eventHandler(event);
          });
        }
      };
    };
  }
  // This is quicker then having code call gridOptionsService.get('context')
  get context() {
    return this.gridOptions["context"];
  }
  init() {
    this.columnApi = new ColumnApi(this.api);
    const async = !this.get("suppressAsyncEvents");
    this.eventService.addGlobalListener(this.globalEventHandlerFactory().bind(this), async);
    this.eventService.addGlobalListener(this.globalEventHandlerFactory(true).bind(this), false);
    this.propertyEventService.setFrameworkOverrides(this.frameworkOverrides);
    this.getScrollbarWidth();
  }
  destroy() {
    this.destroyed = true;
    this.columnApi = void 0;
  }
  /**
   * Get the raw value of the GridOptions property provided.
   * @param property
   */
  get(property) {
    var _a;
    return (_a = this.gridOptions[property]) != null ? _a : GRID_OPTION_DEFAULTS[property];
  }
  /**
   * Get the GridOption callback but wrapped so that the common params of api,columnApi and context are automatically applied to the params.
   * @param property GridOption callback properties based on the fact that this property has a callback with params extending AgGridCommon
   */
  getCallback(property) {
    return this.mergeGridCommonParams(this.gridOptions[property]);
  }
  /**
   * Returns `true` if a value has been specified for this GridOption.
   * @param property GridOption property
   */
  exists(property) {
    return exists(this.gridOptions[property]);
  }
  /**
  * Wrap the user callback and attach the api, columnApi and context to the params object on the way through.
  * @param callback User provided callback
  * @returns Wrapped callback where the params object not require api, columnApi and context
  */
  mergeGridCommonParams(callback) {
    if (callback) {
      const wrapped = (callbackParams) => {
        const mergedParams = callbackParams;
        mergedParams.api = this.api;
        mergedParams.columnApi = this.columnApi;
        mergedParams.context = this.context;
        return callback(mergedParams);
      };
      return wrapped;
    }
    return callback;
  }
  static toBoolean(value) {
    if (typeof value === "boolean") {
      return value;
    }
    if (typeof value === "string") {
      return value.toUpperCase() === "TRUE" || value == "";
    }
    return false;
  }
  static toNumber(value) {
    if (typeof value === "number") {
      return value;
    }
    if (typeof value === "string") {
      const parsed = parseInt(value);
      if (isNaN(parsed)) {
        return void 0;
      }
      return parsed;
    }
    return void 0;
  }
  static toConstrainedNum(min, max) {
    return (value) => {
      const num = GridOptionsService.toNumber(value);
      if (num == null || num < min || num > max) {
        return void 0;
      }
      return num;
    };
  }
  static getCoercedValue(key, value) {
    const coerceFunc = GridOptionsService.PROPERTY_COERCIONS.get(key);
    if (!coerceFunc) {
      return value;
    }
    return coerceFunc(value);
  }
  static getCoercedGridOptions(gridOptions) {
    const newGo = {};
    Object.entries(gridOptions).forEach(([key, value]) => {
      const coercedValue = GridOptionsService.getCoercedValue(key, value);
      newGo[key] = coercedValue;
    });
    return newGo;
  }
  updateGridOptions({ options, force, source = "api" }) {
    const changeSet = { id: GridOptionsService.changeSetId++, properties: [] };
    const events = [];
    Object.entries(options).forEach(([key, value]) => {
      if (source === "api" && INITIAL_GRID_OPTION_KEYS[key]) {
        warnOnce(`${key} is an initial property and cannot be updated.`);
      }
      const coercedValue = GridOptionsService.getCoercedValue(key, value);
      const shouldForce = force || typeof coercedValue === "object" && source === "api";
      const previousValue = this.gridOptions[key];
      if (shouldForce || previousValue !== coercedValue) {
        this.gridOptions[key] = coercedValue;
        const event = {
          type: key,
          currentValue: coercedValue,
          previousValue,
          changeSet,
          source
        };
        events.push(event);
      }
    });
    this.validationService.processGridOptions(this.gridOptions);
    changeSet.properties = events.map((event) => event.type);
    events.forEach((event) => {
      if (this.gridOptions.debug) {
        console.log(`AG Grid: Updated property ${event.type} from `, event.previousValue, " to  ", event.currentValue);
      }
      this.propertyEventService.dispatchEvent(event);
    });
  }
  addEventListener(key, listener) {
    this.propertyEventService.addEventListener(key, listener);
  }
  removeEventListener(key, listener) {
    this.propertyEventService.removeEventListener(key, listener);
  }
  // *************** Helper methods ************************** //
  // Methods to share common GridOptions related logic that goes above accessing a single property
  // the user might be using some non-standard scrollbar, eg a scrollbar that has zero
  // width and overlays (like the Safari scrollbar, but presented in Chrome). so we
  // allow the user to provide the scroll width before we work it out.
  getScrollbarWidth() {
    if (this.scrollbarWidth == null) {
      const useGridOptions = typeof this.gridOptions.scrollbarWidth === "number" && this.gridOptions.scrollbarWidth >= 0;
      const scrollbarWidth = useGridOptions ? this.gridOptions.scrollbarWidth : getScrollbarWidth();
      if (scrollbarWidth != null) {
        this.scrollbarWidth = scrollbarWidth;
        this.eventService.dispatchEvent({
          type: Events.EVENT_SCROLLBAR_WIDTH_CHANGED
        });
      }
    }
    return this.scrollbarWidth;
  }
  isRowModelType(rowModelType) {
    return this.gridOptions.rowModelType === rowModelType || rowModelType === "clientSide" && missing(this.gridOptions.rowModelType);
  }
  isDomLayout(domLayout) {
    var _a;
    const gridLayout = (_a = this.gridOptions.domLayout) != null ? _a : "normal";
    return gridLayout === domLayout;
  }
  isRowSelection() {
    return this.gridOptions.rowSelection === "single" || this.gridOptions.rowSelection === "multiple";
  }
  useAsyncEvents() {
    return !this.get("suppressAsyncEvents");
  }
  isGetRowHeightFunction() {
    return typeof this.gridOptions.getRowHeight === "function";
  }
  getRowHeightForNode(rowNode, allowEstimate = false, defaultRowHeight) {
    if (defaultRowHeight == null) {
      defaultRowHeight = this.environment.getDefaultRowHeight();
    }
    if (this.isGetRowHeightFunction()) {
      if (allowEstimate) {
        return { height: defaultRowHeight, estimated: true };
      }
      const params = {
        node: rowNode,
        data: rowNode.data
      };
      const height = this.getCallback("getRowHeight")(params);
      if (this.isNumeric(height)) {
        if (height === 0) {
          warnOnce("The return of `getRowHeight` cannot be zero. If the intention is to hide rows, use a filter instead.");
        }
        return { height: Math.max(1, height), estimated: false };
      }
    }
    if (rowNode.detail && this.get("masterDetail")) {
      return this.getMasterDetailRowHeight();
    }
    const rowHeight = this.gridOptions.rowHeight && this.isNumeric(this.gridOptions.rowHeight) ? this.gridOptions.rowHeight : defaultRowHeight;
    return { height: rowHeight, estimated: false };
  }
  getMasterDetailRowHeight() {
    if (this.get("detailRowAutoHeight")) {
      return { height: 1, estimated: false };
    }
    if (this.isNumeric(this.gridOptions.detailRowHeight)) {
      return { height: this.gridOptions.detailRowHeight, estimated: false };
    }
    return { height: 300, estimated: false };
  }
  // we don't allow dynamic row height for virtual paging
  getRowHeightAsNumber() {
    if (!this.gridOptions.rowHeight || missing(this.gridOptions.rowHeight)) {
      return this.environment.getDefaultRowHeight();
    }
    const rowHeight = this.environment.refreshRowHeightVariable();
    if (rowHeight !== -1) {
      return rowHeight;
    }
    console.warn("AG Grid row height must be a number if not using standard row model");
    return this.environment.getDefaultRowHeight();
  }
  isNumeric(value) {
    return !isNaN(value) && typeof value === "number" && isFinite(value);
  }
  getDomDataKey() {
    return this.domDataKey;
  }
  // returns the dom data, or undefined if not found
  getDomData(element, key) {
    const domData = element[this.getDomDataKey()];
    return domData ? domData[key] : void 0;
  }
  setDomData(element, key, value) {
    const domDataKey = this.getDomDataKey();
    let domData = element[domDataKey];
    if (missing(domData)) {
      domData = {};
      element[domDataKey] = domData;
    }
    domData[key] = value;
  }
  getDocument() {
    let result = null;
    if (this.gridOptions.getDocument && exists(this.gridOptions.getDocument)) {
      result = this.gridOptions.getDocument();
    } else if (this.eGridDiv) {
      result = this.eGridDiv.ownerDocument;
    }
    if (result && exists(result)) {
      return result;
    }
    return document;
  }
  getWindow() {
    const eDocument = this.getDocument();
    return eDocument.defaultView || window;
  }
  getRootNode() {
    return this.eGridDiv.getRootNode();
  }
  getActiveDomElement() {
    return this.getRootNode().activeElement;
  }
  getAsyncTransactionWaitMillis() {
    return exists(this.gridOptions.asyncTransactionWaitMillis) ? this.gridOptions.asyncTransactionWaitMillis : 50;
  }
  isAnimateRows() {
    if (this.get("ensureDomOrder")) {
      return false;
    }
    return this.get("animateRows");
  }
  isGroupRowsSticky() {
    if (this.get("paginateChildRows") || this.get("groupHideOpenParents") || this.isDomLayout("print")) {
      return false;
    }
    return true;
  }
  isColumnsSortingCoupledToGroup() {
    const autoGroupColumnDef = this.gridOptions.autoGroupColumnDef;
    return !(autoGroupColumnDef == null ? void 0 : autoGroupColumnDef.comparator) && !this.get("treeData");
  }
  getGroupAggFiltering() {
    const userValue = this.gridOptions.groupAggFiltering;
    if (typeof userValue === "function") {
      return this.getCallback("groupAggFiltering");
    }
    if (userValue === true) {
      return () => true;
    }
    return void 0;
  }
  getGrandTotalRow() {
    const userValue = this.gridOptions.grandTotalRow;
    if (userValue) {
      return userValue;
    }
    const legacyValue = this.gridOptions.groupIncludeTotalFooter;
    if (legacyValue) {
      return "bottom";
    }
    return void 0;
  }
  getGroupTotalRowCallback() {
    const userValue = this.get("groupTotalRow");
    if (typeof userValue === "function") {
      return this.getCallback("groupTotalRow");
    }
    if (userValue) {
      return () => userValue;
    }
    const legacyValue = this.get("groupIncludeFooter");
    if (typeof legacyValue === "function") {
      const legacyCallback = this.getCallback("groupIncludeFooter");
      return (p) => {
        return legacyCallback(p) ? "bottom" : void 0;
      };
    }
    return () => legacyValue ? "bottom" : void 0;
  }
  isGroupMultiAutoColumn() {
    if (this.gridOptions.groupDisplayType) {
      return this.gridOptions.groupDisplayType === "multipleColumns";
    }
    return this.get("groupHideOpenParents");
  }
  isGroupUseEntireRow(pivotMode) {
    if (pivotMode) {
      return false;
    }
    return this.gridOptions.groupDisplayType === "groupRows";
  }
  getGridCommonParams() {
    return {
      api: this.api,
      columnApi: this.columnApi,
      context: this.context
    };
  }
  addGridCommonParams(params) {
    const updatedParams = params;
    updatedParams.api = this.api;
    updatedParams.columnApi = this.columnApi;
    updatedParams.context = this.context;
    return updatedParams;
  }
};
/**
 * Handles value coercion including validation of ranges etc. If value is invalid, undefined is set, allowing default to be used.
 */
GridOptionsService.PROPERTY_COERCIONS = new Map([
  ...PropertyKeys.BOOLEAN_PROPERTIES.map((key) => [key, GridOptionsService.toBoolean]),
  ...PropertyKeys.NUMBER_PROPERTIES.map((key) => [key, GridOptionsService.toNumber]),
  ["groupAggFiltering", (val) => typeof val === "function" ? val : GridOptionsService.toBoolean(val)],
  ["pageSize", GridOptionsService.toConstrainedNum(1, Number.MAX_VALUE)],
  ["autoSizePadding", GridOptionsService.toConstrainedNum(0, Number.MAX_VALUE)],
  ["keepDetailRowsCount", GridOptionsService.toConstrainedNum(1, Number.MAX_VALUE)],
  ["rowBuffer", GridOptionsService.toConstrainedNum(0, Number.MAX_VALUE)],
  ["infiniteInitialRowCount", GridOptionsService.toConstrainedNum(1, Number.MAX_VALUE)],
  ["cacheOverflowSize", GridOptionsService.toConstrainedNum(1, Number.MAX_VALUE)],
  ["cacheBlockSize", GridOptionsService.toConstrainedNum(1, Number.MAX_VALUE)],
  ["serverSideInitialRowCount", GridOptionsService.toConstrainedNum(1, Number.MAX_VALUE)],
  ["viewportRowModelPageSize", GridOptionsService.toConstrainedNum(1, Number.MAX_VALUE)],
  ["viewportRowModelBufferSize", GridOptionsService.toConstrainedNum(0, Number.MAX_VALUE)]
]);
GridOptionsService.changeSetId = 0;
__decorateClass([
  Autowired("gridOptions")
], GridOptionsService.prototype, "gridOptions", 2);
__decorateClass([
  Autowired("eventService")
], GridOptionsService.prototype, "eventService", 2);
__decorateClass([
  Autowired("environment")
], GridOptionsService.prototype, "environment", 2);
__decorateClass([
  Autowired("frameworkOverrides")
], GridOptionsService.prototype, "frameworkOverrides", 2);
__decorateClass([
  Autowired("eGridDiv")
], GridOptionsService.prototype, "eGridDiv", 2);
__decorateClass([
  Autowired("validationService")
], GridOptionsService.prototype, "validationService", 2);
__decorateClass([
  Autowired("gridApi")
], GridOptionsService.prototype, "api", 2);
__decorateClass([
  PostConstruct
], GridOptionsService.prototype, "init", 1);
__decorateClass([
  PreDestroy
], GridOptionsService.prototype, "destroy", 1);
GridOptionsService = __decorateClass([
  Bean("gridOptionsService")
], GridOptionsService);

// community-modules/core/src/localeService.ts
var LocaleService = class extends BeanStub {
  getLocaleTextFunc() {
    const getLocaleText = this.gos.getCallback("getLocaleText");
    if (getLocaleText) {
      return (key, defaultValue, variableValues) => {
        const params = {
          key,
          defaultValue,
          variableValues
        };
        return getLocaleText(params);
      };
    }
    const localeText = this.gos.get("localeText");
    return (key, defaultValue, variableValues) => {
      let localisedText = localeText && localeText[key];
      if (localisedText && variableValues && variableValues.length) {
        let found = 0;
        while (true) {
          if (found >= variableValues.length) {
            break;
          }
          const idx = localisedText.indexOf("${variable}");
          if (idx === -1) {
            break;
          }
          localisedText = localisedText.replace("${variable}", variableValues[found++]);
        }
      }
      return localisedText != null ? localisedText : defaultValue;
    };
  }
};
LocaleService = __decorateClass([
  Bean("localeService")
], LocaleService);

// community-modules/core/src/gridBodyComp/fakeVScrollComp.ts
var _FakeVScrollComp = class _FakeVScrollComp extends AbstractFakeScrollComp {
  constructor() {
    super(_FakeVScrollComp.TEMPLATE, "vertical");
  }
  postConstruct() {
    super.postConstruct();
    this.createManagedBean(new SetHeightFeature(this.eContainer));
    this.ctrlsService.register("fakeVScrollComp", this);
    this.addManagedListener(this.eventService, Events.EVENT_ROW_CONTAINER_HEIGHT_CHANGED, this.onRowContainerHeightChanged.bind(this));
  }
  setScrollVisible() {
    const vScrollShowing = this.scrollVisibleService.isVerticalScrollShowing();
    const invisibleScrollbar2 = this.invisibleScrollbar;
    const scrollbarWidth = vScrollShowing ? this.gos.getScrollbarWidth() || 0 : 0;
    const adjustedScrollbarWidth = scrollbarWidth === 0 && invisibleScrollbar2 ? 16 : scrollbarWidth;
    this.addOrRemoveCssClass("ag-scrollbar-invisible", invisibleScrollbar2);
    setFixedWidth(this.getGui(), adjustedScrollbarWidth);
    setFixedWidth(this.eViewport, adjustedScrollbarWidth);
    setFixedWidth(this.eContainer, adjustedScrollbarWidth);
    this.setDisplayed(vScrollShowing, { skipAriaHidden: true });
  }
  onRowContainerHeightChanged() {
    const { ctrlsService } = this;
    const gridBodyCtrl = ctrlsService.getGridBodyCtrl();
    const gridBodyViewportEl = gridBodyCtrl.getBodyViewportElement();
    const eViewportScrollTop = this.getScrollPosition();
    const gridBodyViewportScrollTop = gridBodyViewportEl.scrollTop;
    if (eViewportScrollTop != gridBodyViewportScrollTop) {
      this.setScrollPosition(gridBodyViewportScrollTop, true);
    }
  }
  getScrollPosition() {
    return this.getViewport().scrollTop;
  }
  setScrollPosition(value, force) {
    if (!force && !isVisible(this.getViewport())) {
      this.attemptSettingScrollPosition(value);
    }
    this.getViewport().scrollTop = value;
  }
};
_FakeVScrollComp.TEMPLATE = /* html */
`<div class="ag-body-vertical-scroll" aria-hidden="true">
            <div class="ag-body-vertical-scroll-viewport" ref="eViewport">
                <div class="ag-body-vertical-scroll-container" ref="eContainer"></div>
            </div>
        </div>`;
__decorateClass([
  PostConstruct
], _FakeVScrollComp.prototype, "postConstruct", 1);
var FakeVScrollComp = _FakeVScrollComp;

// community-modules/core/src/columns/dataTypeService.ts
var MONTH_LOCALE_TEXT = {
  january: "January",
  february: "February",
  march: "March",
  april: "April",
  may: "May",
  june: "June",
  july: "July",
  august: "August",
  september: "September",
  october: "October",
  november: "November",
  december: "December"
};
var MONTH_KEYS = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var DataTypeService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.dataTypeDefinitions = {};
    this.isWaitingForRowData = false;
    this.isColumnTypeOverrideInDataTypeDefinitions = false;
    // keep track of any column state updates whilst waiting for data types to be inferred
    this.columnStateUpdatesPendingInference = {};
    this.columnStateUpdateListenerDestroyFuncs = [];
  }
  init() {
    this.groupHideOpenParents = this.gos.get("groupHideOpenParents");
    this.addManagedPropertyListener("groupHideOpenParents", () => {
      this.groupHideOpenParents = this.gos.get("groupHideOpenParents");
    });
    this.processDataTypeDefinitions();
    this.addManagedPropertyListener("dataTypeDefinitions", (event) => {
      this.processDataTypeDefinitions();
      this.columnModel.recreateColumnDefs(convertSourceType(event.source));
    });
  }
  processDataTypeDefinitions() {
    var _a;
    const defaultDataTypes = this.getDefaultDataTypes();
    this.dataTypeDefinitions = {};
    Object.entries(defaultDataTypes).forEach(([cellDataType, dataTypeDefinition]) => {
      this.dataTypeDefinitions[cellDataType] = __spreadProps(__spreadValues({}, dataTypeDefinition), {
        groupSafeValueFormatter: this.createGroupSafeValueFormatter(dataTypeDefinition)
      });
    });
    const dataTypeDefinitions = (_a = this.gos.get("dataTypeDefinitions")) != null ? _a : {};
    this.dataTypeMatchers = {};
    Object.entries(dataTypeDefinitions).forEach(([cellDataType, dataTypeDefinition]) => {
      const mergedDataTypeDefinition = this.processDataTypeDefinition(dataTypeDefinition, dataTypeDefinitions, [cellDataType], defaultDataTypes);
      if (mergedDataTypeDefinition) {
        this.dataTypeDefinitions[cellDataType] = mergedDataTypeDefinition;
        if (dataTypeDefinition.dataTypeMatcher) {
          this.dataTypeMatchers[cellDataType] = dataTypeDefinition.dataTypeMatcher;
        }
      }
    });
    this.checkObjectValueHandlers(defaultDataTypes);
    ["dateString", "text", "number", "boolean", "date"].forEach((cellDataType) => {
      const overriddenDataTypeMatcher = this.dataTypeMatchers[cellDataType];
      if (overriddenDataTypeMatcher) {
        delete this.dataTypeMatchers[cellDataType];
      }
      this.dataTypeMatchers[cellDataType] = overriddenDataTypeMatcher != null ? overriddenDataTypeMatcher : defaultDataTypes[cellDataType].dataTypeMatcher;
    });
  }
  mergeDataTypeDefinitions(parentDataTypeDefinition, childDataTypeDefinition) {
    const mergedDataTypeDefinition = __spreadValues(__spreadValues({}, parentDataTypeDefinition), childDataTypeDefinition);
    if (parentDataTypeDefinition.columnTypes && childDataTypeDefinition.columnTypes && childDataTypeDefinition.appendColumnTypes) {
      mergedDataTypeDefinition.columnTypes = [
        ...this.convertColumnTypes(parentDataTypeDefinition.columnTypes),
        ...this.convertColumnTypes(childDataTypeDefinition.columnTypes)
      ];
    }
    return mergedDataTypeDefinition;
  }
  processDataTypeDefinition(dataTypeDefinition, dataTypeDefinitions, alreadyProcessedDataTypes, defaultDataTypes) {
    let mergedDataTypeDefinition;
    const extendsCellDataType = dataTypeDefinition.extendsDataType;
    if (dataTypeDefinition.columnTypes) {
      this.isColumnTypeOverrideInDataTypeDefinitions = true;
    }
    if (dataTypeDefinition.extendsDataType === dataTypeDefinition.baseDataType) {
      let baseDataTypeDefinition = defaultDataTypes[extendsCellDataType];
      const overriddenBaseDataTypeDefinition = dataTypeDefinitions[extendsCellDataType];
      if (baseDataTypeDefinition && overriddenBaseDataTypeDefinition) {
        baseDataTypeDefinition = overriddenBaseDataTypeDefinition;
      }
      if (!this.validateDataTypeDefinition(dataTypeDefinition, baseDataTypeDefinition, extendsCellDataType)) {
        return void 0;
      }
      mergedDataTypeDefinition = this.mergeDataTypeDefinitions(
        baseDataTypeDefinition,
        dataTypeDefinition
      );
    } else {
      if (alreadyProcessedDataTypes.includes(extendsCellDataType)) {
        warnOnce('Data type definition hierarchies (via the "extendsDataType" property) cannot contain circular references.');
        return void 0;
      }
      const extendedDataTypeDefinition = dataTypeDefinitions[extendsCellDataType];
      if (!this.validateDataTypeDefinition(dataTypeDefinition, extendedDataTypeDefinition, extendsCellDataType)) {
        return void 0;
      }
      const mergedExtendedDataTypeDefinition = this.processDataTypeDefinition(
        extendedDataTypeDefinition,
        dataTypeDefinitions,
        [...alreadyProcessedDataTypes, extendsCellDataType],
        defaultDataTypes
      );
      if (!mergedExtendedDataTypeDefinition) {
        return void 0;
      }
      mergedDataTypeDefinition = this.mergeDataTypeDefinitions(
        mergedExtendedDataTypeDefinition,
        dataTypeDefinition
      );
    }
    return __spreadProps(__spreadValues({}, mergedDataTypeDefinition), {
      groupSafeValueFormatter: this.createGroupSafeValueFormatter(mergedDataTypeDefinition)
    });
  }
  validateDataTypeDefinition(dataTypeDefinition, parentDataTypeDefinition, parentCellDataType) {
    if (!parentDataTypeDefinition) {
      warnOnce(`The data type definition ${parentCellDataType} does not exist.`);
      return false;
    }
    if (parentDataTypeDefinition.baseDataType !== dataTypeDefinition.baseDataType) {
      warnOnce('The "baseDataType" property of a data type definition must match that of its parent.');
      return false;
    }
    return true;
  }
  createGroupSafeValueFormatter(dataTypeDefinition) {
    if (!dataTypeDefinition.valueFormatter) {
      return void 0;
    }
    return (params) => {
      var _a, _b;
      if ((_a = params.node) == null ? void 0 : _a.group) {
        const aggFunc = params.column.getAggFunc();
        if (aggFunc) {
          if (aggFunc === "first" || aggFunc === "last") {
            return dataTypeDefinition.valueFormatter(params);
          }
          if (dataTypeDefinition.baseDataType === "number" && aggFunc !== "count") {
            if (typeof params.value === "number") {
              return dataTypeDefinition.valueFormatter(params);
            }
            if (typeof params.value === "object") {
              if (!params.value) {
                return void 0;
              }
              if ("toNumber" in params.value) {
                return dataTypeDefinition.valueFormatter(__spreadProps(__spreadValues({}, params), {
                  value: params.value.toNumber()
                }));
              }
              if ("value" in params.value) {
                return dataTypeDefinition.valueFormatter(__spreadProps(__spreadValues({}, params), {
                  value: params.value.value
                }));
              }
            }
          }
        }
        if (!this.gos.get("suppressGroupMaintainValueType")) {
          return void 0;
        }
      } else if (this.groupHideOpenParents && params.column.isRowGroupActive()) {
        if (typeof params.value !== "string" || ((_b = dataTypeDefinition.dataTypeMatcher) == null ? void 0 : _b.call(dataTypeDefinition, params.value))) {
          return dataTypeDefinition.valueFormatter(params);
        }
        if (!this.gos.get("suppressGroupMaintainValueType")) {
          return void 0;
        }
      }
      return dataTypeDefinition.valueFormatter(params);
    };
  }
  updateColDefAndGetDataTypeDefinitionColumnType(colDef, userColDef, colId) {
    let { cellDataType } = userColDef;
    const { field } = userColDef;
    if (cellDataType === void 0) {
      cellDataType = colDef.cellDataType;
    }
    if (cellDataType == null || cellDataType === true) {
      cellDataType = this.canInferCellDataType(colDef, userColDef) ? this.inferCellDataType(field, colId) : false;
    }
    if (!cellDataType) {
      colDef.cellDataType = false;
      return void 0;
    }
    const dataTypeDefinition = this.dataTypeDefinitions[cellDataType];
    if (!dataTypeDefinition) {
      warnOnce(`Missing data type definition - "${cellDataType}"`);
      return void 0;
    }
    colDef.cellDataType = cellDataType;
    if (dataTypeDefinition.groupSafeValueFormatter) {
      colDef.valueFormatter = dataTypeDefinition.groupSafeValueFormatter;
    }
    if (dataTypeDefinition.valueParser) {
      colDef.valueParser = dataTypeDefinition.valueParser;
    }
    if (!dataTypeDefinition.suppressDefaultProperties) {
      this.setColDefPropertiesForBaseDataType(colDef, dataTypeDefinition, colId);
    }
    return dataTypeDefinition.columnTypes;
  }
  updateColDefAndGetColumnType(colDef, userColDef, colId) {
    var _a, _b;
    const dataTypeDefinitionColumnType = this.updateColDefAndGetDataTypeDefinitionColumnType(colDef, userColDef, colId);
    const columnTypes = (_b = (_a = userColDef.type) != null ? _a : dataTypeDefinitionColumnType) != null ? _b : colDef.type;
    colDef.type = columnTypes;
    return columnTypes ? this.convertColumnTypes(columnTypes) : void 0;
  }
  addColumnListeners(column) {
    if (!this.isWaitingForRowData) {
      return;
    }
    const columnStateUpdates = this.columnStateUpdatesPendingInference[column.getColId()];
    if (!columnStateUpdates) {
      return;
    }
    const columnListener = (event) => {
      columnStateUpdates.add(event.key);
    };
    column.addEventListener(Column.EVENT_STATE_UPDATED, columnListener);
    this.columnStateUpdateListenerDestroyFuncs.push(() => column.removeEventListener(Column.EVENT_STATE_UPDATED, columnListener));
  }
  canInferCellDataType(colDef, userColDef) {
    var _a;
    if (this.rowModel.getType() !== "clientSide") {
      return false;
    }
    const propsToCheckForInference = { cellRenderer: true, valueGetter: true, valueParser: true, refData: true };
    if (this.doColDefPropsPreventInference(userColDef, propsToCheckForInference)) {
      return false;
    }
    const columnTypes = userColDef.type === null ? colDef.type : userColDef.type;
    if (columnTypes) {
      const columnTypeDefs = (_a = this.gos.get("columnTypes")) != null ? _a : {};
      const hasPropsPreventingInference = this.convertColumnTypes(columnTypes).some((columnType) => {
        const columnTypeDef = columnTypeDefs[columnType.trim()];
        return columnTypeDef && this.doColDefPropsPreventInference(columnTypeDef, propsToCheckForInference);
      });
      if (hasPropsPreventingInference) {
        return false;
      }
    }
    return !this.doColDefPropsPreventInference(colDef, propsToCheckForInference);
  }
  doColDefPropsPreventInference(colDef, propsToCheckForInference) {
    return [
      ["cellRenderer", "agSparklineCellRenderer"],
      ["valueGetter", void 0],
      ["valueParser", void 0],
      ["refData", void 0]
    ].some(([prop, comparisonValue]) => this.doesColDefPropPreventInference(colDef, propsToCheckForInference, prop, comparisonValue));
  }
  doesColDefPropPreventInference(colDef, checkProps, prop, comparisonValue) {
    if (!checkProps[prop]) {
      return false;
    }
    const value = colDef[prop];
    if (value === null) {
      checkProps[prop] = false;
      return false;
    } else {
      return comparisonValue === void 0 ? !!value : value === comparisonValue;
    }
  }
  inferCellDataType(field, colId) {
    var _a;
    if (!field) {
      return void 0;
    }
    let value;
    const initialData = this.getInitialData();
    if (initialData) {
      const fieldContainsDots = field.indexOf(".") >= 0 && !this.gos.get("suppressFieldDotNotation");
      value = getValueUsingField(initialData, field, fieldContainsDots);
    } else {
      this.initWaitForRowData(colId);
    }
    if (value == null) {
      return void 0;
    }
    const [cellDataType] = (_a = Object.entries(this.dataTypeMatchers).find(([_cellDataType, dataTypeMatcher]) => dataTypeMatcher(value))) != null ? _a : ["object"];
    return cellDataType;
  }
  getInitialData() {
    const rowData = this.gos.get("rowData");
    if (rowData == null ? void 0 : rowData.length) {
      return rowData[0];
    } else if (this.initialData) {
      return this.initialData;
    } else {
      const rowNodes = this.rowModel.getRootNode().allLeafChildren;
      if (rowNodes == null ? void 0 : rowNodes.length) {
        return rowNodes[0].data;
      }
    }
    return null;
  }
  initWaitForRowData(colId) {
    this.columnStateUpdatesPendingInference[colId] = /* @__PURE__ */ new Set();
    if (this.isWaitingForRowData) {
      return;
    }
    this.isWaitingForRowData = true;
    const columnTypeOverridesExist = this.isColumnTypeOverrideInDataTypeDefinitions;
    if (columnTypeOverridesExist) {
      this.columnModel.queueResizeOperations();
    }
    const destroyFunc = this.addManagedListener(this.eventService, Events.EVENT_ROW_DATA_UPDATE_STARTED, (event) => {
      const { firstRowData } = event;
      if (!firstRowData) {
        return;
      }
      destroyFunc == null ? void 0 : destroyFunc();
      this.isWaitingForRowData = false;
      this.processColumnsPendingInference(firstRowData, columnTypeOverridesExist);
      this.columnStateUpdatesPendingInference = {};
      if (columnTypeOverridesExist) {
        this.columnModel.processResizeOperations();
      }
      const dataTypesInferredEvent = {
        type: Events.EVENT_DATA_TYPES_INFERRED
      };
      this.eventService.dispatchEvent(dataTypesInferredEvent);
    });
  }
  isPendingInference() {
    return this.isWaitingForRowData;
  }
  processColumnsPendingInference(firstRowData, columnTypeOverridesExist) {
    this.initialData = firstRowData;
    const state = [];
    this.columnStateUpdateListenerDestroyFuncs.forEach((destroyFunc) => destroyFunc());
    this.columnStateUpdateListenerDestroyFuncs = [];
    const newRowGroupColumnStateWithoutIndex = {};
    const newPivotColumnStateWithoutIndex = {};
    Object.entries(this.columnStateUpdatesPendingInference).forEach(([colId, columnStateUpdates]) => {
      const column = this.columnModel.getGridColumn(colId);
      if (!column) {
        return;
      }
      const oldColDef = column.getColDef();
      if (!this.columnModel.resetColumnDefIntoColumn(column, "cellDataTypeInferred")) {
        return;
      }
      const newColDef = column.getColDef();
      if (columnTypeOverridesExist && newColDef.type && newColDef.type !== oldColDef.type) {
        const updatedColumnState = this.getUpdatedColumnState(column, columnStateUpdates);
        if (updatedColumnState.rowGroup && updatedColumnState.rowGroupIndex == null) {
          newRowGroupColumnStateWithoutIndex[colId] = updatedColumnState;
        }
        if (updatedColumnState.pivot && updatedColumnState.pivotIndex == null) {
          newPivotColumnStateWithoutIndex[colId] = updatedColumnState;
        }
        state.push(updatedColumnState);
      }
    });
    if (columnTypeOverridesExist) {
      state.push(...this.columnModel.generateColumnStateForRowGroupAndPivotIndexes(newRowGroupColumnStateWithoutIndex, newPivotColumnStateWithoutIndex));
    }
    if (state.length) {
      this.columnModel.applyColumnState({ state }, "cellDataTypeInferred");
    }
    this.initialData = null;
  }
  getUpdatedColumnState(column, columnStateUpdates) {
    const columnState = this.columnModel.getColumnStateFromColDef(column);
    columnStateUpdates.forEach((key) => {
      delete columnState[key];
      if (key === "rowGroup") {
        delete columnState.rowGroupIndex;
      } else if (key === "pivot") {
        delete columnState.pivotIndex;
      }
    });
    return columnState;
  }
  checkObjectValueHandlers(defaultDataTypes) {
    const resolvedObjectDataTypeDefinition = this.dataTypeDefinitions.object;
    const defaultObjectDataTypeDefinition = defaultDataTypes.object;
    this.hasObjectValueParser = resolvedObjectDataTypeDefinition.valueParser !== defaultObjectDataTypeDefinition.valueParser;
    this.hasObjectValueFormatter = resolvedObjectDataTypeDefinition.valueFormatter !== defaultObjectDataTypeDefinition.valueFormatter;
  }
  convertColumnTypes(type) {
    let typeKeys = [];
    if (type instanceof Array) {
      const invalidArray = type.some((a) => typeof a !== "string");
      if (invalidArray) {
        console.warn("if colDef.type is supplied an array it should be of type 'string[]'");
      } else {
        typeKeys = type;
      }
    } else if (typeof type === "string") {
      typeKeys = type.split(",");
    } else {
      console.warn("colDef.type should be of type 'string' | 'string[]'");
    }
    return typeKeys;
  }
  getDateStringTypeDefinition(column) {
    var _a;
    if (!column) {
      return this.dataTypeDefinitions.dateString;
    }
    return (_a = this.getDataTypeDefinition(column)) != null ? _a : this.dataTypeDefinitions.dateString;
  }
  getDateParserFunction(column) {
    return this.getDateStringTypeDefinition(column).dateParser;
  }
  getDateFormatterFunction(column) {
    return this.getDateStringTypeDefinition(column).dateFormatter;
  }
  getDataTypeDefinition(column) {
    const colDef = column.getColDef();
    if (!colDef.cellDataType) {
      return void 0;
    }
    return this.dataTypeDefinitions[colDef.cellDataType];
  }
  getBaseDataType(column) {
    var _a;
    return (_a = this.getDataTypeDefinition(column)) == null ? void 0 : _a.baseDataType;
  }
  checkType(column, value) {
    var _a;
    if (value == null) {
      return true;
    }
    const dataTypeMatcher = (_a = this.getDataTypeDefinition(column)) == null ? void 0 : _a.dataTypeMatcher;
    if (!dataTypeMatcher) {
      return true;
    }
    return dataTypeMatcher(value);
  }
  validateColDef(colDef) {
    if (colDef.cellDataType === "object") {
      if (colDef.valueFormatter === this.dataTypeDefinitions.object.groupSafeValueFormatter && !this.hasObjectValueFormatter) {
        warnOnce('Cell data type is "object" but no value formatter has been provided. Please either provide an object data type definition with a value formatter, or set "colDef.valueFormatter"');
      }
      if (colDef.editable && colDef.valueParser === this.dataTypeDefinitions.object.valueParser && !this.hasObjectValueParser) {
        warnOnce('Cell data type is "object" but no value parser has been provided. Please either provide an object data type definition with a value parser, or set "colDef.valueParser"');
      }
    }
  }
  setColDefPropertiesForBaseDataType(colDef, dataTypeDefinition, colId) {
    const formatValue = (column, node, value) => {
      let valueFormatter = column.getColDef().valueFormatter;
      if (valueFormatter === dataTypeDefinition.groupSafeValueFormatter) {
        valueFormatter = dataTypeDefinition.valueFormatter;
      }
      return this.valueService.formatValue(column, node, value, valueFormatter);
    };
    const usingSetFilter = ModuleRegistry.__isRegistered("@ag-grid-enterprise/set-filter" /* SetFilterModule */, this.context.getGridId());
    const translate = this.localeService.getLocaleTextFunc();
    const mergeFilterParams = (params) => {
      const { filterParams } = colDef;
      colDef.filterParams = typeof filterParams === "object" ? __spreadValues(__spreadValues({}, filterParams), params) : params;
    };
    switch (dataTypeDefinition.baseDataType) {
      case "number": {
        colDef.cellEditor = "agNumberCellEditor";
        if (usingSetFilter) {
          mergeFilterParams({
            comparator: (a, b) => {
              const valA = a == null ? 0 : parseInt(a);
              const valB = b == null ? 0 : parseInt(b);
              if (valA === valB)
                return 0;
              return valA > valB ? 1 : -1;
            }
          });
        }
        break;
      }
      case "boolean": {
        colDef.cellEditor = "agCheckboxCellEditor";
        colDef.cellRenderer = "agCheckboxCellRenderer";
        colDef.suppressKeyboardEvent = (params) => !!params.colDef.editable && params.event.key === KeyCode.SPACE;
        if (usingSetFilter) {
          mergeFilterParams({
            valueFormatter: (params) => {
              if (!exists(params.value)) {
                return translate("blanks", "(Blanks)");
              }
              return translate(String(params.value), params.value ? "True" : "False");
            }
          });
        } else {
          mergeFilterParams({
            maxNumConditions: 1,
            debounceMs: 0,
            filterOptions: [
              "empty",
              {
                displayKey: "true",
                displayName: "True",
                predicate: (_filterValues, cellValue) => cellValue,
                numberOfInputs: 0
              },
              {
                displayKey: "false",
                displayName: "False",
                predicate: (_filterValues, cellValue) => cellValue === false,
                numberOfInputs: 0
              }
            ]
          });
        }
        break;
      }
      case "date": {
        colDef.cellEditor = "agDateCellEditor";
        colDef.keyCreator = (params) => formatValue(params.column, params.node, params.value);
        if (usingSetFilter) {
          mergeFilterParams({
            valueFormatter: (params) => {
              const valueFormatted = formatValue(params.column, params.node, params.value);
              return exists(valueFormatted) ? valueFormatted : translate("blanks", "(Blanks)");
            },
            treeList: true,
            treeListFormatter: (pathKey, level) => {
              if (level === 1 && pathKey != null) {
                const monthKey = MONTH_KEYS[Number(pathKey) - 1];
                return translate(monthKey, MONTH_LOCALE_TEXT[monthKey]);
              }
              return pathKey != null ? pathKey : translate("blanks", "(Blanks)");
            }
          });
        }
        break;
      }
      case "dateString": {
        colDef.cellEditor = "agDateStringCellEditor";
        colDef.keyCreator = (params) => formatValue(params.column, params.node, params.value);
        const convertToDate = dataTypeDefinition.dateParser;
        if (usingSetFilter) {
          mergeFilterParams({
            valueFormatter: (params) => {
              const valueFormatted = formatValue(params.column, params.node, params.value);
              return exists(valueFormatted) ? valueFormatted : translate("blanks", "(Blanks)");
            },
            treeList: true,
            treeListPathGetter: (value) => {
              const date = convertToDate(value != null ? value : void 0);
              return date ? [String(date.getFullYear()), String(date.getMonth() + 1), String(date.getDate())] : null;
            },
            treeListFormatter: (pathKey, level) => {
              if (level === 1 && pathKey != null) {
                const monthKey = MONTH_KEYS[Number(pathKey) - 1];
                return translate(monthKey, MONTH_LOCALE_TEXT[monthKey]);
              }
              return pathKey != null ? pathKey : translate("blanks", "(Blanks)");
            }
          });
        } else {
          mergeFilterParams({
            comparator: (filterDate, cellValue) => {
              const cellAsDate = convertToDate(cellValue);
              if (cellValue == null || cellAsDate < filterDate) {
                return -1;
              }
              if (cellAsDate > filterDate) {
                return 1;
              }
              return 0;
            }
          });
        }
        break;
      }
      case "object": {
        colDef.cellEditorParams = {
          useFormatter: true
        };
        colDef.comparator = (a, b) => {
          const column = this.columnModel.getPrimaryColumn(colId);
          const colDef2 = column == null ? void 0 : column.getColDef();
          if (!column || !colDef2) {
            return 0;
          }
          const valA = a == null ? "" : formatValue(column, null, a);
          const valB = b == null ? "" : formatValue(column, null, b);
          if (valA === valB)
            return 0;
          return valA > valB ? 1 : -1;
        };
        colDef.keyCreator = (params) => formatValue(params.column, params.node, params.value);
        if (usingSetFilter) {
          mergeFilterParams({
            valueFormatter: (params) => {
              const valueFormatted = formatValue(params.column, params.node, params.value);
              return exists(valueFormatted) ? valueFormatted : translate("blanks", "(Blanks)");
            }
          });
        } else {
          colDef.filterValueGetter = (params) => formatValue(
            params.column,
            params.node,
            this.valueService.getValue(params.column, params.node)
          );
        }
        break;
      }
    }
  }
  getDefaultDataTypes() {
    const defaultDateFormatMatcher = (value) => !!value.match("^\\d{4}-\\d{2}-\\d{2}$");
    const translate = this.localeService.getLocaleTextFunc();
    return {
      number: {
        baseDataType: "number",
        // can be empty space with legacy copy
        valueParser: (params) => {
          var _a, _b;
          return ((_b = (_a = params.newValue) == null ? void 0 : _a.trim) == null ? void 0 : _b.call(_a)) === "" ? null : Number(params.newValue);
        },
        valueFormatter: (params) => {
          if (params.value == null) {
            return "";
          }
          if (typeof params.value !== "number" || isNaN(params.value)) {
            return translate("invalidNumber", "Invalid Number");
          }
          return String(params.value);
        },
        dataTypeMatcher: (value) => typeof value === "number"
      },
      text: {
        baseDataType: "text",
        valueParser: (params) => params.newValue === "" ? null : toStringOrNull(params.newValue),
        dataTypeMatcher: (value) => typeof value === "string"
      },
      boolean: {
        baseDataType: "boolean",
        valueParser: (params) => {
          var _a, _b;
          if (params.newValue == null) {
            return params.newValue;
          }
          return ((_b = (_a = params.newValue) == null ? void 0 : _a.trim) == null ? void 0 : _b.call(_a)) === "" ? null : String(params.newValue).toLowerCase() === "true";
        },
        valueFormatter: (params) => params.value == null ? "" : String(params.value),
        dataTypeMatcher: (value) => typeof value === "boolean"
      },
      date: {
        baseDataType: "date",
        valueParser: (params) => parseDateTimeFromString(params.newValue == null ? null : String(params.newValue)),
        valueFormatter: (params) => {
          var _a;
          if (params.value == null) {
            return "";
          }
          if (!(params.value instanceof Date) || isNaN(params.value.getTime())) {
            return translate("invalidDate", "Invalid Date");
          }
          return (_a = serialiseDate(params.value, false)) != null ? _a : "";
        },
        dataTypeMatcher: (value) => value instanceof Date
      },
      dateString: {
        baseDataType: "dateString",
        dateParser: (value) => {
          var _a;
          return (_a = parseDateTimeFromString(value)) != null ? _a : void 0;
        },
        dateFormatter: (value) => {
          var _a;
          return (_a = serialiseDate(value != null ? value : null, false)) != null ? _a : void 0;
        },
        valueParser: (params) => defaultDateFormatMatcher(String(params.newValue)) ? params.newValue : null,
        valueFormatter: (params) => defaultDateFormatMatcher(String(params.value)) ? params.value : "",
        dataTypeMatcher: (value) => typeof value === "string" && defaultDateFormatMatcher(value)
      },
      object: {
        baseDataType: "object",
        valueParser: () => null,
        valueFormatter: (params) => {
          var _a;
          return (_a = toStringOrNull(params.value)) != null ? _a : "";
        }
      }
    };
  }
};
__decorateClass([
  Autowired("rowModel")
], DataTypeService.prototype, "rowModel", 2);
__decorateClass([
  Autowired("columnModel")
], DataTypeService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("valueService")
], DataTypeService.prototype, "valueService", 2);
__decorateClass([
  PostConstruct
], DataTypeService.prototype, "init", 1);
DataTypeService = __decorateClass([
  Bean("dataTypeService")
], DataTypeService);

// community-modules/core/src/syncService.ts
var SyncService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.waitingForColumns = false;
  }
  postConstruct() {
    this.addManagedPropertyListener("columnDefs", (event) => this.setColumnDefs(event));
  }
  start() {
    this.ctrlsService.whenReady(() => {
      const columnDefs = this.gos.get("columnDefs");
      if (columnDefs) {
        this.setColumnsAndData(columnDefs);
      } else {
        this.waitingForColumns = true;
      }
      this.gridReady();
    });
  }
  setColumnsAndData(columnDefs) {
    this.columnModel.setColumnDefs(columnDefs != null ? columnDefs : [], "gridInitializing");
    this.rowModel.start();
  }
  gridReady() {
    this.dispatchGridReadyEvent();
    const isEnterprise = ModuleRegistry.__isRegistered("@ag-grid-enterprise/core" /* EnterpriseCoreModule */, this.context.getGridId());
    const logger = new Logger("AG Grid", () => this.gos.get("debug"));
    logger.log(`initialised successfully, enterprise = ${isEnterprise}`);
  }
  dispatchGridReadyEvent() {
    const readyEvent = {
      type: Events.EVENT_GRID_READY
    };
    this.eventService.dispatchEvent(readyEvent);
  }
  setColumnDefs(event) {
    const columnDefs = this.gos.get("columnDefs");
    if (!columnDefs) {
      return;
    }
    if (this.waitingForColumns) {
      this.waitingForColumns = false;
      this.setColumnsAndData(columnDefs);
      return;
    }
    this.columnModel.setColumnDefs(columnDefs, convertSourceType(event.source));
  }
};
__decorateClass([
  Autowired("ctrlsService")
], SyncService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("columnModel")
], SyncService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("rowModel")
], SyncService.prototype, "rowModel", 2);
__decorateClass([
  PostConstruct
], SyncService.prototype, "postConstruct", 1);
SyncService = __decorateClass([
  Bean("syncService")
], SyncService);

// community-modules/core/src/rendering/overlays/overlayService.ts
var OverlayService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.manuallyDisplayed = false;
  }
  postConstruct() {
    this.addManagedListener(this.eventService, Events.EVENT_ROW_DATA_UPDATED, () => this.onRowDataUpdated());
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, () => this.onNewColumnsLoaded());
  }
  registerOverlayWrapperComp(overlayWrapperComp) {
    this.overlayWrapperComp = overlayWrapperComp;
    if (!this.gos.get("columnDefs") || this.gos.isRowModelType("clientSide") && !this.gos.get("rowData")) {
      this.showLoadingOverlay();
    }
  }
  showLoadingOverlay() {
    if (this.gos.get("suppressLoadingOverlay")) {
      return;
    }
    const params = {};
    const compDetails = this.userComponentFactory.getLoadingOverlayCompDetails(params);
    this.showOverlay(compDetails, "ag-overlay-loading-wrapper", "loadingOverlayComponentParams");
  }
  showNoRowsOverlay() {
    if (this.gos.get("suppressNoRowsOverlay")) {
      return;
    }
    const params = {};
    const compDetails = this.userComponentFactory.getNoRowsOverlayCompDetails(params);
    this.showOverlay(compDetails, "ag-overlay-no-rows-wrapper", "noRowsOverlayComponentParams");
  }
  showOverlay(compDetails, wrapperCssClass, gridOption) {
    const promise = compDetails.newAgStackInstance();
    const listenerDestroyFunc = this.addManagedPropertyListener(gridOption, ({ currentValue }) => {
      promise.then((comp) => {
        if (comp.refresh) {
          comp.refresh(this.gos.addGridCommonParams(__spreadValues({}, currentValue != null ? currentValue : {})));
        }
      });
    });
    this.manuallyDisplayed = this.columnModel.isReady() && !this.paginationProxy.isEmpty();
    this.overlayWrapperComp.showOverlay(promise, wrapperCssClass, listenerDestroyFunc);
  }
  hideOverlay() {
    this.manuallyDisplayed = false;
    this.overlayWrapperComp.hideOverlay();
  }
  showOrHideOverlay() {
    const isEmpty = this.paginationProxy.isEmpty();
    const isSuppressNoRowsOverlay = this.gos.get("suppressNoRowsOverlay");
    if (isEmpty && !isSuppressNoRowsOverlay) {
      this.showNoRowsOverlay();
    } else {
      this.hideOverlay();
    }
  }
  onRowDataUpdated() {
    this.showOrHideOverlay();
  }
  onNewColumnsLoaded() {
    if (this.columnModel.isReady() && !this.paginationProxy.isEmpty() && !this.manuallyDisplayed) {
      this.hideOverlay();
    }
  }
};
__decorateClass([
  Autowired("userComponentFactory")
], OverlayService.prototype, "userComponentFactory", 2);
__decorateClass([
  Autowired("paginationProxy")
], OverlayService.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("columnModel")
], OverlayService.prototype, "columnModel", 2);
__decorateClass([
  PostConstruct
], OverlayService.prototype, "postConstruct", 1);
OverlayService = __decorateClass([
  Bean("overlayService")
], OverlayService);

// community-modules/core/src/misc/stateService.ts
var StateService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.suppressEvents = true;
    this.queuedUpdateSources = /* @__PURE__ */ new Set();
    this.dispatchStateUpdateEventDebounced = debounce(() => this.dispatchQueuedStateUpdateEvents(), 0);
    // If user is doing a manual expand all node by node, we don't want to process one at a time.
    // EVENT_ROW_GROUP_OPENED is already async, so no impact of making the state async here.
    this.onRowGroupOpenedDebounced = debounce(() => this.updateCachedState("rowGroupExpansion", this.getRowGroupExpansionState()), 0);
    // similar to row expansion, want to debounce. However, selection is synchronous, so need to mark as stale in case `getState` is called.
    this.onRowSelectedDebounced = debounce(() => {
      this.staleStateKeys.delete("rowSelection");
      this.updateCachedState("rowSelection", this.getRowSelectionState());
    }, 0);
    this.staleStateKeys = /* @__PURE__ */ new Set();
  }
  postConstruct() {
    var _a;
    this.isClientSideRowModel = this.rowModel.getType() === "clientSide";
    this.cachedState = (_a = this.gos.get("initialState")) != null ? _a : {};
    this.ctrlsService.whenReady(() => this.suppressEventsAndDispatchInitEvent(() => this.setupStateOnGridReady()));
    const newColumnsLoadedDestroyFunc = this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, ({ source }) => {
      if (source === "gridInitializing") {
        newColumnsLoadedDestroyFunc == null ? void 0 : newColumnsLoadedDestroyFunc();
        this.suppressEventsAndDispatchInitEvent(() => this.setupStateOnColumnsInitialised());
      }
    });
    const rowCountReadyDestroyFunc = this.addManagedListener(this.eventService, Events.EVENT_ROW_COUNT_READY, () => {
      rowCountReadyDestroyFunc == null ? void 0 : rowCountReadyDestroyFunc();
      this.suppressEventsAndDispatchInitEvent(() => this.setupStateOnRowCountReady());
    });
    const firstDataRenderedDestroyFunc = this.addManagedListener(this.eventService, Events.EVENT_FIRST_DATA_RENDERED, () => {
      firstDataRenderedDestroyFunc == null ? void 0 : firstDataRenderedDestroyFunc();
      this.suppressEventsAndDispatchInitEvent(() => this.setupStateOnFirstDataRendered());
    });
  }
  getState() {
    if (this.staleStateKeys.size) {
      this.refreshStaleState();
    }
    return this.cachedState;
  }
  setupStateOnGridReady() {
    this.updateCachedState("sideBar", this.getSideBarState());
    this.addManagedListener(this.eventService, Events.EVENT_TOOL_PANEL_VISIBLE_CHANGED, () => this.updateCachedState("sideBar", this.getSideBarState()));
    this.addManagedListener(this.eventService, Events.EVENT_SIDE_BAR_UPDATED, () => this.updateCachedState("sideBar", this.getSideBarState()));
  }
  setupStateOnColumnsInitialised() {
    var _a;
    const initialState = (_a = this.gos.get("initialState")) != null ? _a : {};
    this.setColumnState(initialState);
    this.setColumnGroupState(initialState);
    this.updateColumnState([
      "aggregation",
      "columnOrder",
      "columnPinning",
      "columnSizing",
      "columnVisibility",
      "pivot",
      "pivot",
      "rowGroup",
      "sort"
    ]);
    this.updateCachedState("columnGroup", this.getColumnGroupState());
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VALUE_CHANGED, () => this.updateColumnState(["aggregation"]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_MOVED, () => this.updateColumnState(["columnOrder"]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PINNED, () => this.updateColumnState(["columnPinning"]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_RESIZED, () => this.updateColumnState(["columnSizing"]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VISIBLE, () => this.updateColumnState(["columnVisibility"]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_CHANGED, () => this.updateColumnState(["pivot"]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, () => this.updateColumnState(["pivot"]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, () => this.updateColumnState(["rowGroup"]));
    this.addManagedListener(this.eventService, Events.EVENT_SORT_CHANGED, () => this.updateColumnState(["sort"]));
    this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, () => this.updateColumnState([
      "aggregation",
      "columnOrder",
      "columnPinning",
      "columnSizing",
      "columnVisibility",
      "pivot",
      "pivot",
      "rowGroup",
      "sort"
    ]));
    this.addManagedListener(this.eventService, Events.EVENT_COLUMN_GROUP_OPENED, () => this.updateCachedState("columnGroup", this.getColumnGroupState()));
  }
  setupStateOnRowCountReady() {
    var _a;
    const {
      filter: filterState,
      rowGroupExpansion: rowGroupExpansionState,
      rowSelection: rowSelectionState,
      pagination: paginationState
    } = (_a = this.gos.get("initialState")) != null ? _a : {};
    const advancedFilterModel = this.gos.get("advancedFilterModel");
    if (filterState || advancedFilterModel) {
      this.setFilterState(filterState, advancedFilterModel);
    }
    if (rowGroupExpansionState) {
      this.setRowGroupExpansionState(rowGroupExpansionState);
    }
    if (rowSelectionState) {
      this.setRowSelectionState(rowSelectionState);
    }
    if (paginationState) {
      this.setPaginationState(paginationState);
    }
    this.updateCachedState("filter", this.getFilterState());
    this.updateCachedState("rowGroupExpansion", this.getRowGroupExpansionState());
    this.updateCachedState("rowSelection", this.getRowSelectionState());
    this.updateCachedState("pagination", this.getPaginationState());
    this.addManagedListener(this.eventService, Events.EVENT_FILTER_CHANGED, () => this.updateCachedState("filter", this.getFilterState()));
    this.addManagedListener(this.eventService, Events.EVENT_ROW_GROUP_OPENED, () => this.onRowGroupOpenedDebounced());
    this.addManagedListener(this.eventService, Events.EVENT_EXPAND_COLLAPSE_ALL, () => this.updateCachedState("rowGroupExpansion", this.getRowGroupExpansionState()));
    this.addManagedListener(this.eventService, Events.EVENT_SELECTION_CHANGED, () => {
      this.staleStateKeys.add("rowSelection");
      this.onRowSelectedDebounced();
    });
    this.addManagedListener(this.eventService, Events.EVENT_PAGINATION_CHANGED, (event) => {
      if (event.newPage || event.newPageSize) {
        this.updateCachedState("pagination", this.getPaginationState());
      }
    });
  }
  setupStateOnFirstDataRendered() {
    var _a;
    const {
      scroll: scrollState,
      rangeSelection: rangeSelectionState,
      focusedCell: focusedCellState,
      columnOrder: columnOrderState
    } = (_a = this.gos.get("initialState")) != null ? _a : {};
    if (focusedCellState) {
      this.setFocusedCellState(focusedCellState);
    }
    if (rangeSelectionState) {
      this.setRangeSelectionState(rangeSelectionState);
    }
    if (scrollState) {
      this.setScrollState(scrollState);
    }
    this.setColumnPivotState(!!(columnOrderState == null ? void 0 : columnOrderState.orderedColIds));
    this.updateCachedState("sideBar", this.getSideBarState());
    this.updateCachedState("focusedCell", this.getFocusedCellState());
    this.updateCachedState("rangeSelection", this.getRangeSelectionState());
    this.updateCachedState("scroll", this.getScrollState());
    this.addManagedListener(this.eventService, Events.EVENT_CELL_FOCUSED, () => this.updateCachedState("focusedCell", this.getFocusedCellState()));
    this.addManagedListener(this.eventService, Events.EVENT_RANGE_SELECTION_CHANGED, (event) => {
      if (event.finished) {
        this.updateCachedState("rangeSelection", this.getRangeSelectionState());
      }
    });
    this.addManagedListener(this.eventService, Events.EVENT_BODY_SCROLL_END, () => this.updateCachedState("scroll", this.getScrollState()));
  }
  getColumnState() {
    const pivotMode = this.columnModel.isPivotMode();
    const sortColumns = [];
    const groupColIds = [];
    const aggregationColumns = [];
    const pivotColIds = [];
    const leftColIds = [];
    const rightColIds = [];
    const hiddenColIds = [];
    const columnSizes = [];
    const columns = [];
    const columnState = this.columnModel.getColumnState();
    for (let i = 0; i < columnState.length; i++) {
      const {
        colId,
        sort,
        sortIndex,
        rowGroup,
        rowGroupIndex,
        aggFunc,
        pivot,
        pivotIndex,
        pinned,
        hide,
        width,
        flex
      } = columnState[i];
      columns.push(colId);
      if (sort) {
        sortColumns[sortIndex != null ? sortIndex : 0] = { colId, sort };
      }
      if (rowGroup) {
        groupColIds[rowGroupIndex != null ? rowGroupIndex : 0] = colId;
      }
      if (typeof aggFunc === "string") {
        aggregationColumns.push({ colId, aggFunc });
      }
      if (pivot) {
        pivotColIds[pivotIndex != null ? pivotIndex : 0] = colId;
      }
      if (pinned) {
        (pinned === "right" ? rightColIds : leftColIds).push(colId);
      }
      if (hide) {
        hiddenColIds.push(colId);
      }
      if (flex || width) {
        columnSizes.push({ colId, flex: flex != null ? flex : void 0, width });
      }
    }
    return {
      sort: sortColumns.length ? { sortModel: sortColumns } : void 0,
      rowGroup: groupColIds.length ? { groupColIds } : void 0,
      aggregation: aggregationColumns.length ? { aggregationModel: aggregationColumns } : void 0,
      pivot: pivotColIds.length || pivotMode ? { pivotMode, pivotColIds } : void 0,
      columnPinning: leftColIds.length || rightColIds.length ? { leftColIds, rightColIds } : void 0,
      columnVisibility: hiddenColIds.length ? { hiddenColIds } : void 0,
      columnSizing: columnSizes.length ? { columnSizingModel: columnSizes } : void 0,
      columnOrder: columns.length ? { orderedColIds: columns } : void 0
    };
  }
  setColumnState(initialState) {
    const {
      sort: sortState,
      rowGroup: groupState,
      aggregation: aggregationState,
      pivot: pivotState,
      columnPinning: columnPinningState,
      columnVisibility: columnVisibilityState,
      columnSizing: columnSizingState,
      columnOrder: columnOrderState
    } = initialState;
    const columnStateMap = {};
    const getColumnState = (colId) => {
      let columnState = columnStateMap[colId];
      if (columnState) {
        return columnState;
      }
      columnState = { colId };
      columnStateMap[colId] = columnState;
      return columnState;
    };
    if (sortState) {
      sortState.sortModel.forEach(({ colId, sort }, sortIndex) => {
        const columnState = getColumnState(colId);
        columnState.sort = sort;
        columnState.sortIndex = sortIndex;
      });
    }
    if (groupState) {
      groupState.groupColIds.forEach((colId, rowGroupIndex) => {
        const columnState = getColumnState(colId);
        columnState.rowGroup = true;
        columnState.rowGroupIndex = rowGroupIndex;
      });
    }
    if (aggregationState) {
      aggregationState.aggregationModel.forEach(({ colId, aggFunc }) => {
        getColumnState(colId).aggFunc = aggFunc;
      });
    }
    if (pivotState) {
      pivotState.pivotColIds.forEach((colId, pivotIndex) => {
        const columnState = getColumnState(colId);
        columnState.pivot = true;
        columnState.pivotIndex = pivotIndex;
      });
      this.gos.updateGridOptions({ options: { pivotMode: pivotState.pivotMode }, source: "gridInitializing" });
    }
    if (columnPinningState) {
      columnPinningState.leftColIds.forEach((colId) => {
        getColumnState(colId).pinned = "left";
      });
      columnPinningState.rightColIds.forEach((colId) => {
        getColumnState(colId).pinned = "right";
      });
    }
    if (columnVisibilityState) {
      columnVisibilityState.hiddenColIds.forEach((colId) => {
        getColumnState(colId).hide = true;
      });
    }
    if (columnSizingState) {
      columnSizingState.columnSizingModel.forEach(({ colId, flex, width }) => {
        const columnState = getColumnState(colId);
        columnState.flex = flex != null ? flex : null;
        columnState.width = width;
      });
    }
    const columns = columnOrderState == null ? void 0 : columnOrderState.orderedColIds;
    const applyOrder = !!(columns == null ? void 0 : columns.length);
    const columnStates = applyOrder ? columns.map((colId) => getColumnState(colId)) : Object.values(columnStateMap);
    if (columnStates.length) {
      this.columnStates = columnStates;
      const defaultState = {
        sort: null,
        sortIndex: null,
        rowGroup: null,
        rowGroupIndex: null,
        aggFunc: null,
        pivot: null,
        pivotIndex: null,
        pinned: null,
        hide: null,
        flex: null
      };
      this.columnModel.applyColumnState({
        state: columnStates,
        applyOrder,
        defaultState
      }, "gridInitializing");
    }
  }
  setColumnPivotState(applyOrder) {
    const columnStates = this.columnStates;
    this.columnStates = void 0;
    const columnGroupStates = this.columnGroupStates;
    this.columnGroupStates = void 0;
    if (!this.columnModel.isSecondaryColumnsPresent()) {
      return;
    }
    if (columnStates) {
      let secondaryColumnStates = [];
      for (const columnState of columnStates) {
        if (this.columnModel.getSecondaryColumn(columnState.colId)) {
          secondaryColumnStates.push(columnState);
        }
      }
      this.columnModel.applyColumnState({
        state: secondaryColumnStates,
        applyOrder
      }, "gridInitializing");
    }
    if (columnGroupStates) {
      this.columnModel.setColumnGroupState(columnGroupStates, "gridInitializing");
    }
  }
  getColumnGroupState() {
    const columnGroupState = this.columnModel.getColumnGroupState();
    const openColumnGroups = [];
    columnGroupState.forEach(({ groupId, open }) => {
      if (open) {
        openColumnGroups.push(groupId);
      }
    });
    return openColumnGroups.length ? { openColumnGroupIds: openColumnGroups } : void 0;
  }
  setColumnGroupState(initialState) {
    var _a;
    if (!initialState.hasOwnProperty("columnGroup")) {
      return;
    }
    const openColumnGroups = new Set((_a = initialState.columnGroup) == null ? void 0 : _a.openColumnGroupIds);
    const existingColumnGroupState = this.columnModel.getColumnGroupState();
    const stateItems = existingColumnGroupState.map(({ groupId }) => {
      const open = openColumnGroups.has(groupId);
      if (open) {
        openColumnGroups.delete(groupId);
      }
      return {
        groupId,
        open
      };
    });
    openColumnGroups.forEach((groupId) => {
      stateItems.push({
        groupId,
        open: true
      });
    });
    if (stateItems.length) {
      this.columnGroupStates = stateItems;
    }
    this.columnModel.setColumnGroupState(stateItems, "gridInitializing");
  }
  getFilterState() {
    var _a;
    let filterModel = this.filterManager.getFilterModel();
    if (filterModel && Object.keys(filterModel).length === 0) {
      filterModel = void 0;
    }
    const advancedFilterModel = (_a = this.filterManager.getAdvancedFilterModel()) != null ? _a : void 0;
    return filterModel || advancedFilterModel ? { filterModel, advancedFilterModel } : void 0;
  }
  setFilterState(filterState, gridOptionAdvancedFilterModel) {
    const { filterModel, advancedFilterModel } = filterState != null ? filterState : { advancedFilterModel: gridOptionAdvancedFilterModel };
    if (filterModel) {
      this.filterManager.setFilterModel(filterModel, "columnFilter");
    }
    if (advancedFilterModel) {
      this.filterManager.setAdvancedFilterModel(advancedFilterModel);
    }
  }
  getRangeSelectionState() {
    var _a;
    const cellRanges = (_a = this.rangeService) == null ? void 0 : _a.getCellRanges().map((cellRange) => {
      const { id, type, startRow, endRow, columns, startColumn } = cellRange;
      return {
        id,
        type,
        startRow,
        endRow,
        colIds: columns.map((column) => column.getColId()),
        startColId: startColumn.getColId()
      };
    });
    return (cellRanges == null ? void 0 : cellRanges.length) ? { cellRanges } : void 0;
  }
  setRangeSelectionState(rangeSelectionState) {
    if (!this.gos.get("enableRangeSelection") || !this.rangeService) {
      return;
    }
    const cellRanges = [];
    rangeSelectionState.cellRanges.forEach((cellRange) => {
      const columns = [];
      cellRange.colIds.forEach((colId) => {
        const column = this.columnModel.getGridColumn(colId);
        if (column) {
          columns.push(column);
        }
      });
      if (!columns.length) {
        return;
      }
      let startColumn = this.columnModel.getGridColumn(cellRange.startColId);
      if (!startColumn) {
        const allColumns = this.columnModel.getAllDisplayedColumns();
        const columnSet = new Set(columns);
        startColumn = allColumns.find((column) => columnSet.has(column));
      }
      cellRanges.push(__spreadProps(__spreadValues({}, cellRange), {
        columns,
        startColumn
      }));
    });
    this.rangeService.setCellRanges(cellRanges);
  }
  getScrollState() {
    var _a, _b, _c;
    if (!this.isClientSideRowModel) {
      return void 0;
    }
    const scrollFeature = (_a = this.ctrlsService.getGridBodyCtrl()) == null ? void 0 : _a.getScrollFeature();
    const { left } = (_b = scrollFeature == null ? void 0 : scrollFeature.getHScrollPosition()) != null ? _b : { left: 0 };
    const { top } = (_c = scrollFeature == null ? void 0 : scrollFeature.getVScrollPosition()) != null ? _c : { top: 0 };
    return top || left ? {
      top,
      left
    } : void 0;
  }
  setScrollState(scrollState) {
    var _a;
    if (!this.isClientSideRowModel) {
      return;
    }
    const { top, left } = scrollState;
    (_a = this.ctrlsService.getGridBodyCtrl()) == null ? void 0 : _a.getScrollFeature().setScrollPosition(top, left);
  }
  getSideBarState() {
    var _a, _b;
    return (_b = (_a = this.sideBarService) == null ? void 0 : _a.getSideBarComp()) == null ? void 0 : _b.getState();
  }
  getFocusedCellState() {
    if (!this.isClientSideRowModel) {
      return void 0;
    }
    const focusedCell = this.focusService.getFocusedCell();
    if (focusedCell) {
      const { column, rowIndex, rowPinned } = focusedCell;
      return {
        colId: column.getColId(),
        rowIndex,
        rowPinned
      };
    }
    return void 0;
  }
  setFocusedCellState(focusedCellState) {
    if (!this.isClientSideRowModel) {
      return;
    }
    const { colId, rowIndex, rowPinned } = focusedCellState;
    this.focusService.setFocusedCell({
      column: this.columnModel.getGridColumn(colId),
      rowIndex,
      rowPinned,
      forceBrowserFocus: true,
      preventScrollOnBrowserFocus: true
    });
  }
  getPaginationState() {
    const page = this.paginationProxy.getCurrentPage();
    const pageSize = !this.gos.get("paginationAutoPageSize") ? this.paginationProxy.getPageSize() : void 0;
    if (!page && !pageSize) {
      return;
    }
    return { page, pageSize };
  }
  setPaginationState(paginationState) {
    if (paginationState.pageSize && !this.gos.get("paginationAutoPageSize")) {
      this.paginationProxy.setPageSize(paginationState.pageSize, "initialState");
    }
    if (typeof paginationState.page === "number") {
      this.paginationProxy.setPage(paginationState.page);
    }
  }
  getRowSelectionState() {
    var _a;
    const selectionState = this.selectionService.getSelectionState();
    const noSelections = !selectionState || !Array.isArray(selectionState) && (selectionState.selectAll === false || selectionState.selectAllChildren === false) && !((_a = selectionState == null ? void 0 : selectionState.toggledNodes) == null ? void 0 : _a.length);
    return noSelections ? void 0 : selectionState;
  }
  setRowSelectionState(rowSelectionState) {
    this.selectionService.setSelectionState(rowSelectionState, "gridInitializing");
  }
  getRowGroupExpansionState() {
    const expandedRowGroups = this.expansionService.getExpandedRows();
    return expandedRowGroups.length ? {
      expandedRowGroupIds: expandedRowGroups
    } : void 0;
  }
  setRowGroupExpansionState(rowGroupExpansionState) {
    this.expansionService.expandRows(rowGroupExpansionState.expandedRowGroupIds);
  }
  updateColumnState(features) {
    const newColumnState = this.getColumnState();
    let hasChanged = false;
    Object.entries(newColumnState).forEach(([key, value]) => {
      if (!jsonEquals(value, this.cachedState[key])) {
        hasChanged = true;
      }
    });
    this.cachedState = __spreadValues(__spreadValues({}, this.cachedState), newColumnState);
    if (hasChanged) {
      this.dispatchStateUpdateEvent(features);
    }
  }
  updateCachedState(key, value) {
    const existingValue = this.cachedState[key];
    this.setCachedStateValue(key, value);
    if (!jsonEquals(value, existingValue)) {
      this.dispatchStateUpdateEvent([key]);
    }
  }
  setCachedStateValue(key, value) {
    this.cachedState = __spreadProps(__spreadValues({}, this.cachedState), {
      [key]: value
    });
  }
  refreshStaleState() {
    this.staleStateKeys.forEach((key) => {
      switch (key) {
        case "rowSelection":
          this.setCachedStateValue(key, this.getRowSelectionState());
          break;
      }
    });
    this.staleStateKeys.clear();
  }
  dispatchStateUpdateEvent(sources) {
    if (this.suppressEvents) {
      return;
    }
    sources.forEach((source) => this.queuedUpdateSources.add(source));
    this.dispatchStateUpdateEventDebounced();
  }
  dispatchQueuedStateUpdateEvents() {
    const sources = Array.from(this.queuedUpdateSources);
    this.queuedUpdateSources.clear();
    const event = {
      type: Events.EVENT_STATE_UPDATED,
      sources,
      state: this.cachedState
    };
    this.eventService.dispatchEvent(event);
  }
  suppressEventsAndDispatchInitEvent(updateFunc) {
    this.suppressEvents = true;
    this.columnAnimationService.setSuppressAnimation(true);
    updateFunc();
    setTimeout(() => {
      this.suppressEvents = false;
      this.queuedUpdateSources.clear();
      if (!this.isAlive()) {
        return;
      }
      this.columnAnimationService.setSuppressAnimation(false);
      this.dispatchStateUpdateEvent(["gridInitializing"]);
    });
  }
};
__decorateClass([
  Autowired("filterManager")
], StateService.prototype, "filterManager", 2);
__decorateClass([
  Autowired("ctrlsService")
], StateService.prototype, "ctrlsService", 2);
__decorateClass([
  Autowired("focusService")
], StateService.prototype, "focusService", 2);
__decorateClass([
  Autowired("columnModel")
], StateService.prototype, "columnModel", 2);
__decorateClass([
  Autowired("paginationProxy")
], StateService.prototype, "paginationProxy", 2);
__decorateClass([
  Autowired("rowModel")
], StateService.prototype, "rowModel", 2);
__decorateClass([
  Autowired("selectionService")
], StateService.prototype, "selectionService", 2);
__decorateClass([
  Autowired("expansionService")
], StateService.prototype, "expansionService", 2);
__decorateClass([
  Autowired("columnAnimationService")
], StateService.prototype, "columnAnimationService", 2);
__decorateClass([
  Optional("sideBarService")
], StateService.prototype, "sideBarService", 2);
__decorateClass([
  Optional("rangeService")
], StateService.prototype, "rangeService", 2);
__decorateClass([
  PostConstruct
], StateService.prototype, "postConstruct", 1);
StateService = __decorateClass([
  Bean("stateService")
], StateService);

// community-modules/core/src/validation/validationService.ts
var ValidationService = class extends BeanStub {
  init() {
    this.processGridOptions(this.gridOptions);
  }
  processGridOptions(options) {
    this.processOptions(options, GRID_OPTIONS_VALIDATORS);
  }
  processColumnDefs(options) {
    this.processOptions(options, COL_DEF_VALIDATORS);
  }
  processOptions(options, validator) {
    const { validations, deprecations, allProperties, propertyExceptions, objectName, docsUrl } = validator;
    if (allProperties && this.gridOptions.suppressPropertyNamesCheck !== true) {
      this.checkProperties(
        options,
        [...propertyExceptions != null ? propertyExceptions : [], ...Object.keys(deprecations)],
        allProperties,
        objectName,
        docsUrl
      );
    }
    const warnings = /* @__PURE__ */ new Set();
    const optionKeys = Object.keys(options);
    optionKeys.forEach((key) => {
      var _a;
      const deprecation = deprecations[key];
      if (deprecation) {
        if ("renamed" in deprecation) {
          const { renamed, version } = deprecation;
          warnings.add(`As of v${version}, ${String(key)} is deprecated. Please use ${String(renamed)} instead.`);
          options[renamed] = options[key];
        } else {
          const { message, version } = deprecation;
          warnings.add(`As of v${version}, ${String(key)} is deprecated. ${message != null ? message : ""}`);
        }
      }
      const value = options[key];
      if (value == null || value === false) {
        return;
      }
      const rulesOrGetter = validations[key];
      let rules;
      if (!rulesOrGetter) {
        return;
      } else if (typeof rulesOrGetter === "function") {
        const fromGetter = rulesOrGetter(options, this.gridOptions);
        if (!fromGetter) {
          return;
        }
        if ("objectName" in fromGetter) {
          const value2 = options[key];
          if (Array.isArray(value2)) {
            value2.forEach((item) => {
              this.processOptions(item, fromGetter);
            });
            return;
          }
          this.processOptions(options[key], fromGetter);
          return;
        }
        rules = fromGetter;
      } else {
        rules = rulesOrGetter;
      }
      const { module: module2, dependencies, supportedRowModels } = rules;
      if (supportedRowModels) {
        const rowModel = (_a = this.gridOptions.rowModelType) != null ? _a : "clientSide";
        if (!supportedRowModels.includes(rowModel)) {
          warnings.add(`${String(key)} is not supported with the '${rowModel}' row model.`);
          return;
        }
      }
      if (module2) {
        const modules = Array.isArray(module2) ? module2 : [module2];
        let allRegistered = true;
        modules.forEach((m) => {
          if (!ModuleRegistry.__assertRegistered(m, String(key), this.context.getGridId())) {
            allRegistered = false;
            warnings.add(`${String(key)} is only available when ${m} is loaded.`);
          }
        });
        if (!allRegistered) {
          return;
        }
      }
      if (dependencies) {
        const warning = this.checkForWarning(key, dependencies, options);
        if (warning) {
          warnings.add(warning);
          return;
        }
      }
    });
    if (warnings.size > 0) {
      warnings.forEach((warning) => {
        warnOnce(warning);
      });
    }
  }
  checkForWarning(key, validator, options) {
    if (typeof validator === "function") {
      return validator(options, this.gridOptions);
    }
    const optionEntries = Object.entries(validator);
    const failed = optionEntries.find(([key2, value]) => {
      const gridOptionValue = options[key2];
      return !value.includes(gridOptionValue);
    });
    if (!failed) {
      return null;
    }
    const [failedKey, possibleOptions] = failed;
    if (possibleOptions.length > 1) {
      return `'${String(key)}' requires '${failedKey}' to be one of [${possibleOptions.join(", ")}].`;
    }
    return `'${String(key)}' requires '${failedKey}' to be ${possibleOptions[0]}.`;
  }
  checkProperties(object, exceptions, validProperties, containerName, docsUrl) {
    const VUE_FRAMEWORK_PROPS = ["__ob__", "__v_skip", "__metadata__"];
    const invalidProperties = fuzzyCheckStrings(
      Object.getOwnPropertyNames(object),
      [...VUE_FRAMEWORK_PROPS, ...exceptions, ...validProperties],
      validProperties
    );
    iterateObject(invalidProperties, (key, value) => {
      warnOnce(`invalid ${containerName} property '${key}' did you mean any of these: ${value.slice(0, 8).join(", ")}`);
    });
    if (Object.keys(invalidProperties).length > 0 && docsUrl) {
      const url = this.getFrameworkOverrides().getDocLink(docsUrl);
      warnOnce(`to see all the valid ${containerName} properties please check: ${url}`);
    }
  }
};
__decorateClass([
  Autowired("gridOptions")
], ValidationService.prototype, "gridOptions", 2);
__decorateClass([
  PostConstruct
], ValidationService.prototype, "init", 1);
ValidationService = __decorateClass([
  Bean("validationService")
], ValidationService);

// community-modules/core/src/misc/apiEventService.ts
var ApiEventService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.syncEventListeners = /* @__PURE__ */ new Map();
    this.asyncEventListeners = /* @__PURE__ */ new Map();
    this.syncGlobalEventListeners = /* @__PURE__ */ new Set();
    this.globalEventListenerPairs = /* @__PURE__ */ new Map();
  }
  postConstruct() {
    this.frameworkEventWrappingService = new FrameworkEventListenerService(this.getFrameworkOverrides());
  }
  addEventListener(eventType, userListener) {
    const listener = this.frameworkEventWrappingService.wrap(userListener);
    const async = this.gos.useAsyncEvents() && !ALWAYS_SYNC_GLOBAL_EVENTS.has(eventType);
    ;
    const listeners = async ? this.asyncEventListeners : this.syncEventListeners;
    if (!listeners.has(eventType)) {
      listeners.set(eventType, /* @__PURE__ */ new Set());
    }
    listeners.get(eventType).add(listener);
    this.eventService.addEventListener(eventType, listener, async);
  }
  removeEventListener(eventType, userListener) {
    var _a;
    const listener = this.frameworkEventWrappingService.unwrap(userListener);
    const asyncListeners = this.asyncEventListeners.get(eventType);
    const hasAsync = !!(asyncListeners == null ? void 0 : asyncListeners.delete(listener));
    if (!hasAsync) {
      (_a = this.syncEventListeners.get(eventType)) == null ? void 0 : _a.delete(listener);
    }
    this.eventService.removeEventListener(eventType, listener, hasAsync);
  }
  addGlobalListener(userListener) {
    const listener = this.frameworkEventWrappingService.wrapGlobal(userListener);
    const async = this.gos.useAsyncEvents();
    if (async) {
      const syncListener = (eventType, event) => {
        if (ALWAYS_SYNC_GLOBAL_EVENTS.has(eventType)) {
          listener(eventType, event);
        }
      };
      const asyncListener = (eventType, event) => {
        if (!ALWAYS_SYNC_GLOBAL_EVENTS.has(eventType)) {
          listener(eventType, event);
        }
      };
      this.globalEventListenerPairs.set(userListener, { syncListener, asyncListener });
      this.eventService.addGlobalListener(syncListener, false);
      this.eventService.addGlobalListener(asyncListener, true);
    } else {
      this.syncGlobalEventListeners.add(listener);
      this.eventService.addGlobalListener(listener, false);
    }
  }
  removeGlobalListener(userListener) {
    const listener = this.frameworkEventWrappingService.unwrapGlobal(userListener);
    const hasAsync = this.globalEventListenerPairs.has(listener);
    if (hasAsync) {
      const { syncListener, asyncListener } = this.globalEventListenerPairs.get(listener);
      this.eventService.removeGlobalListener(syncListener, false);
      this.eventService.removeGlobalListener(asyncListener, true);
      this.globalEventListenerPairs.delete(userListener);
    } else {
      this.syncGlobalEventListeners.delete(listener);
      this.eventService.removeGlobalListener(listener, false);
    }
  }
  destroyEventListeners(map, async) {
    map.forEach((listeners, eventType) => {
      listeners.forEach((listener) => this.eventService.removeEventListener(eventType, listener, async));
      listeners.clear();
    });
    map.clear();
  }
  destroyGlobalListeners(set, async) {
    set.forEach((listener) => this.eventService.removeGlobalListener(listener, async));
    set.clear();
  }
  destroy() {
    super.destroy();
    this.destroyEventListeners(this.syncEventListeners, false);
    this.destroyEventListeners(this.asyncEventListeners, true);
    this.destroyGlobalListeners(this.syncGlobalEventListeners, false);
    this.globalEventListenerPairs.forEach(({ syncListener, asyncListener }) => {
      this.eventService.removeGlobalListener(syncListener, false);
      this.eventService.removeGlobalListener(asyncListener, true);
    });
    this.globalEventListenerPairs.clear();
  }
};
__decorateClass([
  PostConstruct
], ApiEventService.prototype, "postConstruct", 1);
ApiEventService = __decorateClass([
  Bean("apiEventService")
], ApiEventService);

// community-modules/core/src/pagination/pageSizeSelector/pageSizeSelectorComp.ts
var PageSizeSelectorComp = class extends Component {
  constructor() {
    super(
      /* html */
      `<span class="ag-paging-page-size"></span>`
    );
    this.hasEmptyOption = false;
    this.handlePageSizeItemSelected = () => {
      if (!this.selectPageSizeComp) {
        return;
      }
      const newValue = this.selectPageSizeComp.getValue();
      if (!newValue) {
        return;
      }
      const paginationPageSize = Number(newValue);
      if (isNaN(paginationPageSize) || paginationPageSize < 1 || paginationPageSize === this.paginationProxy.getPageSize()) {
        return;
      }
      this.paginationProxy.setPageSize(paginationPageSize, "pageSizeSelector");
      if (this.hasEmptyOption) {
        this.toggleSelectDisplay(true);
      }
      this.selectPageSizeComp.getFocusableElement().focus();
    };
  }
  init() {
    this.addManagedPropertyListener("paginationPageSizeSelector", () => {
      this.onPageSizeSelectorValuesChange();
    });
    this.addManagedListener(
      this.eventService,
      Events.EVENT_PAGINATION_CHANGED,
      (event) => this.handlePaginationChanged(event)
    );
  }
  handlePaginationChanged(paginationChangedEvent) {
    if (!this.selectPageSizeComp || !(paginationChangedEvent == null ? void 0 : paginationChangedEvent.newPageSize)) {
      return;
    }
    const paginationPageSize = this.paginationProxy.getPageSize();
    if (this.getPageSizeSelectorValues().includes(paginationPageSize)) {
      this.selectPageSizeComp.setValue(paginationPageSize.toString());
    } else {
      if (this.hasEmptyOption) {
        this.selectPageSizeComp.setValue("");
      } else {
        this.toggleSelectDisplay(true);
      }
    }
  }
  toggleSelectDisplay(show) {
    if (this.selectPageSizeComp) {
      this.reset();
    }
    if (!show) {
      return;
    }
    this.reloadPageSizesSelector();
    if (!this.selectPageSizeComp) {
      return;
    }
    this.appendChild(this.selectPageSizeComp);
  }
  reset() {
    clearElement(this.getGui());
    if (!this.selectPageSizeComp) {
      return;
    }
    this.destroyBean(this.selectPageSizeComp);
    this.selectPageSizeComp = void 0;
  }
  onPageSizeSelectorValuesChange() {
    if (!this.selectPageSizeComp) {
      return;
    }
    if (this.shouldShowPageSizeSelector()) {
      this.reloadPageSizesSelector();
    }
  }
  shouldShowPageSizeSelector() {
    return this.gos.get("pagination") && !this.gos.get("suppressPaginationPanel") && !this.gos.get("paginationAutoPageSize") && this.gos.get("paginationPageSizeSelector") !== false;
  }
  reloadPageSizesSelector() {
    const pageSizeOptions = this.getPageSizeSelectorValues();
    const paginationPageSizeOption = this.paginationProxy.getPageSize();
    const shouldAddAndSelectEmptyOption = !paginationPageSizeOption || !pageSizeOptions.includes(paginationPageSizeOption);
    if (shouldAddAndSelectEmptyOption) {
      pageSizeOptions.unshift("");
      warnOnce(
        `The paginationPageSize grid option is set to a value that is not in the list of page size options.
                Please make sure that the paginationPageSize grid option is set to one of the values in the 
                paginationPageSizeSelector array, or set the paginationPageSizeSelector to false to hide the page size selector.`
      );
    }
    if (this.selectPageSizeComp) {
      this.destroyBean(this.selectPageSizeComp);
      this.selectPageSizeComp = void 0;
    }
    const localeTextFunc = this.localeService.getLocaleTextFunc();
    const localisedLabel = localeTextFunc("pageSizeSelectorLabel", "Page Size:");
    const options = pageSizeOptions.map((value) => ({
      value: String(value),
      text: String(value)
    }));
    const localisedAriaLabel = localeTextFunc("ariaPageSizeSelectorLabel", "Page Size");
    this.selectPageSizeComp = this.createManagedBean(new AgSelect()).addOptions(options).setValue(String(shouldAddAndSelectEmptyOption ? "" : paginationPageSizeOption)).setAriaLabel(localisedAriaLabel).setLabel(localisedLabel).onValueChange(() => this.handlePageSizeItemSelected());
    this.hasEmptyOption = shouldAddAndSelectEmptyOption;
  }
  getPageSizeSelectorValues() {
    const defaultValues = [20, 50, 100];
    const paginationPageSizeSelectorValues = this.gos.get("paginationPageSizeSelector");
    if (!Array.isArray(paginationPageSizeSelectorValues) || !this.validateValues(paginationPageSizeSelectorValues)) {
      return defaultValues;
    }
    return [...paginationPageSizeSelectorValues].sort((a, b) => a - b);
  }
  validateValues(values2) {
    if (!values2.length) {
      warnOnce(
        `The paginationPageSizeSelector grid option is an empty array. This is most likely a mistake.
                If you want to hide the page size selector, please set the paginationPageSizeSelector to false.`
      );
      return false;
    }
    for (let i = 0; i < values2.length; i++) {
      const value = values2[i];
      const isNumber = typeof value === "number";
      const isPositive = value > 0;
      if (!isNumber) {
        warnOnce(
          `The paginationPageSizeSelector grid option contains a non-numeric value.
                    Please make sure that all values in the paginationPageSizeSelector array are numbers.`
        );
        return false;
      }
      if (!isPositive) {
        warnOnce(
          `The paginationPageSizeSelector grid option contains a negative number or zero.
                    Please make sure that all values in the paginationPageSizeSelector array are positive.`
        );
        return false;
      }
    }
    return true;
  }
  destroy() {
    this.toggleSelectDisplay(false);
    super.destroy();
  }
};
__decorateClass([
  Autowired("paginationProxy")
], PageSizeSelectorComp.prototype, "paginationProxy", 2);
__decorateClass([
  PostConstruct
], PageSizeSelectorComp.prototype, "init", 1);

// community-modules/core/src/rendering/ariaAnnouncementService.ts
var AriaAnnouncementService = class extends BeanStub {
  constructor() {
    super();
    this.descriptionContainer = null;
    this.announceValue = debounce(this.announceValue.bind(this), 200);
  }
  postConstruct() {
    const eDocument = this.gos.getDocument();
    const div = this.descriptionContainer = eDocument.createElement("div");
    div.classList.add("ag-aria-description-container");
    setAriaLive(div, "polite");
    setAriaRelevant(div, "additions text");
    setAriaAtomic(div, true);
    this.eGridDiv.appendChild(div);
  }
  announceValue(value) {
    if (!this.descriptionContainer) {
      return;
    }
    this.descriptionContainer.textContent = "";
    setTimeout(() => {
      if (this.isAlive() && this.descriptionContainer) {
        this.descriptionContainer.textContent = value;
      }
    }, 50);
  }
  destroy() {
    super.destroy();
    const { descriptionContainer } = this;
    if (descriptionContainer) {
      clearElement(descriptionContainer);
      if (descriptionContainer.parentElement) {
        descriptionContainer.parentElement.removeChild(descriptionContainer);
      }
    }
    this.descriptionContainer = null;
    this.eGridDiv = null;
  }
};
__decorateClass([
  Autowired("eGridDiv")
], AriaAnnouncementService.prototype, "eGridDiv", 2);
__decorateClass([
  PostConstruct
], AriaAnnouncementService.prototype, "postConstruct", 1);
AriaAnnouncementService = __decorateClass([
  Bean("ariaAnnouncementService")
], AriaAnnouncementService);

// community-modules/core/src/grid.ts
var GlobalGridOptions = class {
};
GlobalGridOptions.gridOptions = void 0;
function provideGlobalGridOptions(gridOptions) {
  GlobalGridOptions.gridOptions = gridOptions;
}
function createGrid(eGridDiv, gridOptions, params) {
  if (!gridOptions) {
    errorOnce("No gridOptions provided to createGrid");
    return {};
  }
  const api = new GridCoreCreator().create(eGridDiv, gridOptions, (context) => {
    const gridComp = new GridComp(eGridDiv);
    context.createBean(gridComp);
  }, void 0, params);
  if (!Object.isFrozen(gridOptions) && !(params == null ? void 0 : params.frameworkOverrides)) {
    const apiUrl = "https://ag-grid.com/javascript-data-grid/grid-interface/#grid-api";
    Object.defineProperty(gridOptions, "api", {
      get: () => {
        errorOnce(`gridOptions.api is no longer supported. See ${apiUrl}.`);
        return void 0;
      },
      configurable: true
    });
    Object.defineProperty(gridOptions, "columnApi", {
      get: () => {
        errorOnce(`gridOptions.columnApi is no longer supported and all methods moved to the grid api. See ${apiUrl}.`);
        return void 0;
      },
      configurable: true
    });
  }
  return api;
}
var Grid = class {
  // Not typed to enable setting api / columnApi for backwards compatibility
  constructor(eGridDiv, gridOptions, params) {
    warnOnce("Since v31 new Grid(...) is deprecated. Use createGrid instead: `const gridApi = createGrid(...)`. The grid api is returned from createGrid and will not be available on gridOptions.");
    if (!gridOptions) {
      errorOnce("No gridOptions provided to the grid");
      return;
    }
    this.gridOptions = gridOptions;
    const api = new GridCoreCreator().create(
      eGridDiv,
      gridOptions,
      (context) => {
        const gridComp = new GridComp(eGridDiv);
        const bean = context.createBean(gridComp);
        bean.addDestroyFunc(() => {
          this.destroy();
        });
      },
      void 0,
      params
    );
    this.gridOptions.api = api;
    this.gridOptions.columnApi = new ColumnApi(api);
  }
  destroy() {
    var _a;
    if (this.gridOptions) {
      (_a = this.gridOptions.api) == null ? void 0 : _a.destroy();
      delete this.gridOptions.api;
      delete this.gridOptions.columnApi;
    }
  }
};
var nextGridId = 1;
var GridCoreCreator = class {
  create(eGridDiv, providedOptions, createUi, acceptChanges, params) {
    var _a;
    let mergedGridOps = {};
    if (GlobalGridOptions.gridOptions) {
      mergeDeep(mergedGridOps, GlobalGridOptions.gridOptions, true, true);
      mergedGridOps = __spreadValues(__spreadValues({}, mergedGridOps), providedOptions);
    } else {
      mergedGridOps = providedOptions;
    }
    const gridOptions = GridOptionsService.getCoercedGridOptions(mergedGridOps);
    const debug = !!gridOptions.debug;
    const gridId = (_a = gridOptions.gridId) != null ? _a : String(nextGridId++);
    const registeredModules = this.getRegisteredModules(params, gridId);
    const beanClasses = this.createBeansList(gridOptions.rowModelType, registeredModules, gridId);
    const providedBeanInstances = this.createProvidedBeans(eGridDiv, gridOptions, params);
    if (!beanClasses) {
      errorOnce("Failed to create grid.");
      return void 0;
    }
    const contextParams = {
      providedBeanInstances,
      beanClasses,
      debug,
      gridId
    };
    const contextLogger = new Logger("Context", () => contextParams.debug);
    const context = new Context(contextParams, contextLogger);
    const beans = context.getBean("beans");
    this.registerModuleUserComponents(beans, registeredModules);
    this.registerStackComponents(beans, registeredModules);
    this.registerControllers(beans, registeredModules);
    createUi(context);
    beans.syncService.start();
    if (acceptChanges) {
      acceptChanges(context);
    }
    const gridApi = context.getBean("gridApi");
    return gridApi;
  }
  registerControllers(beans, registeredModules) {
    registeredModules.forEach((module2) => {
      if (module2.controllers) {
        module2.controllers.forEach((meta) => beans.ctrlsFactory.register(meta));
      }
    });
  }
  registerStackComponents(beans, registeredModules) {
    const agStackComponents = this.createAgStackComponentsList(registeredModules);
    beans.agStackComponentsRegistry.setupComponents(agStackComponents);
  }
  getRegisteredModules(params, gridId) {
    const passedViaConstructor = params ? params.modules : null;
    const registered = ModuleRegistry.__getRegisteredModules(gridId);
    const allModules = [];
    const mapNames = {};
    const addModule = (moduleBased, mod, gridId2) => {
      const addIndividualModule = (currentModule) => {
        if (!mapNames[currentModule.moduleName]) {
          mapNames[currentModule.moduleName] = true;
          allModules.push(currentModule);
          ModuleRegistry.__register(currentModule, moduleBased, gridId2);
        }
      };
      addIndividualModule(mod);
      if (mod.dependantModules) {
        mod.dependantModules.forEach((m) => addModule(moduleBased, m, gridId2));
      }
    };
    if (passedViaConstructor) {
      passedViaConstructor.forEach((m) => addModule(true, m, gridId));
    }
    if (registered) {
      registered.forEach((m) => addModule(!ModuleRegistry.__isPackageBased(), m, void 0));
    }
    return allModules;
  }
  registerModuleUserComponents(beans, registeredModules) {
    const moduleUserComps = this.extractModuleEntity(
      registeredModules,
      (module2) => module2.userComponents ? module2.userComponents : []
    );
    moduleUserComps.forEach((compMeta) => {
      beans.userComponentRegistry.registerDefaultComponent(compMeta.componentName, compMeta.componentClass);
    });
  }
  createProvidedBeans(eGridDiv, gridOptions, params) {
    let frameworkOverrides = params ? params.frameworkOverrides : null;
    if (missing(frameworkOverrides)) {
      frameworkOverrides = new VanillaFrameworkOverrides();
    }
    const seed = {
      gridOptions,
      eGridDiv,
      globalEventListener: params ? params.globalEventListener : null,
      globalSyncEventListener: params ? params.globalSyncEventListener : null,
      frameworkOverrides
    };
    if (params && params.providedBeanInstances) {
      Object.assign(seed, params.providedBeanInstances);
    }
    return seed;
  }
  createAgStackComponentsList(registeredModules) {
    let components = [
      { componentName: "AgCheckbox", componentClass: AgCheckbox },
      { componentName: "AgRadioButton", componentClass: AgRadioButton },
      { componentName: "AgToggleButton", componentClass: AgToggleButton },
      { componentName: "AgInputTextField", componentClass: AgInputTextField },
      { componentName: "AgInputTextArea", componentClass: AgInputTextArea },
      { componentName: "AgInputNumberField", componentClass: AgInputNumberField },
      { componentName: "AgInputDateField", componentClass: AgInputDateField },
      { componentName: "AgInputRange", componentClass: AgInputRange },
      { componentName: "AgRichSelect", componentClass: AgRichSelect },
      { componentName: "AgSelect", componentClass: AgSelect },
      { componentName: "AgSlider", componentClass: AgSlider },
      { componentName: "AgGridBody", componentClass: GridBodyComp },
      { componentName: "AgHeaderRoot", componentClass: GridHeaderComp },
      { componentName: "AgSortIndicator", componentClass: SortIndicatorComp },
      { componentName: "AgPagination", componentClass: PaginationComp },
      { componentName: "AgPageSizeSelector", componentClass: PageSizeSelectorComp },
      { componentName: "AgOverlayWrapper", componentClass: OverlayWrapperComponent },
      { componentName: "AgGroupComponent", componentClass: AgGroupComponent },
      { componentName: "AgRowContainer", componentClass: RowContainerComp },
      { componentName: "AgFakeHorizontalScroll", componentClass: FakeHScrollComp },
      { componentName: "AgFakeVerticalScroll", componentClass: FakeVScrollComp },
      { componentName: "AgAutocomplete", componentClass: AgAutocomplete }
    ];
    const moduleAgStackComps = this.extractModuleEntity(
      registeredModules,
      (module2) => module2.agStackComponents ? module2.agStackComponents : []
    );
    components = components.concat(moduleAgStackComps);
    return components;
  }
  createBeansList(rowModelType = "clientSide", registeredModules, gridId) {
    const rowModelModules = registeredModules.filter((module2) => !module2.rowModel || module2.rowModel === rowModelType);
    const rowModelModuleNames = {
      clientSide: "@ag-grid-community/client-side-row-model" /* ClientSideRowModelModule */,
      infinite: "@ag-grid-community/infinite-row-model" /* InfiniteRowModelModule */,
      serverSide: "@ag-grid-enterprise/server-side-row-model" /* ServerSideRowModelModule */,
      viewport: "@ag-grid-enterprise/viewport-row-model" /* ViewportRowModelModule */
    };
    if (!rowModelModuleNames[rowModelType]) {
      errorOnce("Could not find row model for rowModelType = " + rowModelType);
      return;
    }
    if (!ModuleRegistry.__assertRegistered(rowModelModuleNames[rowModelType], `rowModelType = '${rowModelType}'`, gridId)) {
      return;
    }
    const beans = [
      Beans,
      RowPositionUtils,
      CellPositionUtils,
      HeaderPositionUtils,
      PaginationAutoPageSizeService,
      GridApi,
      UserComponentRegistry,
      AgComponentUtils,
      ComponentMetadataProvider,
      ResizeObserverService,
      UserComponentFactory,
      RowContainerHeightService,
      HorizontalResizeService,
      LocaleService,
      ValidationService,
      PinnedRowModel,
      DragService,
      DisplayedGroupCreator,
      EventService,
      GridOptionsService,
      PopupService,
      SelectionService,
      FilterManager,
      ColumnModel,
      HeaderNavigationService,
      PaginationProxy,
      RowRenderer,
      ExpressionService,
      ColumnFactory,
      AlignedGridsService,
      NavigationService,
      ValueCache,
      ValueService,
      LoggerFactory,
      AutoWidthCalculator,
      StandardMenuFactory,
      DragAndDropService,
      ColumnApi,
      FocusService,
      MouseEventService,
      Environment,
      CellNavigationService,
      StylingService,
      ScrollVisibleService,
      SortController,
      ColumnHoverService,
      ColumnAnimationService,
      SelectableService,
      AutoGroupColService,
      ChangeDetectionService,
      AnimationFrameService,
      UndoRedoService,
      AgStackComponentsRegistry,
      ColumnDefFactory,
      RowCssClassCalculator,
      RowNodeBlockLoader,
      RowNodeSorter,
      CtrlsService,
      PinnedWidthService,
      RowNodeEventThrottle,
      CtrlsFactory,
      DataTypeService,
      QuickFilterService,
      SyncService,
      OverlayService,
      StateService,
      ExpansionService,
      ApiEventService,
      AriaAnnouncementService,
      MenuService
    ];
    const moduleBeans = this.extractModuleEntity(rowModelModules, (module2) => module2.beans ? module2.beans : []);
    beans.push(...moduleBeans);
    const beansNoDuplicates = [];
    beans.forEach((bean) => {
      if (beansNoDuplicates.indexOf(bean) < 0) {
        beansNoDuplicates.push(bean);
      }
    });
    return beansNoDuplicates;
  }
  extractModuleEntity(moduleEntities, extractor) {
    return [].concat(...moduleEntities.map(extractor));
  }
};

// community-modules/core/src/components/framework/frameworkComponentWrapper.ts
var BaseComponentWrapper = class {
  wrap(OriginalConstructor, mandatoryMethodList, optionalMethodList = [], componentType) {
    const wrapper = this.createWrapper(OriginalConstructor, componentType);
    mandatoryMethodList.forEach((methodName) => {
      this.createMethod(wrapper, methodName, true);
    });
    optionalMethodList.forEach((methodName) => {
      this.createMethod(wrapper, methodName, false);
    });
    return wrapper;
  }
  unwrap(comp) {
    return comp;
  }
  createMethod(wrapper, methodName, mandatory) {
    wrapper.addMethod(methodName, this.createMethodProxy(wrapper, methodName, mandatory));
  }
  createMethodProxy(wrapper, methodName, mandatory) {
    return function() {
      if (wrapper.hasMethod(methodName)) {
        return wrapper.callMethod(methodName, arguments);
      }
      if (mandatory) {
        console.warn("AG Grid: Framework component is missing the method " + methodName + "()");
      }
      return null;
    };
  }
};

// community-modules/core/src/interfaces/iChartOptions.ts
var ChartMappings = class {
};
ChartMappings.CHART_TYPE_TO_SERIES_TYPE = {
  column: "bar",
  groupedColumn: "bar",
  stackedColumn: "bar",
  normalizedColumn: "bar",
  bar: "bar",
  groupedBar: "bar",
  stackedBar: "bar",
  normalizedBar: "bar",
  line: "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"
};
ChartMappings.COMBO_CHART_TYPES = ["columnLineCombo", "areaColumnCombo", "customCombo"];
ChartMappings.SERIES_GROUP_TYPES = ["grouped", "stacked", "normalized"];

// community-modules/core/src/interfaces/iAgChartOptions.ts
var __FORCE_MODULE_DETECTION = 0;

// community-modules/core/src/interfaces/iSparklineCellRendererParams.ts
var BarColumnLabelPlacement = /* @__PURE__ */ ((BarColumnLabelPlacement2) => {
  BarColumnLabelPlacement2["InsideBase"] = "insideBase";
  BarColumnLabelPlacement2["InsideEnd"] = "insideEnd";
  BarColumnLabelPlacement2["Center"] = "center";
  BarColumnLabelPlacement2["OutsideEnd"] = "outsideEnd";
  return BarColumnLabelPlacement2;
})(BarColumnLabelPlacement || {});

// community-modules/core/src/main.ts
var globalObj = typeof global === "undefined" ? {} : global;
globalObj.HTMLElement = typeof HTMLElement === "undefined" ? {} : HTMLElement;
globalObj.HTMLButtonElement = typeof HTMLButtonElement === "undefined" ? {} : HTMLButtonElement;
globalObj.HTMLSelectElement = typeof HTMLSelectElement === "undefined" ? {} : HTMLSelectElement;
globalObj.HTMLInputElement = typeof HTMLInputElement === "undefined" ? {} : HTMLInputElement;
globalObj.Node = typeof Node === "undefined" ? {} : Node;
globalObj.MouseEvent = typeof MouseEvent === "undefined" ? {} : MouseEvent;
