"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.ToolbarCollectionState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _bexCore = require("@wix/bex-core");
var _simplifyColumns = require("./simplifyColumns");
var _ToolbarBIReporter = require("./ToolbarBIReporter");
var _SidePanelsState = require("./SidePanelsState");
var _RectState = require("./RectState");
var _BulkActionToolbarState = require("./BulkActionToolbarState");
var _util = require("@wix/bex-core/util");
var _simplifyExtendedColumns = require("./simplifyExtendedColumns");
var _ToolbarState = require("../components/CollectionToolbars/ToolbarState");
var _ColumnSizesState = require("./ColumnSizesState");
class ToolbarCollectionState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "collection", void 0);
    (0, _defineProperty2.default)(this, "selectedColumns", (0, _bexCore.idArrayFilter)());
    (0, _defineProperty2.default)(this, "initTask", new _bexCore.TaskState());
    (0, _defineProperty2.default)(this, "fedopsReporter", void 0);
    (0, _defineProperty2.default)(this, "dataCapsule", void 0);
    (0, _defineProperty2.default)(this, "toolbar", void 0);
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "namespace", void 0);
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "featuredComponents", {
      moreFiltersButton: new _bexCore.ValueBox(null),
      appliedFiltersTagList: new _bexCore.ValueBox(null),
      exportButton: new _bexCore.ValueBox(null),
      exportModal: new _bexCore.ValueBox(null)
    });
    (0, _defineProperty2.default)(this, "toolbarRect", void 0);
    (0, _defineProperty2.default)(this, "itemsContentRect", void 0);
    (0, _defineProperty2.default)(this, "panels", void 0);
    (0, _defineProperty2.default)(this, "bulk", void 0);
    (0, _defineProperty2.default)(this, "multi", void 0);
    (0, _defineProperty2.default)(this, "componentType", void 0);
    (0, _defineProperty2.default)(this, "_syncedProps", void 0);
    (0, _defineProperty2.default)(this, "_userColumns", []);
    // columns propagated from user
    (0, _defineProperty2.default)(this, "_featureColumns", _mobx.observable.array());
    // columns propagated from installed features
    (0, _defineProperty2.default)(this, "_extendedColumns", []);
    // columns propagated from data-extension (can be merged with above?)
    (0, _defineProperty2.default)(this, "internalScroll", undefined);
    (0, _defineProperty2.default)(this, "customColumnsState", null);
    (0, _defineProperty2.default)(this, "customColumnsStateInitialized", false);
    (0, _defineProperty2.default)(this, "columnSizesState", null);
    (0, _defineProperty2.default)(this, "multiLevelSorting", null);
    (0, _defineProperty2.default)(this, "liveRegionRef", {
      current: null
    });
    (0, _defineProperty2.default)(this, "collectionDataExtension", null);
    (0, _defineProperty2.default)(this, "menuItemExtensions", new Map());
    (0, _defineProperty2.default)(this, "tagsCollectionState", null);
    (0, _defineProperty2.default)(this, "toolbarFiltersState", null);
    (0, _defineProperty2.default)(this, "toolbarFiltersStateInitialized", false);
    (0, _defineProperty2.default)(this, "_dnd", null);
    (0, _defineProperty2.default)(this, "toolbarBIReporter", void 0);
    (0, _defineProperty2.default)(this, "filtersProps", null);
    (0, _defineProperty2.default)(this, "viewsProps", null);
    (0, _defineProperty2.default)(this, "dragAndDropCategories", null);
    (0, _defineProperty2.default)(this, "customColumnsProps", null);
    (0, _defineProperty2.default)(this, "selectionProps", new _bexCore.ValueBox({}));
    (0, _defineProperty2.default)(this, "featuresAvailability", {});
    (0, _defineProperty2.default)(this, "additionalFeaturesAvailability", {});
    (0, _defineProperty2.default)(this, "actionCell", new _bexCore.ValueBox(undefined));
    (0, _defineProperty2.default)(this, "contentPadding", 24);
    (0, _defineProperty2.default)(this, "contentPaddingPx", `${this.contentPadding}px`);
    (0, _defineProperty2.default)(this, "scrollElementRect", (0, _mobx.observable)({
      height: null,
      top: null
    }));
    (0, _defineProperty2.default)(this, "scrollTopBeforeUnmount", null);
    (0, _defineProperty2.default)(this, "minimizedHeaderHeight", 0);
    (0, _defineProperty2.default)(this, "tabsFilterProps", undefined);
    (0, _defineProperty2.default)(this, "viewsState", void 0);
    (0, _defineProperty2.default)(this, "exportState", void 0);
    (0, _defineProperty2.default)(this, "pendingQuery", void 0);
    (0, _defineProperty2.default)(this, "AddApplyFiltersButton", void 0);
    (0, _defineProperty2.default)(this, "tabs", void 0);
    (0, _defineProperty2.default)(this, "_searchExpanded", false);
    (0, _defineProperty2.default)(this, "forceRenderIndexes", undefined);
    (0, _defineProperty2.default)(this, "getCollectionSnapshot", () => {
      var _this$viewsState, _originQuery$sort;
      const {
        collection: {
          result: {
            originQuery
          }
        }
      } = this;
      return {
        viewShown: (_this$viewsState = this.viewsState) == null || (_this$viewsState = _this$viewsState.views.currentView) == null ? void 0 : _this$viewsState.id,
        tabShown: this.getCurrentTabName(),
        sortOrderApplied: (_originQuery$sort = originQuery.sort) != null && _originQuery$sort.length ? JSON.stringify(originQuery.sort) : undefined,
        filtersApplied: JSON.stringify(originQuery.filtersKey),
        filteredListSizeShown: this.collection.result.total
      };
    });
    (0, _defineProperty2.default)(this, "_toStoredColumn", column => {
      const {
        id,
        defaultHidden,
        hideable,
        hiddenFromCustomColumnsSelection
      } = column;
      return {
        id,
        isSelected: !hideable || hiddenFromCustomColumnsSelection || !defaultHidden
      };
    });
    (0, _defineProperty2.default)(this, "_adjustSelectedColumns", () => {
      const {
        selectedColumns,
        customColumnsState,
        customColumnsProps,
        customColumnsStateInitialized
      } = this;

      // as long as consumer rendered `<CustomColumns/>` at least once, use `mergeNewColumns` strategy when re-rendering new columns prop
      if (customColumnsProps != null || customColumnsStateInitialized) {
        // if `customColumns` is not set yet - do nothing
        if (customColumnsState) {
          const {
            initTask
          } = customColumnsState;
          const mergedColumns = customColumnsState.mergeNewColumns();
          (0, _mobx.runInAction)(() => {
            selectedColumns.defaultValue = this.columns.map(col => {
              const {
                id,
                isSelected
              } = this._toStoredColumn(col);
              return {
                id,
                isSelected
              };
            });
          });
          if (initTask.status.isSuccess && customColumnsState._touched) {
            selectedColumns.refresh(mergedColumns);
          } else {
            selectedColumns.setValue(mergedColumns);
          }
        }
      } else {
        const allColumns = this.columns.map(({
          id
        }) => ({
          id,
          isSelected: true
        }));
        selectedColumns.defaultValue = allColumns;
        selectedColumns.setValue(allColumns);
      }
    });
    (0, _defineProperty2.default)(this, "closeSidePanel", () => {
      this.sidePanel.close();
    });
    (0, _defineProperty2.default)(this, "retryErrorState", (0, _mobx.action)(() => {
      const {
        initTask,
        multi
      } = this;
      if (initTask.status.isError) {
        initTask.runOnce();
      } else {
        multi.retryErrorState();
      }
    }));
    (0, _defineProperty2.default)(this, "onSelectionStarted", () => {
      this.bulk._selectionStartTime = performance.now();
    });
    (0, _defineProperty2.default)(this, "onSelectionChanged", (0, _mobx.action)((_selectedIds, change) => {
      if (change == null) {
        return;
      }
      const {
        panels,
        bulk
      } = this;
      panels.closeSidePanel();
      switch (change.type) {
        case 'ALL':
          bulk.toggleSelectAll({
            location: 'Checkbox'
          });
          break;
        case 'NONE':
          bulk.deselectAll({
            location: 'Checkbox'
          });
          break;
        case 'SINGLE_TOGGLE':
          if (change.value) {
            bulk.selectOne(change.id);
          } else {
            bulk.deselectOne(change.id);
          }
          break;
      }
    }));
    (0, _defineProperty2.default)(this, "openCustomFieldModal", ({
      customOrigin
    } = {}) => {
      var _this$collectionDataE;
      return (_this$collectionDataE = this.collectionDataExtension) == null ? void 0 : _this$collectionDataE.customFieldsPanel.openCustomFieldModal({
        origin: 'external',
        customOrigin
      });
    });
    (0, _defineProperty2.default)(this, "openManageTagsModal", () => {
      var _this$tagsCollectionS;
      return (_this$tagsCollectionS = this.tagsCollectionState) == null ? void 0 : _this$tagsCollectionS.openManageTagsModal();
    });
    (0, _defineProperty2.default)(this, "onAddItemActionComplete", async items => {
      await this._resetQueryAndAddItems(items);
      this.toolbarBIReporter.newItemCreationEnd(items);
    });
    (0, _defineProperty2.default)(this, "_resetQueryAndAddItems", async items => {
      var _collection$_optimist, _collection$scrollabl;
      const {
        collection
      } = this;
      const {
        query
      } = collection;
      query.resetFilters();
      query.resetSorting();
      await collection.clearResultAndMoveToStart({
        force: true
      });
      (_collection$_optimist = collection._optimisticActions) == null || _collection$_optimist.createMany(items, {
        submit: async () => items
      });
      (_collection$scrollabl = collection.scrollableContent) == null || _collection$scrollabl.scrollTo == null || _collection$scrollabl.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    });
    this.collection = params.collection;
    this.container = params.container;
    this.componentType = params.componentType;
    this.toolbar = new _ToolbarState.ToolbarState(this);
    this.fedopsReporter = new _bexCore.FedopsReporter({
      componentName: this.componentType,
      collection: this.collection,
      internalMonitor: this.container.internalMonitor
    });
    this.multi = new _bexCore.MultiCollectionSupport({
      collections: [this.collection]
    });
    this.itemsContentRect = new _RectState.RectState(params);
    this.toolbarRect = new _RectState.RectState(params);
    this.panels = new _SidePanelsState.SidePanelsState({
      container: this.container,
      panelGroupName: this.collection.queryName
    });
    this.toolbarBIReporter = new _ToolbarBIReporter.ToolbarBIReporter({
      toolbar: this,
      collection: this.collection,
      reportBi: ev => {
        this.reportBi({
          ...ev,
          params: {
            ...this._commonDynamicBiParams(),
            ...ev.params
          }
        });
      }
    });
    this.bulk = new _BulkActionToolbarState.BulkActionToolbarState({
      toolbarBIReporter: this.toolbarBIReporter,
      panels: this.panels,
      multi: this.multi,
      translate: this.container.translate,
      scrollToTop: () => {
        var _this$collection$scro;
        (_this$collection$scro = this.collection.scrollableContent) == null || _this$collection$scro.scrollTo({
          top: 0,
          left: 0
        });
      }
    });
    this.namespace = [this.container.environment.componentId, this.collection.queryName].join('.');
    const {
      dataCapsule
    } = this.container.createEssentials({
      dataCapsule: {
        namespace: this.namespace
      }
    });
    this.dataCapsule = dataCapsule;
    const reportBiBase = params.reportBi ?? this.container.reportBi;
    this.reportBi = ev => {
      reportBiBase({
        ...ev,
        params: {
          ...this._commonDynamicBiParams(),
          ...ev.params
        }
      });
    };
    this.columnSizesState = new _ColumnSizesState.ColumnSizesState({
      container: this.container,
      dataCapsule: this.dataCapsule,
      fqdn: this.namespace
    });
    (0, _mobx.makeObservable)(this, {
      forceRenderIndexes: _mobx.observable.ref,
      _userColumns: _mobx.observable.ref,
      _extendedColumns: _mobx.observable.ref,
      columns: _mobx.computed,
      customColumnsStateInitialized: _mobx.observable.ref,
      viewsProps: _mobx.observable.ref,
      dragAndDropCategories: _mobx.observable.ref,
      customColumnsProps: _mobx.observable.ref,
      filtersProps: _mobx.observable.ref,
      shouldDisplayFiltersTags: _mobx.computed,
      totalStickyContentHeight: _mobx.computed,
      showInitialLoader: _mobx.computed,
      showEmptyState: _mobx.computed,
      showErrorState: _mobx.computed,
      hasSubToolbarComponents: _mobx.computed,
      containerRect: _mobx.computed,
      setFilterTagsPropsIfChanged: _mobx.action,
      _initDefaultSortableColumn: _mobx.action,
      minimizedHeaderHeight: _mobx.observable.ref,
      tabsFilterProps: _mobx.observable.ref,
      toolbarFiltersStateInitialized: _mobx.observable.ref,
      hasToolbarTabs: _mobx.computed,
      itemsContentHeight: _mobx.computed,
      setNewColumns: _mobx.action,
      addFeatureColumn: _mobx.action,
      setNewExtendedColumns: _mobx.action,
      _commonDynamicBiParams: _mobx.action,
      _adjustSortWithNewColumns: _mobx.action,
      setToolbarFiltersStateInitialized: _mobx.action,
      activeFiltersEntries: _mobx.computed,
      _searchExpanded: _mobx.observable.ref
    });
  }
  get containerRect() {
    const {
      itemsContentRect,
      toolbarRect,
      internalScroll
    } = this;
    if (internalScroll && itemsContentRect.rect.height) {
      return {
        ...itemsContentRect.rect
      };
    }
    if (itemsContentRect.rect.left && toolbarRect.rect.left) {
      const top = toolbarRect.rect.bottom;
      const bottom = top + itemsContentRect.rect.height;
      const left = toolbarRect.rect.left;
      const right = left + toolbarRect.rect.width;
      return {
        left,
        right,
        top,
        bottom,
        height: bottom - top,
        width: right - left
      };
    }
    return undefined;
  }
  get containerTop() {
    var _this$containerRect;
    return (_this$containerRect = this.containerRect) == null ? void 0 : _this$containerRect.top;
  }

  /**
   * How much height left for the content inside the viewport
   */
  get itemsContentHeight() {
    const {
      toolbarRect,
      scrollElementRect,
      contentPadding,
      internalScroll,
      itemsContentRect
    } = this;
    if (internalScroll && itemsContentRect.rect.height) {
      return itemsContentRect.rect.height;
    }
    if (toolbarRect.rect.height == null || toolbarRect.rect.top == null || scrollElementRect.height == null || scrollElementRect.top == null) {
      return 0;
    }
    if (process.env.NODE_ENV === 'test') {
      return 796;
    }
    const toolbarOffsetTop = toolbarRect.rect.top - scrollElementRect.top;
    return scrollElementRect.height - toolbarOffsetTop - toolbarRect.rect.height - contentPadding;
  }
  get totalStickyContentHeight() {
    const {
      toolbarRect,
      minimizedHeaderHeight
    } = this;
    if (toolbarRect.rect.height == null) {
      return null;
    }
    return toolbarRect.rect.height + minimizedHeaderHeight;
  }
  get sidePanel() {
    return this.panels.sidePanel;
  }
  get sidePanelComponents() {
    return this.panels.sidePanelComponents;
  }
  get showInitialLoader() {
    const {
      multi,
      initTask
    } = this;
    return multi.showInitialLoader || initTask.status.isLoading || initTask.status.isIdle;
  }
  get showEmptyState() {
    const {
      showInitialLoader,
      multi: {
        showRefreshLoader,
        showEmptyState
      }
    } = this;
    return showEmptyState && !showInitialLoader && !showRefreshLoader;
  }
  get errorStatus() {
    const {
      initTask,
      multi
    } = this;
    return initTask.errorStatus ?? multi.errorStatus;
  }
  get showErrorState() {
    const {
      showInitialLoader,
      multi: {
        showRefreshLoader,
        showErrorState
      },
      initTask
    } = this;
    return (showErrorState || initTask.status.isError) && !showInitialLoader && !showRefreshLoader;
  }
  get hasSubToolbarComponents() {
    const {
      appliedFiltersTagList
    } = this.featuredComponents;
    return appliedFiltersTagList.value != null;
  }
  get reorderModeState() {
    var _this$_dnd;
    return (_this$_dnd = this._dnd) == null ? void 0 : _this$_dnd.reorderModeState;
  }
  get shouldDisplayFiltersTags() {
    var _this$featuredCompone;
    return !!((_this$featuredCompone = this.featuredComponents.appliedFiltersTagList.value) != null && _this$featuredCompone.state.tags.length);
  }
  get hasToolbarTabs() {
    return this.tabsFilterProps != null;
  }
  get isReorderModeToolbarVisible() {
    var _this$reorderModeStat;
    return (_this$reorderModeStat = this.reorderModeState) == null ? void 0 : _this$reorderModeStat.isReorderModeToolbarVisible;
  }
  get isReorderModePending() {
    var _this$reorderModeStat2;
    return (_this$reorderModeStat2 = this.reorderModeState) == null ? void 0 : _this$reorderModeStat2.isReorderModePending;
  }
  get columns() {
    const {
      _userColumns,
      _featureColumns,
      _extendedColumns
    } = this;
    return [..._userColumns, ..._featureColumns, ..._extendedColumns];
  }
  get selectedOrderedColumnsOrAll() {
    const {
      columns,
      customColumnsState,
      columnSizesState
    } = this;
    const baseColumns = customColumnsState ? customColumnsState.selectedOrderedColumns : columns;
    return (columnSizesState == null ? void 0 : columnSizesState.mergeSizes(baseColumns)) ?? baseColumns;
  }
  _commonDynamicBiParams(query = this.collection.result.originQuery) {
    var _viewsState$views$cur, _viewsState$views, _viewsState$views2;
    const {
      collection,
      viewsState
    } = this;
    return {
      componentType: this.componentType,
      ...collection._commonDynamicBiParams(query),
      currentTab: this.getCurrentTabName(),
      ...(viewsState && {
        currentView: (_viewsState$views$cur = viewsState.views.currentView) == null ? void 0 : _viewsState$views$cur.id
      }),
      ...((viewsState == null || (_viewsState$views = viewsState.views) == null ? void 0 : _viewsState$views.currentView) && {
        isPredefined: viewsState.views.currentView.isPreset
      }),
      ...((viewsState == null || (_viewsState$views2 = viewsState.views) == null || (_viewsState$views2 = _viewsState$views2.currentView) == null ? void 0 : _viewsState$views2.filters) && {
        numFiltersInView: this._numberFiltersInView(viewsState.views.currentView)
      }),
      visibleColumnsOrder: this.selectedOrderedColumnsOrAll.map(col => col.id ?? col.title ?? col.name).join(','),
      numColumns: this.selectedOrderedColumnsOrAll.length,
      numFiltersActive: collection.query.activeFiltersCount
    };
  }
  _numberFiltersInView(view) {
    let numFiltersInView = 0;
    if (view.filters) {
      for (const filterName of Object.keys(view.filters)) {
        const filter = view.filters[filterName];
        if (filter && filter.value) {
          if (Array.isArray(filter.value)) {
            numFiltersInView += filter.value.length;
          } else if (filter.value) {
            numFiltersInView += 1;
          }
        }
      }
    }
    return numFiltersInView;
  }
  getCurrentTabName() {
    const {
      tabsFilterProps,
      collection: {
        result: {
          originQuery: query
        }
      }
    } = this;
    const tabs = tabsFilterProps && Object.entries(query.rawFilters).filter(([key]) => key === tabsFilterProps.filter.name).flatMap(([, value]) => Array.isArray(value) ? value.map(tabsFilterProps.filter.itemKey) : value);
    return tabs == null ? void 0 : tabs[0];
  }
  getPendingFilter(filter) {
    var _this$pendingQuery;
    return ((_this$pendingQuery = this.pendingQuery) == null ? void 0 : _this$pendingQuery.getApplicableFilter(filter)) ?? filter;
  }
  init({
    featuresInitializers,
    hasMultiLevelSorting,
    skipFilterListeners
  }) {
    const {
      collection,
      multi,
      initTask,
      panels,
      sidePanel,
      collectionDataExtension,
      tagsCollectionState,
      bulk,
      customColumnsState,
      viewsState,
      columnSizesState
    } = this;
    const biReporters = multi.collections.map(collection => new _bexCore.CollectionBIReporter({
      collection,
      reportBi: ev => {
        this.reportBi({
          ...ev,
          params: {
            ...collection._commonDynamicBiParams(),
            ...ev.params
          }
        });
      }
    }));

    // must call `initOptionalFeatures` before collection init because we want to allow features to customize the collection before collection.init
    const tableFeatures = featuresInitializers.filter(t => t != null).map(tableFeatInit => tableFeatInit(this));

    // should be initialized before collection.init() so the sort query will be updated before the time of the first request.
    this._initDefaultSortableColumn(hasMultiLevelSorting);
    const disposers = [collectionDataExtension == null ? void 0 : collectionDataExtension.init(), // dataExtensionState should be initialized and beforeInitialFetch promise listener registered before customColumnsState?._tableInit() because custom columns might use data extensions
    customColumnsState == null ? void 0 : customColumnsState._tableInit(), viewsState == null ? void 0 : viewsState.init(), columnSizesState == null ? void 0 : columnSizesState.init(),
    // register table feature first as they might register to the collection `beforeInitialFetch`
    ...tableFeatures.map(t => t.init()), (0, _mobx.reaction)(() => this.selectedOrderedColumnsOrAll, columns => {
      collection.query._columns.replace(columns.map(c => c.id));
    }, {
      fireImmediately: true
    }), (0, _mobx.reaction)(() => collectionDataExtension == null ? void 0 : collectionDataExtension.dataExtension.availableCustomFields, customFields => {
      this.setNewExtendedColumns(customFields ?? []);
    }), multi.init({
      skipFilterListeners
    }), ...biReporters.map(b => b.init()), panels.init(), sidePanel.init(), bulk.init(), tagsCollectionState == null ? void 0 : tagsCollectionState.init(), (0, _util.addEventListener)(collection.bulkSelect.events, 'openModal', this.bulk.modals.actionModal.modal.open), (0, _util.addEventListener)(collection.bulkSelect.events, 'closeModal', this.bulk.modals.actionModal.modal.close), (0, _util.addEventListener)(this.collection.emitter, 'resultUpdated', () => {
      this.broadcast({
        message: this.container.translate('cairo.a11y.liveRegion.resultsFound', {
          num: this.collection.result.total
        })
      });
    })];
    const startTime = performance.now();
    initTask.runOnce(async () => {
      this.toolbarBIReporter.loadStart();
      multi.initTask.runOnce();
      customColumnsState == null || customColumnsState.initTask.runOnce();
      tableFeatures.forEach(({
        initTask
      }) => {
        if (initTask) {
          initTask.runOnce();
        }
      });
      try {
        var _tagsCollectionState$, _collectionDataExtens;
        await Promise.all([multi.initTask.status.promise, tagsCollectionState == null || (_tagsCollectionState$ = tagsCollectionState.initTask.status.promise) == null ? void 0 : _tagsCollectionState$.catch(() => null), // resilience to failed request
        collectionDataExtension == null || (_collectionDataExtens = collectionDataExtension.initTask.status.promise) == null ? void 0 : _collectionDataExtens.catch(() => null), // resilience to failed request
        customColumnsState == null ? void 0 : customColumnsState.initTask.status.promise, columnSizesState == null ? void 0 : columnSizesState.initTask.status.promise, ...tableFeatures.map(t => {
          var _t$initTask;
          return (_t$initTask = t.initTask) == null ? void 0 : _t$initTask.status.promise;
        })]);
        this.toolbarBIReporter.loadEnd(startTime);
      } catch (e) {
        throw e;
      }
    });
    return () => {
      disposers.forEach(d => d == null ? void 0 : d());
    };
  }
  setFilterTagsPropsIfChanged(filtersProps) {
    if (this.filtersProps !== filtersProps) {
      this.filtersProps = filtersProps;
    }
  }
  setNewColumns(tableColumns) {
    this._userColumns = (0, _simplifyColumns.simplifyColumns)(tableColumns);
  }
  addFeatureColumn(featureColumn) {
    this._featureColumns.push((0, _simplifyColumns.simplifyColumn)(featureColumn));
    this._adjustSelectedColumns();
  }
  setNewExtendedColumns(fields = [], {
    defaultHidden = false
  } = {}) {
    var _this$collectionDataE2;
    if (!((_this$collectionDataE2 = this.collectionDataExtension) != null && _this$collectionDataE2.dataExtension.initTask.status.isSuccess)) {
      return;
    }
    this._extendedColumns = (0, _simplifyExtendedColumns.simplifyExtendedColumns)({
      fields,
      toExtendedFields: this.collection.toExtendedFields,
      defaultHidden
    });
    this._adjustSelectedColumns();
  }
  broadcast(params) {
    var _this$liveRegionRef$c;
    (_this$liveRegionRef$c = this.liveRegionRef.current) == null || _this$liveRegionRef$c.broadcast(params);
  }
  setToolbarFiltersStateInitialized(value) {
    this.toolbarFiltersStateInitialized = value;
  }
  updateColumnWidth(columnId, width) {
    var _this$columnSizesStat;
    (_this$columnSizesStat = this.columnSizesState) == null || _this$columnSizesStat.updateColumnWidth(columnId, width);
  }
  _initDefaultSortableColumn(hasMultiLevelSorting = false) {
    const {
      columns,
      collection: {
        query
      }
    } = this;
    const defaultSortableColumns = columns.filter(col => col.sortable === true && col.id != null && col.defaultSortOrder != null);
    if (defaultSortableColumns.length && !query.sort.value.length) {
      const sortQuery = defaultSortableColumns.map(column => ({
        field: column.id,
        direction: column.defaultSortOrder
      }));
      query.sort.setSortQuery(hasMultiLevelSorting ? sortQuery : sortQuery.slice(0, 1));
    }
  }
  _adjustSortWithNewColumns(tableColumns) {
    const {
      collection: {
        query
      }
    } = this;
    const tableColumnsIds = new Set(tableColumns.map(column => column.id));
    query.sort.value.filter(({
      field
    }) => !tableColumnsIds.has(field)).forEach(s => {
      query.sort.value.remove(s);
    });
    query.sort.events.emit('change');
    this.collection.scheduleSort({
      clearResult: true
    });
  }
  openFiltersPanel() {
    this.panels.openSidePanel('filters');
  }
  _onSelectAllCheckboxClick() {}
  get activeFiltersEntries() {
    return Array.from(this.multi.collections.flatMap(({
      query
    }) => query.activeFiltersEntries.filter(([_, filter]) => filter !== query.search)).reduce((map, entry) => map.set(entry[0], entry), new Map()).values());
  }
  getPageFeaturedActions() {
    const {
      collectionDataExtension,
      tagsCollectionState
    } = this;
    return [collectionDataExtension, tagsCollectionState].filter(e => e != null).filter(e => {
      var _e$props;
      return !((_e$props = e.props) != null && _e$props.disableDefaultPageAction);
    }).flatMap(e => e.featuredPageActions);
  }
}
exports.ToolbarCollectionState = ToolbarCollectionState;
//# sourceMappingURL=ToolbarCollectionState.js.map