async _sortTabsInternal()

in src/js/background/backgroundLogic.js [370:439]


  async _sortTabsInternal(windowObj, pinnedTabs) {
    const tabs = await browser.tabs.query({windowId: windowObj.id});
    let pos = 0;

    // Let's collect UCIs/tabs for this window.
    /** @type {Map<string, {order: string, tabs: Tab[]}>} */
    const map = new Map;

    const lastTab = tabs.at(-1);
    /** @type {boolean} */
    let lastTabIsInTabGroup = !!lastTab && lastTab.groupId >= 0;

    for (const tab of tabs) {
      if (pinnedTabs && !tab.pinned) {
        // We don't have, or we already handled all the pinned tabs.
        break;
      }

      if (!pinnedTabs && tab.pinned) {
        // pinned tabs must be consider as taken positions.
        ++pos;
        continue;
      }

      if (tab.groupId >= 0) {
        // Skip over tabs in tab groups until it's possible to handle them better.
        continue;
      }

      if (!map.has(tab.cookieStoreId)) {
        const userContextId = backgroundLogic.getUserContextIdFromCookieStoreId(tab.cookieStoreId);
        map.set(tab.cookieStoreId, { order: userContextId, tabs: [] });
      }
      map.get(tab.cookieStoreId).tabs.push(tab);
    }

    const containerOrderStorage = await browser.storage.local.get([CONTAINER_ORDER_STORAGE_KEY]);
    const containerOrder =
      containerOrderStorage && containerOrderStorage[CONTAINER_ORDER_STORAGE_KEY];

    if (containerOrder) {
      map.forEach((obj, key) => {
        obj.order = (key in containerOrder) ? containerOrder[key] : -1;
      });
    }

    // Let's sort the map.
    const sortMap = new Map([...map.entries()].sort((a, b) => a[1].order > b[1].order));

    // Let's move tabs.
    for (const { tabs } of sortMap.values()) {
      for (const tab of tabs) {
        ++pos;
        browser.tabs.move(tab.id, {
          windowId: windowObj.id,
          index: pinnedTabs ? pos : -1
        });
        // Pinned tabs are never grouped and always inserted in the front.
        if (!pinnedTabs && lastTabIsInTabGroup && browser.tabs.ungroup) {
          // If the last item in the tab strip is a grouped tab, moving a tab
          // to its position will also add it to the tab group. Since this code
          // is only sorting ungrouped tabs, this forcibly ungroups the first
          // tab to be moved. All subsequent iterations will only be moving
          // ungrouped tabs to the position of other ungrouped tabs.
          lastTabIsInTabGroup = false;
          browser.tabs.ungroup(tab.id);
        }
      }
    }
  },