'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-305226cb.js');
const index$1 = require('./index-f92a5850.js');
require('./v4-c23234d2.js');

function debounce(func, wait, immediate) {
  let timeout;
  return function () {
    let context = this, args = arguments;
    clearTimeout(timeout);
    if (immediate && !timeout)
      func.apply(context, args);
    timeout = setTimeout(function () {
      timeout = null;
      if (!immediate)
        func.apply(context, args);
    }, wait);
  };
}

const bsTabListCss = ":is(.bs-tab-list,bs-tab-list){--active-line-offset:0;--active-line-max-width:0;--active-line-scale:0;--active-line-transition-duration:300ms;--tab-list-opacity:1;--tab-color:var(--bs-ink-light);--tab-cursor:pointer;--tab-display:inline-flex;--tab-justify:space-around;--tab-text-size:var(--bs-text-sm);--tab-weight:var(--bs-font-normal);align-items:center;border-bottom:1px solid var(--bs-border-base);display:flex;font-size:var(--tab-text-size);height:2.5rem;justify-content:var(--tab-justify);line-height:1.5;opacity:var(--tab-list-opacity);position:relative;width:100%}:is(.bs-tab-list,bs-tab-list):where([data-resizing]:not([data-resizing=\"false\"])){--tab-list-opacity:0}@media (min-width: 752px){:is(.bs-tab-list,bs-tab-list){--tab-justify:flex-start;--tab-text-size:var(--bs-text-base)}}:is(bs-tab-list,.bs-tab-list) :where([role=\"tab\"],.bs-tab-list-toggle){align-items:center;color:var(--tab-color, var(--bs-ink-light));column-gap:0.5rem;cursor:var(--tab-cursor);display:var(--tab-display);flex-grow:0;flex-shrink:0;font-weight:var(--tab-weight, var(--bs-font-normal));height:2.5rem;padding:0.5rem;outline-color:var(--bs-blue-base);outline-offset:-1px;text-decoration:none}:is(bs-tab-list,.bs-tab-list) :where([role=\"tab\"]):where([tabindex=\"-1\"]){--tab-cursor:default}:is(bs-tab-list,.bs-tab-list) :where([role=\"tab\"],.bs-tab-list-toggle):where([data-hidden]:not([data-hidden=\"false\"])){--tab-display:none}:is(bs-tab-list,.bs-tab-list) :where([role=\"tab\"]):where([aria-selected]:not([aria-selected=\"false\"])),:is(bs-tab-list,.bs-tab-list) :where(.bs-tab-list-toggle):where([data-active]:not([data-active=\"false\"])){--tab-color:var(--bs-ink-light);--tab-weight:var(--bs-font-bold)}:where(.bs-tab-panel,bs-tab-panel):where([role=\"tabpanel\"]){display:none}:where(.bs-tab-panel,bs-tab-panel):where([role=\"tabpanel\"][data-active]:not([data-active=\"false\"])){display:block}:is(.bs-tab-list,bs-tab-list)::after{background-color:var(--bs-blue-base);bottom:0;content:\"\";height:0.25rem;left:0;position:absolute;transform:translate(var(--active-line-offset)) scaleX(var(--active-line-scale));transform-origin:top left;transition:transform var(--active-line-transition-duration) ease-in;width:100%}";

const DEFAULT_TOGGLE_WIDTH = 73;
const ELLIPSIS_WIDTH = 20;
const BsTabList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.tabChange = index.createEvent(this, "tabChange", 7);
    this.accumulatedWidths = [];
    this.activeLineInitialized = false;
    this.setAccumlulatedWidths = debounce(() => {
      let tabWidth;
      this.allTabs.forEach((t, i) => {
        tabWidth = t.getBoundingClientRect().width;
        this.accumulatedWidths.push(i ? tabWidth + this.accumulatedWidths[i - 1] : tabWidth);
      });
    }, 500, true);
    this.activeTabId = undefined;
    this.helperText = 'Select a tab';
    this.helperDescription = undefined;
    this.adaptedToWidth = false;
    this.dropdownMounted = false;
    this.hiddenTabs = [];
    this.showDropdown = false;
    this.showDropdownToggle = false;
  }
  get activeTabIdx() {
    if (this.activeTabId)
      return this.allTabs.findIndex(t => t.id === this.activeTabId);
  }
  get activeTabIsHidden() {
    return this.hiddenTabs.some(t => t.id === this.activeTabId);
  }
  get dropdownOptionsId() {
    return `${this.dropdownId}-options`;
  }
  get dropdownToggleId() {
    return `${this.dropdownId}-toggle`;
  }
  get dropdownToggleText() {
    return this.activeTabIsHidden ? this.allTabs[this.activeTabIdx].textContent : 'More';
  }
  get dropdownToggleWidth() {
    if (this.activeTabIsHidden) {
      return this.accumulatedWidths[this.activeTabIdx] - this.accumulatedWidths[this.activeTabIdx - 1] + ELLIPSIS_WIDTH;
    }
    return DEFAULT_TOGGLE_WIDTH;
  }
  get navigableTabs() {
    var _a, _b;
    let tabs = [];
    for (let tab of this.allTabs) {
      if (((_a = tab.dataset) === null || _a === void 0 ? void 0 : _a.hidden) === 'true' || ((_b = tab.dataset) === null || _b === void 0 ? void 0 : _b.hidden) === '' || tab.getAttribute('tabindex') === '-1')
        break;
      tabs.push(tab);
    }
    if (this.showDropdownToggle)
      tabs.push(this.hostEl.querySelector('.bs-tab-list-toggle'));
    return tabs;
  }
  /**
   * This is basically the main function of this component.
   * It determines which tabs should be hidden and which should be shown.
   * If we're hiding tabs, need to show the dropdown toggle.
   * Tabs can be hidden when the total width of the tabs exceeds the max width of the tablist.
   * When tabs are hidden and a hidden tab is selected from the dropdown, the dropdown toggle text should be the text of the selected tab in most cases.
   * Otherwise, the dropdown toggle text should be 'More'.
   * @returns {void}
   */
  adaptToWidth() {
    var _a;
    let showToggle = false;
    let tab;
    let thresholdWidth = 0;
    let thresholdReached = false;
    let tabsToHide = [];
    if (!((_a = this.allTabs) === null || _a === void 0 ? void 0 : _a.length))
      return;
    for (let i = 0; i < this.allTabs.length; i++) {
      tab = this.allTabs[i];
      tab.setAttribute('tabindex', '-1');
      if (thresholdReached && i !== this.activeTabIdx) {
        tab.dataset.hidden = 'true';
        tabsToHide.push(tab);
        continue;
      }
      thresholdWidth = i < this.allTabs.length - 1 ? this.totalWidth - this.dropdownToggleWidth : this.totalWidth;
      if (this.accumulatedWidths[i] > thresholdWidth) {
        tab.dataset.hidden = 'true';
        tabsToHide.push(tab);
        showToggle = true;
        thresholdReached = true;
        continue;
      }
      tab.dataset.hidden = 'false';
      tab.setAttribute('tabindex', '0');
    }
    this.showDropdownToggle = showToggle;
    this.hiddenTabs = tabsToHide;
    if (!this.adaptedToWidth)
      setTimeout(() => this.adaptedToWidth = true, 100);
    setTimeout(() => {
      this.moveActiveLine();
      this.activeLineInitialized = true;
    }, this.activeLineInitialized ? 0 : 1000);
  }
  getTabWidth(tabIdx) {
    var _a, _b, _c;
    const actualWidth = (_c = (_b = (_a = this.allTabs[tabIdx]) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.width;
    if (actualWidth)
      return actualWidth;
    const approxWidth = (tabIdx === 0) ? this.accumulatedWidths[0] : this.accumulatedWidths[tabIdx] - this.accumulatedWidths[tabIdx - 1];
    return approxWidth || 0;
  }
  handleDropdownClose() {
    this.dropdownToggle.focus();
    this.showDropdown = false;
  }
  handleDropdownToggleClick() {
    this.showDropdown = !this.showDropdown;
    if (!this.dropdownMounted)
      this.dropdownMounted = true;
  }
  handleDropdownOptionSelect(event) {
    this.showDropdown = false;
    this.dropdownToggle.focus();
    this.tabChange.emit(event.detail);
  }
  handleTabClick(event) {
    const tab = event.target.closest('[role="tab"]');
    if (!tab || tab.getAttribute('aria-selected') === 'true')
      return;
    const tabId = tab.getAttribute('id');
    this.tabChange.emit(tabId);
  }
  handleTabNav(e) {
    if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
      const tabIdx = this.navigableTabs.findIndex(t => t.id === e.target.id);
      if (tabIdx === -1)
        return;
      e.preventDefault();
      e.stopPropagation();
      e.key === 'ArrowLeft' ? this.handleTabPrevious(tabIdx) : this.handleTabNext(tabIdx);
    }
  }
  handleTabNext(tabIdx) {
    const nextIdx = (tabIdx + 1) % this.navigableTabs.length;
    this.navigableTabs[nextIdx].focus();
  }
  handleTabPrevious(tabIdx) {
    const prevIdx = tabIdx === 0 ? this.navigableTabs.length - 1 : tabIdx - 1;
    this.navigableTabs[prevIdx].focus();
  }
  moveActiveLine() {
    var _a, _b;
    const prevOffset = parseInt(this.hostEl.style.getPropertyValue('--active-line-offset')) || 0;
    const max = this.totalWidth;
    let duration = 300;
    let offsetPx = ((_b = (_a = this.navigableTabs) === null || _a === void 0 ? void 0 : _a[this.activeTabIdx]) === null || _b === void 0 ? void 0 : _b.offsetLeft) || 0;
    let scaleNum = this.getTabWidth(this.activeTabIdx);
    if (this.showDropdownToggle && this.activeTabIsHidden) {
      offsetPx = this.dropdownToggle.offsetLeft;
      scaleNum = this.dropdownToggle.offsetWidth;
    }
    duration = Math.max(Math.abs((offsetPx - prevOffset) / max * 300), 100);
    this.hostEl.style.setProperty('--active-line-max-width', `${max}px`);
    this.hostEl.style.setProperty('--active-line-scale', `${scaleNum / max}`);
    this.hostEl.style.setProperty('--active-line-offset', `${offsetPx}px`);
    this.hostEl.style.setProperty('--active-line-transition-duration', `${duration}ms`);
  }
  mutationObserverSetup() {
    this.mutationObserver = new MutationObserver(debounce((mutations) => {
      if (this.shouldIgnoreThisMutation(mutations))
        return;
      this.setAllTabs();
      this.setAccumlulatedWidths();
      this.adaptToWidth();
    }, 500));
    this.mutationObserver.observe(this.hostEl, { childList: true });
  }
  observerCleanup() {
    var _a, _b, _c, _d;
    (_b = (_a = this.mutationObserver) === null || _a === void 0 ? void 0 : _a.disconnect) === null || _b === void 0 ? void 0 : _b.call(_a);
    this.mutationObserver = null;
    (_d = (_c = this.resizeObserver) === null || _c === void 0 ? void 0 : _c.disconnect) === null || _d === void 0 ? void 0 : _d.call(_c);
    this.resizeObserver = null;
  }
  resizeObserverSetup() {
    this.resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        this.totalWidth = entry.contentBoxSize[0].inlineSize;
      }
      this.adaptToWidth();
    });
    this.resizeObserver.observe(this.hostEl);
  }
  setAllTabs() {
    this.allTabs = Array.from(this.hostEl.children).filter(c => c.nodeName === 'BS-TAB' || c.role === 'tab');
  }
  shouldIgnoreThisMutation(mutations) {
    var _a;
    return mutations.length === 1 &&
      ((_a = mutations[0].addedNodes[0]) === null || _a === void 0 ? void 0 : _a.nodeName) === "BS-DROPDOWN-WITH-OPTIONS" &&
      this.adaptedToWidth;
  }
  // Lifecycle Hooks
  connectedCallback() {
    if (!this.mutationObserver)
      this.mutationObserverSetup();
    if (!this.resizeObserver)
      this.resizeObserverSetup();
  }
  componentDidLoad() {
    var _a;
    if (!this.hostEl.hasAttribute('id'))
      this.hostEl.setAttribute('id', index$1.genId());
    this.totalWidth = this.hostEl.getBoundingClientRect().width;
    this.setAllTabs();
    this.setAccumlulatedWidths();
    this.adaptToWidth();
    this.dropdownId = index$1.genId();
    (_a = this.allTabs[this.activeTabIdx]) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-selected', 'true');
  }
  disconnectedCallback() {
    this.observerCleanup();
  }
  // Watchers
  handleActiveTabIdChange() {
    var _a;
    (_a = this.allTabs[this.activeTabIdx]) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-selected', 'true');
    this.adaptToWidth();
  }
  render() {
    return (index.h(index.Host, { role: "tablist", class: "bs-tab-list", "data-resizing": !this.adaptedToWidth || undefined, onClick: (e) => this.handleTabClick(e), onKeydown: (e) => this.handleTabNav(e) }, index.h("slot", null), index.h("button", { "aria-controls": this.dropdownId, "aria-expanded": this.showDropdown, class: "bs-tab-list-toggle", "data-active": this.activeTabIsHidden || undefined, "data-hidden": !this.showDropdownToggle, id: this.dropdownToggleId, ref: el => this.dropdownToggle = el, onClick: () => this.handleDropdownToggleClick() }, index.h("bs-icon-action-ellipsis", { size: "sm" }), this.dropdownToggleText), this.showDropdownToggle &&
      index.h("bs-dropdown-with-options", { id: this.dropdownId, class: "bs-tab-list-dropdown", containerId: this.hostEl.id, enterControlled: true, enterTrigger: this.showDropdown, helperText: this.helperText, helperDescription: this.helperDescription || undefined, leaveTrigger: !this.showDropdown, optionsId: this.dropdownOptionsId, toggleId: this.dropdownToggleId, onClose: () => this.handleDropdownClose(), onOptselected: (e) => this.handleDropdownOptionSelect(e) }, this.hiddenTabs.map(t => (index.h("bs-dropdown-option", { value: t.id, optionsId: this.dropdownOptionsId }, t.textContent))))));
  }
  get hostEl() { return index.getElement(this); }
  static get watchers() { return {
    "activeTabId": ["handleActiveTabIdChange"]
  }; }
};
BsTabList.style = bsTabListCss;

exports.bs_tab_list = BsTabList;

//# sourceMappingURL=bs-tab-list.cjs.entry.js.map