import { cloneDeep as W } from "es-toolkit";
import { resolveComponent as d, openBlock as r, createElementBlock as o, normalizeClass as a, createElementVNode as u, createVNode as S, toDisplayString as k, createCommentVNode as n, createBlock as h, withCtx as m, createTextVNode as T, renderSlot as f, TransitionGroup as F, resolveDirective as O, withDirectives as E, withKeys as Y, normalizeStyle as Z, Fragment as q, renderList as J, mergeProps as X, resolveDynamicComponent as Q, computed as $ } from "vue";
import ee from "./useSearch.js";
import { CSS_VARS as L, LLLV_CHANGE_TRIGGERS as _ } from "./constants.js";
import V from "./directives/sticky.js";
import { t as p } from "./locale.js";
import { persistentStorage as A } from "./storage.js";
import { getCssVar as D, sortItems as te, filterItems as se } from "./utils/helpers.js";
import le from "./Badge.js";
import v from "./Button.js";
import R from "./Checkbox.js";
import ie from "./Dropdown.js";
import { _ as N } from "./Expand.vue_vue_type_script_setup_true_lang-CSzt6UW3.js";
import re from "./Filters.js";
import B from "./Icon.js";
import ae from "./Input.js";
import ne from "./Paginate.js";
import { _ as C } from "./_plugin-vue_export-helper-CHgC5LLL.js";
import oe from "./EmptyState.js";
import ce from "./Loading.js";
const de = "_checkbox_OmglW", he = "_actions_uvytQ", ue = {
  "select-bar": "_select-bar_Jmuxh",
  checkbox: de,
  actions: he
}, me = {
  name: "bulk-actions",
  components: {
    "ll-button": v,
    "ll-checkbox": R
  },
  props: {
    allowSelectAll: Boolean,
    isAllPageChecked: Boolean,
    isSomePageChecked: Boolean,
    hideBulkActionOptions: Boolean,
    hideNumberOfTotalSelected: Boolean,
    totalCount: {
      type: Number,
      default: 0
    },
    totalSelectedCount: {
      type: Number,
      default: 0
    }
  },
  emits: ["change:select-current", "change:select-all", "change:clear-selected"],
  data: function() {
    return {
      selectAllText: p("ll.listView.selectAll")
    };
  },
  computed: {
    clearSelectedText() {
      return this.allowSelectAll ? p("ll.listView.deselectAllCount", { count: this.totalCount }) : p("ll.listView.clearSelection");
    },
    showSelectAll() {
      return [this.totalSelectedCount !== this.totalCount, this.allowSelectAll].every(Boolean);
    },
    numberOfTotalSelectedText() {
      return p("ll.listView.numberOfTotalSelected", {
        num: this.totalSelectedCount,
        total: this.totalCount
      });
    },
    selectAllCountText() {
      return p("ll.listView.selectAllCount", { count: this.totalCount });
    },
    numItemsSelectedText() {
      return p("ll.listView.numItemsSelected", {
        totalSelectedCount: this.totalSelectedCount,
        totalCount: this.totalCount
      });
    }
  },
  methods: {
    onSelectPage(e) {
      this.$emit("change:select-current", e);
    },
    selectAll() {
      this.$emit("change:select-all");
    },
    clearSelected() {
      this.$emit("change:clear-selected");
    }
  }
}, ge = {
  key: 0,
  class: "flex flex-1 items-center justify-between"
}, fe = {
  key: 0,
  class: "text-xs"
}, Se = {
  key: 1,
  class: "ml-1.5 lg:hidden"
};
function ye(e, l, s, b, i, t) {
  const c = d("ll-checkbox"), g = d("ll-button");
  return r(), o("div", {
    class: a(["lg:flex", [
      e.$style["select-bar"],
      {
        "lg:hidden": s.hideBulkActionOptions
      },
      "p-3"
    ]])
  }, [
    u("div", {
      class: a(["flex items-center", {
        "justify-between": !s.hideBulkActionOptions
      }])
    }, [
      S(c, {
        "data-test": "checkbox|bulk-actions",
        class: a([e.$style.checkbox, "m-0 lg:hidden"]),
        checked: s.isSomePageChecked && !!s.totalCount,
        indeterminate: s.isSomePageChecked && !s.isAllPageChecked,
        label: s.totalSelectedCount ? "" : e.selectAllText,
        "onUpdate:checked": t.onSelectPage
      }, null, 8, ["class", "checked", "indeterminate", "label", "onUpdate:checked"]),
      s.totalSelectedCount && !s.hideBulkActionOptions ? (r(), o("div", ge, [
        s.hideNumberOfTotalSelected ? n("", !0) : (r(), o("div", fe, k(t.numberOfTotalSelectedText), 1)),
        u("div", {
          class: a({ "ml-3": !s.hideNumberOfTotalSelected })
        }, [
          t.showSelectAll ? (r(), h(g, {
            key: 0,
            inline: "",
            onClick: t.selectAll
          }, {
            default: m(() => [
              T(k(t.selectAllCountText), 1)
            ]),
            _: 1
          }, 8, ["onClick"])) : (r(), h(g, {
            key: 1,
            inline: "",
            onClick: t.clearSelected
          }, {
            default: m(() => [
              T(k(t.clearSelectedText), 1)
            ]),
            _: 1
          }, 8, ["onClick"]))
        ], 2)
      ])) : s.hideBulkActionOptions && s.totalSelectedCount ? (r(), o("div", Se, [
        u("h4", null, k(t.numItemsSelectedText), 1)
      ])) : n("", !0)
    ], 2),
    s.totalSelectedCount && !s.hideBulkActionOptions ? (r(), o("div", {
      key: 0,
      class: a(e.$style.actions)
    }, [
      f(e.$slots, "bulk-actions-content")
    ], 2)) : n("", !0)
  ], 2);
}
const pe = {
  $style: ue
}, be = /* @__PURE__ */ C(me, [["render", ye], ["__cssModules", pe]]), ke = {
  name: "loading-manager",
  components: {
    EmptyState: oe,
    Loading: ce
  },
  props: {
    emptyStateText: {
      type: String,
      default: ""
    },
    loading: Boolean,
    results: {
      type: Array,
      default: () => []
    }
  }
};
function _e(e, l, s, b, i, t) {
  const c = d("Loading"), g = d("EmptyState");
  return s.loading ? (r(), h(c, {
    key: 0,
    class: "bg-white"
  })) : s.results.length ? (r(), h(F, {
    key: 1,
    name: "slide-y",
    tag: "ul"
  }, {
    default: m(() => [
      f(e.$slots, "default")
    ]),
    _: 3
  })) : (r(), h(g, {
    key: 2,
    class: "max-w-full bg-white",
    text: s.emptyStateText
  }, null, 8, ["text"]));
}
const Ce = /* @__PURE__ */ C(ke, [["render", _e]]), we = {
  "main-header": "_main-header_BtiRR",
  "expanded-content-header": "_expanded-content-header_muYra",
  "expanded-content-header-grid": "_expanded-content-header-grid_Med-X",
  "expansion-toggle-button": "_expansion-toggle-button_x5ijM",
  "list-group": "_list-group_CDLZB",
  "expanded-content-list-items-wrapper": "_expanded-content-list-items-wrapper_a3u05"
}, Te = {
  name: "list-group",
  components: {
    Expand: N,
    "ll-button": v,
    Icon: B
  },
  directives: {
    sticky: V
  },
  props: {
    /**
     * Disables the gutters between adjacent ListGroup components.
     */
    disableExternalGutters: {
      type: Boolean,
      default: !1
    },
    /**
     * Allows the list items to be collapsed
     */
    isCollapsible: {
      type: Boolean,
      default: !1
    },
    /**
     * Allows the expanded content to be collapsed by default.
     * Note: has no effect unless the `isCollapsible` prop is `true`.
     */
    isCollapsedByDefault: {
      type: Boolean,
      default: !1
    }
  },
  data() {
    const e = !this.isCollapsible || !this.isCollapsedByDefault;
    return {
      isExpanded: e,
      isDoneExpanding: e
    };
  },
  computed: {
    headerOffset() {
      return parseFloat(D(L.TOP_HEADER_HEIGHT));
    }
  },
  methods: {
    toggleExpand() {
      this.isCollapsible && (this.isExpanded = !this.isExpanded, this.isExpanded || (this.isDoneExpanding = !1));
    },
    onHeaderClick(e) {
      this.$refs.actionsContainer.contains(e.target) || this.toggleExpand();
    }
  }
}, Ie = { class: "flex-auto" }, xe = { ref: "actionsContainer" }, ve = { class: "relative w-full lg:shadow" };
function Be(e, l, s, b, i, t) {
  const c = d("Icon"), g = d("ll-button"), I = d("Expand"), x = O("sticky");
  return r(), o("div", {
    class: a([
      e.$style["list-group"],
      {
        [e.$style["disable-external-gutters"]]: s.disableExternalGutters,
        [e.$style["is-collapsed"]]: !i.isExpanded
      }
    ])
  }, [
    u("header", {
      class: a(["flex items-center", [e.$style["main-header"], { "cursor-pointer": s.isCollapsible }]]),
      onClick: l[0] || (l[0] = (...w) => t.onHeaderClick && t.onHeaderClick(...w))
    }, [
      s.isCollapsible ? (r(), h(g, {
        key: 0,
        class: a(["mr-1.5 text-ice-900", e.$style["expansion-toggle-button"]]),
        icon: ""
      }, {
        default: m(() => [
          S(c, {
            class: a([i.isExpanded ? "rotate-270" : "rotate-180"]),
            name: "chevron-left"
          }, null, 8, ["class"])
        ]),
        _: 1
      }, 8, ["class"])) : n("", !0),
      u("div", Ie, [
        f(e.$slots, "title")
      ]),
      u("div", xe, [
        f(e.$slots, "actions")
      ], 512)
    ], 2),
    S(I, {
      "is-expanded": i.isExpanded,
      onAfterExpand: l[1] || (l[1] = (w) => i.isDoneExpanding = !0)
    }, {
      default: m(() => [
        u("div", ve, [
          e.$slots["expanded-content-list-header"] ? E((r(), o("header", {
            key: 0,
            class: a(e.$style["expanded-content-header"])
          }, [
            u("div", {
              class: a(["ll-grid flex-1", e.$style["expanded-content-header-grid"]])
            }, [
              f(e.$slots, "expanded-content-list-header")
            ], 2)
          ], 2)), [
            [x, i.isExpanded && i.isDoneExpanding ? t.headerOffset : 0]
          ]) : n("", !0),
          u("div", {
            class: a(e.$style["expanded-content-list-items-wrapper"])
          }, [
            S(F, {
              name: "fade",
              mode: "out-in"
            }, {
              default: m(() => [
                f(e.$slots, "expanded-content-list-items")
              ]),
              _: 3
            })
          ], 2)
        ])
      ]),
      _: 3
    }, 8, ["is-expanded"])
  ], 2);
}
const Ae = {
  $style: we
}, mt = /* @__PURE__ */ C(Te, [["render", Be], ["__cssModules", Ae]]), Pe = "_caret_8aYcq", Fe = {
  "caret-up": "_caret-up__BL13",
  "caret-down": "_caret-down_rIpzM",
  caret: Pe
}, Oe = {
  name: "list-header",
  components: {
    "ll-icon": B
  },
  props: {
    /**
     * keys to be sorted for the column
     * the first key should be the default sort value
     */
    sortKeys: {
      type: Array,
      required: !0,
      validator: (e) => e.length === 2
    },
    listViewRef: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      isAscending: null
    };
  },
  computed: {
    listViewInstance() {
      return this.listViewRef || this.$parent;
    },
    /**
     * Is the column currently sorted
     */
    isSorted() {
      return this.sortKeys.includes(this.listViewInstance.sortTerm);
    },
    /**
     * Show the top icon if it's not sorted or if the current sortTerm matches
     */
    showCaretUp() {
      return this.isAscending === null || this.sortKeys[0] === this.listViewInstance.sortTerm;
    },
    /**
     * Show the bottom icon if it's not sorted or if the current sortTerm matches
     */
    showCaretDown() {
      return this.isAscending === null || this.sortKeys[1] === this.listViewInstance.sortTerm;
    }
  },
  watch: {
    isSorted: {
      handler(e) {
        this.isAscending = e ? !0 : null;
      },
      immediate: !0
    }
  },
  methods: {
    /**
     * Sorts the column by the sort field
     */
    sort() {
      this.listViewInstance.onSort(this.sortKeys[this.isAscending ? 1 : 0]), this.isAscending = !this.isAscending;
    }
  }
};
function Ee(e, l, s, b, i, t) {
  const c = d("ll-icon");
  return r(), o("div", {
    class: a(["cursor-pointer", { "bg-blue-100": t.isSorted }]),
    onClick: l[0] || (l[0] = (...g) => t.sort && t.sort(...g))
  }, [
    f(e.$slots, "default"),
    u("div", {
      class: a(["relative h-4 w-3 text-ice-700", { "is-active-sort": t.isSorted }])
    }, [
      t.showCaretUp ? (r(), h(c, {
        key: 0,
        name: "caret-up",
        class: a(["absolute", [e.$style.caret, e.$style["caret-up"]]]),
        size: "dense"
      }, null, 8, ["class"])) : n("", !0),
      t.showCaretDown ? (r(), h(c, {
        key: 1,
        name: "caret-down",
        class: a(["absolute", [e.$style.caret, e.$style["caret-down"]]]),
        size: "dense"
      }, null, 8, ["class"])) : n("", !0)
    ], 2)
  ], 2);
}
const Le = {
  $style: Fe
}, gt = /* @__PURE__ */ C(Oe, [["render", Ee], ["__cssModules", Le]]), Ve = "_header_bY8r8", De = "_separator_cTiXf", Re = "_dropdown_-yK9K", Ne = {
  "list-items": "_list-items_Ou6dx",
  "legacy-box": "_legacy-box_8grbO",
  header: Ve,
  "header-grid-container": "_header-grid-container_MoKCn",
  "header-grid": "_header-grid_3l2oK",
  "search-input": "_search-input_gSm9G",
  "clear-button": "_clear-button_cFe75",
  "search-button": "_search-button_omFxB",
  "total-sort": "_total-sort_VZm5G",
  "filter-toggle-btn": "_filter-toggle-btn_nKNDZ",
  "filter-toggle-btn-with-hint-text": "_filter-toggle-btn-with-hint-text_rZoiz",
  "filters-expand": "_filters-expand_3SnRt",
  "filters-wrapper": "_filters-wrapper_Ygfi0",
  separator: De,
  "filters-half-width": "_filters-half-width_HDNjK",
  dropdown: Re,
  "sort-option": "_sort-option_y4sWV",
  "select-all": "_select-all_JY2Rw"
}, P = {
  isSearchable: !0,
  placeholder: "Search",
  searchBy: ["name"]
}, ze = {
  name: "ll-list-view",
  components: {
    BulkActions: be,
    Filters: re,
    Paginate: ne,
    LoadingManager: Ce,
    Badge: le,
    Button: v,
    Icon: B,
    Dropdown: ie,
    Expand: N,
    Checkbox: R,
    Input: ae
  },
  directives: {
    sticky: V
  },
  inject: {
    trackSearch: { default: () => () => {
    } },
    trackFilters: { default: () => () => {
    } },
    trackSort: { default: () => () => {
    } },
    trackResults: { default: () => () => {
    } }
  },
  props: {
    /**
     * Hide the '{number} of {total} selected' text for bulk actions
     */
    hideNumberOfTotalSelected: {
      type: Boolean,
      default: !1
    },
    /**
     * Hide the Select All checkbox for bulk actions
     */
    hideSelectAll: {
      type: Boolean,
      default: !1
    },
    /**
     * Text to render in EmptyState component if there are no results
     */
    emptyStateText: {
      type: String,
      default: ""
    },
    filterSchema: {
      type: Array,
      default: () => []
    },
    /**
     * Make search fuzzy. Only for client side search.
     */
    fuzzySearch: {
      type: Boolean,
      default: !1
    },
    hideTotal: Boolean,
    initialPage: {
      type: Number,
      default: void 0
    },
    /**
     * Can items on the page be selected for bulk actions
     */
    isSelectable: Boolean,
    /**
     * For loading data already paginated, filtered (including search), and sorted from a backend.
     * Defining this prop will disable the built-in search, filtering, sorting and pagination.
     * You will instead need to use the available events (`@change`, and `@change:` prefixed)
     * to know when to request new pages from your backend.
     * This requires providing `totalItemCount`.
     * Use the loading prop to indicate when data is being loaded.
     */
    isServerSide: Boolean,
    /**
     * The data for each row. Used in this file as this.internalItems (a copy) to allow mutation;
     */
    items: {
      type: Array,
      default: () => []
    },
    /**
     * Default field to track selected items by
     */
    itemTrackBy: {
      type: String,
      default: "id"
    },
    loading: Boolean,
    // Number of items to display per page
    pageSize: {
      type: Number,
      default: 50
    },
    searchSchema: {
      type: Object,
      default: () => ({})
    },
    // Provide an optional custom 'Sort by' label
    sortLabel: {
      type: String,
      default: () => p("ll.listView.sortBy")
    },
    sortOnLoad: Boolean,
    sorts: {
      type: Object,
      default: () => ({})
    },
    /**
     * Total number of unpaginated results
     * Required when `isServerSide` is `true`
     */
    totalItemCount: {
      type: Number,
      default: void 0
    },
    /**
     * Validation schema function that returns an object
     */
    validationSchema: {
      type: Function,
      default: () => () => {
      }
    },
    /**
     * Whether to disable the sticky filters
     * if disabled, the following will happen
     * 1. pre-selected value(s) can be added to
     * the filter component's attributes to overwrite the sticky filters
     * 2. users will not have sticky filters on the page
     */
    disablePersistency: Boolean,
    /**
     * Whether to disable the ability of saving 'show-filters'
     * in local storage
     */
    disableShowFilter: Boolean,
    /**
     * Whether to disable the stickiness of the header.
     * Default is false. When true, neither the list headers nor
     * the bulk actions (when applicable) will be sticky.
     */
    disableStickyHeader: Boolean,
    /**
     * Whether to expand the filters section by default on load.
     */
    showFiltersOnLoad: Boolean,
    /**
     * Do not use the LoadingManager, and instead render the default slot as passed
     */
    disableLoader: {
      type: Boolean,
      default: !1
    },
    /**
     * Override the header offset used to position the sticky header
     */
    stickyHeaderOffset: {
      type: Number,
      default: null
    },
    /**
     * Prevent bulk actions dropdown from rendering
     */
    hideBulkActionOptions: {
      type: Boolean,
      default: !1
    },
    /**
     * If initial search term is provided, the list will be filtered on load.
     */
    initialSearchTerm: {
      type: String,
      default: ""
    },
    /**
     * Function that determines whether the item checkbox is disabled or not (default: false)
     */
    isItemDisabled: {
      type: Function,
      default: () => !1
    }
  },
  emits: [
    "change",
    "change:filter",
    "change:page",
    "change:search",
    "change:sort",
    "change:reset",
    "filters-toggle-click",
    "select-all",
    "deselect-all",
    "update-filters",
    "updateResults"
  ],
  data() {
    var e;
    return {
      internalItems: [],
      currentPage: this.initialPage || 1,
      // TODO: fetch from query params
      previousPage: null,
      sortOptionsWidth: 0,
      filters: {},
      filterText: p("ll.filter"),
      searchFor: () => {
      },
      // initialized in the watch handler for internalItems
      searchTerm: this.initialSearchTerm,
      searchText: p("ll.search"),
      sortTerm: "",
      isLoadingSearchSchemaAction: !1,
      isShowingFilters: !!((e = this.filterSchema) != null && e.length && (this.showFiltersOnLoad || A.get("show-filters"))),
      isFiltering: !1,
      results: [],
      selectedItems: []
    };
  },
  computed: {
    /**
     * Returns true if any of its list items are truthy; otherwise returns false.
     * @returns {boolean}
     */
    isLoading() {
      return [this.loading, this.isLoadingSearchSchemaAction, this.isFiltering].some(Boolean);
    },
    totalCount() {
      return this.isServerSide ? this.totalItemCount : this.results.length;
    },
    /**
     * Helps determine if the list is filtered or not when there is an incomplete
     * result list, such as when isServerSide is true.
     */
    isFiltered() {
      return !!(this.numberOfFilters || this.searchTerm);
    },
    /**
     * Merges the searchSchema with the default value since all attributes are optional
     */
    internalSearchSchema() {
      return {
        ...P,
        searchBy: !this.searchSchema.isSearchable && P.searchBy,
        ...this.searchSchema
      };
    },
    /**
     * Start of page
     */
    startIndex() {
      return this.pageSize * (this.currentPage - 1);
    },
    /**
     * End of page
     */
    endIndex() {
      return this.startIndex + this.pageSize;
    },
    /**
     * Slices the results set into a paginated segment.
     * @returns One page in the paginated set of results
     */
    paginated() {
      let e;
      if (this.isServerSide)
        e = this.results;
      else {
        const { endIndex: l, totalCount: s, results: b, startIndex: i } = this;
        e = b.slice(i, Math.min(l, s));
      }
      return this.$emit("updateResults", e), e;
    },
    /**
     * Displays a visual indication for the number of results, or "working" if the
     * results are being determined.
     */
    total() {
      const e = this.pageSize * (this.currentPage - 1), l = this.paginated.length ? `${e + 1} - ${e + this.paginated.length}` : 0;
      return this.isLoading ? p("ll.listView.calculating") : p("ll.listView.totalResults", { num: String(l), total: String(this.totalCount) });
    },
    /**
     * Determines if both #list-header and #list-items slots are used.
     * @returns {boolean}
     */
    useDefinedSlots() {
      return !!this.$slots["list-header"] && !!this.$slots["list-items"];
    },
    /**
     * Don't show total count if list items are selected and total is not hidden
     */
    shouldShowTotal() {
      return !this.totalSelectedCount && !this.hideTotal;
    },
    /**
     * Returns a list of the selected items' track by field
     */
    selectedItemIds() {
      return this.selectedItems.map((e) => e[this.itemTrackBy]);
    },
    /**
     * Returns a list of the paginated items' track by field
     */
    paginatedIds() {
      return this.paginated.map((e) => e[this.itemTrackBy]);
    },
    isAllPageChecked() {
      return this.isServerSide ? this.totalCount > 0 && this.totalCount === this.selectedItemIds.length : this.totalCount > 0 && this.paginatedIds.every((e) => this.selectedItemIds.includes(e));
    },
    isSomePageChecked() {
      return this.isServerSide ? this.totalCount > 0 && this.selectedItemIds.length > 0 : this.totalCount > 0 && this.paginatedIds.some((e) => this.selectedItemIds.includes(e));
    },
    numberOfFilters() {
      return Object.keys(this.filters).reduce((e, l) => {
        const s = this.filters[l].filterBy, b = typeof s[0] == "boolean", i = this.filters[l].filterType === "ll-checkbox", t = !this.filters[l].filterType.length, c = this.filters[l].filterType === "ll-input-options" && s[0] === "";
        return t || c ? e : b || typeof s[0] == "string" ? e + (s[0] || !i ? 1 : 0) : e + (s.length || 0);
      }, 0);
    },
    isSelectBarVisible() {
      return !!this.totalSelectedCount;
    },
    showPrimaryControls() {
      return this.internalSearchSchema.isSearchable || this.filterSchema.length;
    },
    showSecondaryControls() {
      return !!this.$slots["secondary-controls"];
    },
    isSortable() {
      return Object.keys(this.sorts).length > 0;
    },
    totalSelectedCount() {
      return this.selectedItems.length;
    },
    headerOffset() {
      return this.disableStickyHeader ? null : this.stickyHeaderOffset ?? parseFloat(D(L.TOP_HEADER_HEIGHT));
    }
  },
  watch: {
    isShowingFilters(e) {
      this.disableShowFilter || A.set("show-filters", e);
    },
    items: {
      handler() {
        this.internalItems = W(this.items);
      },
      immediate: !0,
      deep: !0
    },
    internalItems: {
      handler() {
        if (this.isServerSide) {
          this.results = this.internalItems, this.trackResults({
            page: this.currentPage,
            results: this.results,
            search: this.searchTerm
          });
          return;
        }
        const { searchFor: e } = ee({
          items: $(() => this.internalItems),
          fieldNames: this.internalSearchSchema.searchBy.length ? this.internalSearchSchema.searchBy : [this.displayBy],
          trackBy: this.itemTrackBy
        });
        this.searchFor = (l) => e(l, { fuzzy: this.fuzzySearch }), this.processResults();
      },
      immediate: !0
    },
    sortTerm() {
      this.isServerSide || this.processResults();
    },
    sorts: {
      handler(e) {
        const l = Object.keys(e);
        this.sortTerm = this.sortOnLoad && l.length ? l[0] : "";
      },
      immediate: !0
    }
  },
  created() {
    if (this.isServerSide) {
      if (this.totalItemCount === void 0)
        throw new Error("`totalItemCount` is required when `isServerSide` is `true`.");
      return;
    }
    if (this.searchSchema.action && this.internalItems.length)
      throw new Error("You must pass either `action` or `items`, not both.");
    this.searchTerm && this.onSearch();
  },
  methods: {
    /**
     * Processes the results with searchFor, filterItems, and/or sortItems.
     * Skipped when isServerSide is true because results are pre-processed.
     * @returns {Promise<void>}
     */
    async processResults() {
      if (this.searchSchema.action) {
        this.isLoadingSearchSchemaAction = !0;
        let e;
        try {
          e = await this.searchSchema.action({ search: this.searchTerm });
        } finally {
          this.isLoadingSearchSchemaAction = !1;
        }
        this.results = this.sortItems(this.filterItems((e == null ? void 0 : e.results) || []));
      } else
        this.results = this.sortItems(this.filterItems(this.searchFor(this.searchTerm)));
      this.trackResults({
        page: this.currentPage,
        results: this.results,
        search: this.searchTerm
      });
    },
    /**
     * Filters the list of `items` based on options selected in the `filters` object
     * @param {array} items A list of items to filter.
     * @returns list of items filtered by the applied filters
     */
    filterItems(e) {
      return se(e, this.filters);
    },
    /**
     * Sorts a list of items based on options selected in the `sorts` object
     * @param {array} items A list of items to sort.
     * @returns list of items sorted according to the sort term.
     */
    sortItems(e) {
      return this.sortTerm ? te(e, this.sorts[this.sortTerm]) : e;
    },
    change({ trigger: e = "" } = {}) {
      const { currentPage: l, filters: s, isFiltered: b, pageSize: i, searchTerm: t, sortTerm: c } = this, g = {
        filters: s,
        isFiltered: b,
        page: {
          number: l,
          previousNumber: this.previousPage,
          size: i
        },
        search: t,
        sort: c,
        trigger: e
      };
      this.$emit("change", g);
    },
    /**
     * Clear search term and reset results to their initial state
     */
    async clearSearchTerm() {
      var e, l;
      this.searchTerm = "", await ((l = (e = this.$attrs).onSearchTermClear) == null ? void 0 : l.call(e)), this.onSearch();
    },
    /**
     * Resets the results to their initial state on page load
     */
    reset() {
      if (this.$emit("change:reset"), this.searchTerm = "", this.setPage({ pageNumber: 1 }), this.isServerSide) {
        this.change({ trigger: _.RESET });
        return;
      }
      this.processResults();
    },
    onSearchTermChange() {
      var e, l;
      (l = (e = this.$attrs).onSearchTermChange) == null || l.call(e, this.searchTerm);
    },
    /**
     * Event handler for when the user:
     *  - clicks the Search button
     *  - presses the enter key while focused on the search input
     * Calls a method in Filters that triggers `this.onFilter`. This is necessary
     * in order to persist the filters in local storage, which is handled internally
     * by Filters.
     */
    onSearch() {
      this.$refs.llFilters.applyFilters({ trigger: _.SEARCH });
    },
    /**
     * Event handler for when the user:
     *  - clicks the Apply button
     *  - clicks the Search button (from `this.onSearch`)
     *  - presses the enter key while focused on the search input (from `this.onSearch`)
     * @see: SELL-350
     * @param {object} [options] - optional parameters
     * @param {string} [options.trigger] - what caused the changes
     * @returns {Promise<void>}
     */
    async onFilter({ trigger: e = _.APPLY } = {}) {
      if (this.setPage({ pageNumber: 1 }), this.change({ trigger: e }), this.trackSearch(this.searchTerm), this.trackFilters(this.filters), this.selectedItems = [], !this.isServerSide) {
        try {
          this.isFiltering = !0, await this.processResults({ trigger: e });
        } finally {
          this.isFiltering = !1;
        }
        this.$emit("change:search", this.searchTerm), this.$emit("change:filter", this.filters), this.$emit("update-filters", this.filters), this.clearSelected();
      }
    },
    onFiltersToggleClick() {
      this.isShowingFilters = !this.isShowingFilters, this.$emit("filters-toggle-click", {
        isShowingFilters: this.isShowingFilters
      });
    },
    /**
     * Extend the dropdown list so it does not shift when
     * the options drawer is open
     */
    onSortToggle() {
      this.$nextTick(() => {
        this.sortOptionsWidth = `${this.$refs.sortOptions.clientWidth + 36}px`;
      });
    },
    /**
     * Executes any side-effects when the sort `term` is changed
     * Always fires `change` automatically.
     * @param {string} term The updated sort term
     */
    onSort(e) {
      e !== this.sortTerm && (this.sortTerm = e, this.$emit("change:sort", e), this.trackSort(e), this.clearSelected(), this.setPage({ pageNumber: 1 }), this.change({ trigger: _.SORT }));
    },
    /**
     * Sets current page for the Paginator.
     * @param {Object} data
     * @param {number} data.pageNumber - the page number
     * @param {boolean} data.forceChange - flag to force the change
     */
    setPage({ pageNumber: e, forceChange: l = !1 } = {}) {
      this.previousPage = this.currentPage, this.currentPage = e, this.isServerSide || this.$emit("change:page", e), l && this.change({ trigger: _.PAGE });
    },
    /**
     * Set the scroll position to the top of the list view.
     */
    scrollToTop() {
      this.$refs.scrollTarget && this.$refs.scrollTarget.scrollIntoView({ behavior: "smooth", block: "center" });
    },
    onPaginateSetPage(e) {
      this.setPage({ pageNumber: e, forceChange: !0 }), this.scrollToTop();
    },
    /**
     * Selects or deselects all items on a page
     */
    onSelectPage(e) {
      if (this.$emit("select-all", e), e) {
        const l = Array.from(/* @__PURE__ */ new Set([...this.selectedItems, ...this.paginated]));
        this.selectedItems = this.selectItems(l);
      } else
        this.selectedItems = this.selectedItems.filter((l) => !this.paginatedIds.includes(l[this.itemTrackBy]));
    },
    selectAll() {
      this.selectedItems = this.selectItems(this.results);
    },
    /**
     * Selects one item
     */
    onSelectItem({ item: e, value: l }) {
      this.isItemDisabled(e) || (l ? this.selectedItems.push(e) : this.selectedItems = this.selectedItems.filter(
        (s) => s[this.itemTrackBy] !== e[this.itemTrackBy]
      ));
    },
    /**
     * Clears current selected items
     */
    clearSelected() {
      this.$emit("deselect-all"), this.selectedItems = [];
    },
    selectItems(e) {
      return e.reduce((l, s) => this.isItemDisabled(s) ? l : [...l, s], []);
    }
  }
}, He = { class: "ll-grid grid-cols-4 md:grid-cols-8 lg:grid-cols-12" }, Me = ["disabled"], je = { class: "button-grid col-span-1 items-end justify-end md:col-span-6 lg:col-span-3" }, Ke = {
  key: 0,
  class: "text-xs"
};
function Ge(e, l, s, b, i, t) {
  const c = d("Icon"), g = d("Button"), I = d("Input"), x = d("Badge"), w = d("Filters"), z = d("Expand"), H = d("Dropdown"), M = d("Checkbox"), j = d("BulkActions"), K = d("Paginate"), G = O("sticky");
  return r(), o("div", null, [
    t.showPrimaryControls || t.showSecondaryControls ? (r(), o("div", {
      key: 0,
      ref: "scrollTarget",
      class: a(["mb-6", { "ll-grid": t.showPrimaryControls && t.showSecondaryControls }])
    }, [
      t.showPrimaryControls ? (r(), o("div", {
        key: 0,
        class: a(["controls", [e.$style["legacy-box"], { "col-span-12 lg:col-span-6": t.showSecondaryControls }]]),
        "data-test": "filters|controls"
      }, [
        u("div", He, [
          t.internalSearchSchema.isSearchable ? (r(), h(I, {
            key: 0,
            ref: "search-input",
            modelValue: i.searchTerm,
            "onUpdate:modelValue": l[1] || (l[1] = (y) => i.searchTerm = y),
            class: a(["col-span-3 md:col-span-6 lg:col-span-4", [
              e.$style["search-input"],
              {
                "lg:col-span-8": t.showSecondaryControls,
                "col-span-4 md:col-span-8 lg:col-span-6": !s.filterSchema.length
              }
            ]]),
            "data-test": "input|search-input",
            "hint-text": t.internalSearchSchema.hintText,
            label: i.searchText,
            placeholder: t.internalSearchSchema.placeholder,
            onKeyup: l[2] || (l[2] = Y((y) => !t.isLoading && t.onSearch(), ["enter"])),
            onChange: t.onSearchTermChange
          }, {
            append: m(() => [
              i.searchTerm ? (r(), o("button", {
                key: 0,
                "data-test": "button|clear-search",
                class: a(e.$style["clear-button"]),
                disabled: t.isLoading,
                onClick: l[0] || (l[0] = (...y) => t.clearSearchTerm && t.clearSearchTerm(...y))
              }, [
                S(c, { name: "close" })
              ], 10, Me)) : n("", !0),
              S(g, {
                "data-test": "button|search-button",
                disabled: t.isLoading,
                class: a(e.$style["search-button"]),
                onClick: t.onSearch
              }, {
                default: m(() => [
                  S(c, {
                    class: a({ "animate-spin text-teal-500": i.isFiltering }),
                    name: i.isFiltering ? "working" : "search"
                  }, null, 8, ["class", "name"])
                ]),
                _: 1
              }, 8, ["disabled", "class", "onClick"])
            ]),
            _: 1
          }, 8, ["modelValue", "class", "hint-text", "label", "placeholder", "onChange"])) : n("", !0),
          s.filterSchema.length ? (r(), o("div", {
            key: 1,
            class: a(["col-span-1 flex items-end md:col-span-2 lg:col-span-1", [
              e.$style["filter-toggle-btn"],
              { [e.$style["filter-toggle-btn-with-hint-text"]]: !!t.internalSearchSchema.hintText }
            ]])
          }, [
            S(x, {
              class: "w-full lg:w-auto",
              content: t.numberOfFilters
            }, {
              default: m(() => [
                S(g, {
                  secondary: "",
                  class: "relative w-full min-w-auto",
                  color: "blue",
                  "data-test": "button|toggle-filters",
                  disabled: i.isFiltering,
                  onClick: t.onFiltersToggleClick
                }, {
                  default: m(() => [
                    i.isFiltering ? (r(), h(c, {
                      key: 0,
                      name: "working",
                      class: a([{ "animate-spin": i.isFiltering }, i.isShowingFilters ? "text-teal-500" : "text-ice-700"])
                    }, null, 8, ["class"])) : (r(), h(c, {
                      key: 1,
                      name: "filter-line"
                    })),
                    T(" " + k(i.filterText), 1)
                  ]),
                  _: 1
                }, 8, ["disabled", "onClick"])
              ]),
              _: 1
            }, 8, ["content"])
          ], 2)) : n("", !0),
          u("div", je, [
            f(e.$slots, "actions")
          ])
        ]),
        S(z, {
          "data-test": "filters|content",
          class: a(e.$style["filters-expand"]),
          "is-expanded": i.isShowingFilters
        }, {
          default: m(() => [
            u("div", {
              class: a(["relative pt-12", e.$style["filters-wrapper"]])
            }, [
              S(w, {
                ref: "llFilters",
                class: a({ [e.$style["filters-half-width"]]: t.showPrimaryControls && t.showSecondaryControls }),
                "disable-apply": t.isLoading,
                "disable-clear": t.isLoading || !t.numberOfFilters,
                "disable-persistency": s.disablePersistency,
                schema: s.filterSchema,
                "validation-schema": s.validationSchema,
                onChange: l[3] || (l[3] = (y) => i.filters = y),
                onReset: t.reset,
                onSubmit: t.onFilter
              }, null, 8, ["class", "disable-apply", "disable-clear", "disable-persistency", "schema", "validation-schema", "onReset", "onSubmit"])
            ], 2)
          ]),
          _: 1
        }, 8, ["class", "is-expanded"])
      ], 2)) : n("", !0),
      t.showSecondaryControls ? (r(), o("div", {
        key: 1,
        class: a(["secondary-controls", [e.$style["legacy-box"], { "col-span-12 mt-0 lg:col-span-6": t.showPrimaryControls }]])
      }, [
        f(e.$slots, "secondary-controls")
      ], 2)) : n("", !0)
    ], 2)) : n("", !0),
    f(e.$slots, "eyebrow"),
    t.shouldShowTotal || Object.keys(s.sorts).length ? (r(), o("div", {
      key: 1,
      class: a(["mb-1.5", t.shouldShowTotal ? e.$style["total-sort"] : "text-right"])
    }, [
      t.shouldShowTotal ? (r(), o("div", Ke, k(t.total), 1)) : n("", !0),
      Object.keys(s.sorts).length ? (r(), h(H, {
        key: 1,
        class: a(e.$style.dropdown),
        label: `${s.sortLabel} ${i.sortTerm}`,
        onToggleOnce: t.onSortToggle
      }, {
        default: m(() => [
          u("ul", {
            ref: "sortOptions",
            class: "dropdown__list",
            style: Z({ minWidth: i.sortOptionsWidth })
          }, [
            (r(!0), o(q, null, J(Object.keys(s.sorts), (y, U) => (r(), o("li", {
              key: U,
              class: a([{ "bg-blue-100 text-ice-700": y === i.sortTerm }, "dropdown__item rounded"])
            }, [
              S(g, {
                inline: "",
                class: a(["items-center", e.$style["sort-option"]]),
                onClick: (We) => t.onSort(y)
              }, {
                default: m(() => [
                  T(k(y) + " ", 1),
                  y === i.sortTerm ? (r(), h(c, {
                    key: 0,
                    name: "check",
                    class: "ml-auto text-blue-500"
                  })) : n("", !0)
                ]),
                _: 2
              }, 1032, ["class", "onClick"])
            ], 2))), 128))
          ], 4)
        ]),
        _: 1
      }, 8, ["class", "label", "onToggleOnce"])) : n("", !0)
    ], 2)) : n("", !0),
    t.useDefinedSlots ? (r(), o("div", {
      key: 2,
      class: a(e.$style["list-items"])
    }, [
      E((r(), o("header", {
        "data-test": "header|defined-slot",
        class: a([[
          e.$style.header,
          {
            "m-0": !s.isSelectable
          }
        ], "rounded"])
      }, [
        u("div", {
          class: a([e.$style["header-grid-container"], "border-b border-ice-200 px-3"])
        }, [
          s.isSelectable ? (r(), h(M, {
            key: 0,
            class: a(["ml-3", e.$style["select-all"]]),
            checked: t.isSomePageChecked,
            indeterminate: t.isSomePageChecked && !t.isAllPageChecked,
            "onUpdate:checked": t.onSelectPage
          }, null, 8, ["checked", "class", "indeterminate", "onUpdate:checked"])) : n("", !0),
          u("div", {
            class: a(["ll-grid flex-1", e.$style["header-grid"]])
          }, [
            f(e.$slots, "list-header")
          ], 2)
        ], 2),
        s.isSelectable ? (r(), h(j, X({ key: 0 }, {
          allowSelectAll: !s.hideSelectAll && !s.isServerSide,
          isAllPageChecked: t.isAllPageChecked,
          isSomePageChecked: t.isSomePageChecked,
          totalCount: t.totalCount,
          totalSelectedCount: t.totalSelectedCount,
          hideBulkActionOptions: s.hideBulkActionOptions,
          hideNumberOfTotalSelected: s.hideNumberOfTotalSelected
        }, {
          class: !t.isSelectBarVisible && "lg:hidden",
          "onChange:clearSelected": t.clearSelected,
          "onChange:selectCurrent": t.onSelectPage,
          "onChange:selectAll": t.selectAll
        }), {
          "bulk-actions-content": m(() => [
            f(e.$slots, "bulk-actions", { selectedItems: i.selectedItems })
          ]),
          _: 3
        }, 16, ["class", "onChange:clearSelected", "onChange:selectCurrent", "onChange:selectAll"])) : n("", !0)
      ], 2)), [
        [G, t.headerOffset]
      ]),
      (r(), h(Q(s.disableLoader ? "div" : "LoadingManager"), {
        "empty-state-text": s.emptyStateText,
        loading: t.isLoading,
        results: t.paginated
      }, {
        default: m(() => [
          f(e.$slots, "list-items", {
            clearAll: t.clearSelected,
            displayItems: i.results,
            isFiltered: t.isFiltered,
            isItemDisabled: s.isItemDisabled,
            results: t.paginated,
            onSelect: t.onSelectItem,
            selectedItems: i.selectedItems
          })
        ]),
        _: 3
      }, 8, ["empty-state-text", "loading", "results"]))
    ], 2)) : n("", !0),
    f(e.$slots, "default", {
      currentPage: i.currentPage,
      displayItems: i.results,
      filters: i.filters,
      isFiltered: t.isFiltered,
      isItemDisabled: s.isItemDisabled,
      results: t.paginated,
      searchTerm: i.searchTerm,
      total: t.totalCount
    }),
    t.totalCount > s.pageSize ? (r(), h(K, {
      key: 3,
      "current-page": i.currentPage,
      "list-length": t.totalCount,
      "page-size": s.pageSize,
      onSetPage: t.onPaginateSetPage
    }, null, 8, ["current-page", "list-length", "page-size", "onSetPage"])) : n("", !0)
  ]);
}
const Ue = {
  $style: Ne
}, ft = /* @__PURE__ */ C(ze, [["render", Ge], ["__cssModules", Ue]]);
export {
  be as BulkActions,
  mt as ListGroup,
  gt as ListHeader,
  Ce as LoadingManager,
  ft as default
};
//# sourceMappingURL=ListView.js.map
