Skip to content

Commit

Permalink
Try to reduce refreshing #3383
Browse files Browse the repository at this point in the history
  • Loading branch information
piroor committed Nov 1, 2023
1 parent 5fa5f8d commit d3b0898
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 8 deletions.
8 changes: 8 additions & 0 deletions webextensions/background/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export async function closeOthers(exceptionRoots) {
}

export function collapseTree(rootTabs, { recursively } = {}) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });
rootTabs = Array.isArray(rootTabs) && rootTabs || [rootTabs];
const rootTabsSet = new Set(rootTabs);
const tabs = (
Expand All @@ -199,10 +200,12 @@ export function collapseTree(rootTabs, { recursively } = {}) {
});
});
}
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
TSTAPI.clearCache(cache);
}

export function collapseAll(windowId) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });
const cache = {};
for (const tab of Tab.getNormalTabs(windowId, { iterator: true })) {
if (!tab.$TST.hasChild || tab.$TST.subtreeCollapsed)
Expand All @@ -220,10 +223,12 @@ export function collapseAll(windowId) {
});
});
}
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
TSTAPI.clearCache(cache);
}

export function expandTree(rootTabs, { recursively } = {}) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });
rootTabs = Array.isArray(rootTabs) && rootTabs || [rootTabs];
const rootTabsSet = new Set(rootTabs);
const tabs = (
Expand All @@ -249,10 +254,12 @@ export function expandTree(rootTabs, { recursively } = {}) {
});
});
}
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
TSTAPI.clearCache(cache);
}

export function expandAll(windowId) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });
const cache = {};
for (const tab of Tab.getNormalTabs(windowId, { iterator: true })) {
if (!tab.$TST.hasChild || !tab.$TST.subtreeCollapsed)
Expand All @@ -270,6 +277,7 @@ export function expandAll(windowId) {
});
});
}
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
TSTAPI.clearCache(cache);
}

Expand Down
10 changes: 8 additions & 2 deletions webextensions/background/tab-context-menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import * as ApiTabs from '/common/api-tabs.js';
import * as Constants from '/common/constants.js';
import * as ContextualIdentities from '/common/contextual-identities.js';
import * as SidebarConnection from '/common/sidebar-connection.js';
import * as Sync from '/common/sync.js';
import * as TabsInternalOperation from '/common/tabs-internal-operation.js';
import * as TabsStore from '/common/tabs-store.js';
Expand Down Expand Up @@ -1145,8 +1146,13 @@ async function onClick(info, contextTab) {
}; break;
case 'context_undoCloseTab': {
const sessions = await browser.sessions.getRecentlyClosed({ maxResults: 1 }).catch(ApiTabs.createErrorHandler());
if (sessions.length && sessions[0].tab)
browser.sessions.restore(sessions[0].tab.sessionId).catch(ApiTabs.createErrorSuppressor());
if (sessions.length && sessions[0].tab) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });
browser.sessions.restore(sessions[0].tab.sessionId).catch(ApiTabs.createErrorSuppressor())
.then(() => {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
});
}
}; break;
case 'context_closeTab': {
const closeTabs = (multiselectedTabs || TreeBehavior.getClosingTabsFromParent(contextTab, {
Expand Down
23 changes: 18 additions & 5 deletions webextensions/background/tabs-move.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ async function moveTabsInternallyBefore(tabs, referenceTab, options = {}) {
if (!tabs.length)
return [];

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

const movedTabs = [];
try {
/*
Expand Down Expand Up @@ -135,16 +137,17 @@ async function moveTabsInternallyBefore(tabs, referenceTab, options = {}) {
() => toLines(Array.from(window.getOrderedTabs()),
tab => ` - ${tab.index}: ${tab.id}${tabs.includes(tab) ? '[MOVED]' : ''}`)));
}
if (SidebarConnection.isInitialized()) { // only on the background page
if (options.delayedMove) // Wait until opening animation is finished.
await wait(configs.newTabAnimationDuration);
syncToNativeTabs(tabs);
}
if (options.delayedMove) // Wait until opening animation is finished.
await wait(configs.newTabAnimationDuration);
syncToNativeTabs(tabs);
}
catch(e) {
ApiTabs.handleMissingTabError(e);
log('moveTabsInternallyBefore failed: ', String(e));
}

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });

return movedTabs;
}
export async function moveTabInternallyBefore(tab, referenceTab, options = {}) {
Expand Down Expand Up @@ -189,6 +192,8 @@ async function moveTabsInternallyAfter(tabs, referenceTab, options = {}) {
if (!tabs.length)
return [];

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

const movedTabs = [];
try {
/*
Expand Down Expand Up @@ -254,6 +259,9 @@ async function moveTabsInternallyAfter(tabs, referenceTab, options = {}) {
ApiTabs.handleMissingTabError(e);
log('moveTabsInternallyAfter failed: ', String(e));
}

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });

return movedTabs;
}
export async function moveTabInternallyAfter(tab, referenceTab, options = {}) {
Expand Down Expand Up @@ -321,6 +329,8 @@ async function syncToNativeTabsInternal(windowId) {
log(`syncToNativeTabs(${windowId}): step1, internalOrder => nativeTabsOrder`);
let tabIdsForUpdatedIndices = Array.from(nativeTabsOrder);

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

const moveOperations = (new SequenceMatcher(nativeTabsOrder, internalOrder)).operations();
const movedTabs = new Set();
for (const operation of moveOperations) {
Expand Down Expand Up @@ -386,6 +396,9 @@ async function syncToNativeTabsInternal(windowId) {
break;
}
}

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });

log(`syncToNativeTabs(${windowId}): step1, rearrange completed.`);

if (movedTabs.size > 0) {
Expand Down
3 changes: 3 additions & 0 deletions webextensions/background/tabs-open.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ export async function openURIsInTabs(uris, { windowId, insertBefore, insertAfter
if (!windowId)
throw new Error('missing loading target window\n' + new Error().stack);

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

const tabs = [];
// Don't return the result of Tab.doAndGetNewTabs because their order can
// be inverted due to browser.tabs.insertAfterCurrent=true
Expand Down Expand Up @@ -245,6 +247,7 @@ export async function openURIsInTabs(uris, { windowId, insertBefore, insertAfter
}
await TabsMove.waitUntilSynchronized(windowId);
}
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
return openedTabs;
}

Expand Down
33 changes: 32 additions & 1 deletion webextensions/background/tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ export async function attachTabTo(child, parent, options = {}) {
if (!newlyAttached)
log('=> already attached');

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

if (newlyAttached) {
detachTab(child, {
...options,
Expand Down Expand Up @@ -291,10 +293,14 @@ export async function attachTabTo(child, parent, options = {}) {
newIndex, newlyAttached
});

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });

return !options.dontMove && moved;
}

async function collapseExpandForAttachedTab(tab, parent, options = {}) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

// Because the tab is possibly closing for "reopen" operation,
// we need to apply "forceExpand" immediately. Otherwise, when
// the tab is closed with "subtree collapsed" state, descendant
Expand All @@ -321,8 +327,10 @@ async function collapseExpandForAttachedTab(tab, parent, options = {}) {
{ tabProperties: ['tab'] }
);
TSTAPI.clearCache(cache);
if (!TabsStore.ensureLivingTab(tab))
if (!TabsStore.ensureLivingTab(tab)) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
return;
}

if (options.forceExpand && allowed) {
log(` expand tab ${tab.id} by forceExpand option`);
Expand Down Expand Up @@ -402,6 +410,8 @@ async function collapseExpandForAttachedTab(tab, parent, options = {}) {
broadcast: true
});
}

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
}

export function getReferenceTabsForNewChild(child, parent, { insertAt, ignoreTabs, lastRelatedTab, children, descendants } = {}) {
Expand Down Expand Up @@ -535,6 +545,9 @@ export function getReferenceTabsForNewNextSibling(base, options = {}) {
export function detachTab(child, options = {}) {
log('detachTab: ', child.id, options,
{ stack: `${configs.debug && new Error().stack}\n${options.stack || ''}` });

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

// the "parent" option is used for removing child.
const parent = TabsStore.ensureLivingTab(options.parent) || child.$TST.parent;

Expand Down Expand Up @@ -588,9 +601,13 @@ export function detachTab(child, options = {}) {
toBeRemoved: !!options.toBeRemoved,
toBeDetached: !!options.toBeDetached
});

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
}

export async function detachTabsFromTree(tabs, options = {}) {
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

if (!Array.isArray(tabs))
tabs = [tabs];
tabs = Array.from(tabs).reverse();
Expand Down Expand Up @@ -619,6 +636,8 @@ export async function detachTabsFromTree(tabs, options = {}) {
}
if (promisedAttach.length > 0)
await Promise.all(promisedAttach);

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
}

export async function detachAllChildren(
Expand Down Expand Up @@ -685,6 +704,8 @@ export async function detachAllChildren(
behavior = Constants.kPARENT_TAB_OPERATION_BEHAVIOR_PROMOTE_ALL_CHILDREN;
}

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

if (!dontExpand &&
((tab && !tab.$TST.collapsed) ||
behavior == Constants.kPARENT_TAB_OPERATION_BEHAVIOR_DETACH_ALL_CHILDREN)) {
Expand Down Expand Up @@ -768,6 +789,8 @@ export async function detachAllChildren(
count++;
await Promise.all(promises);
}

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
}

// returns moved (or not)
Expand Down Expand Up @@ -1013,6 +1036,8 @@ async function collapseExpandSubtreeInternal(tab, params = {}) {
}
//setTabValue(tab, Constants.kTAB_STATE_SUBTREE_COLLAPSED, params.collapsed);

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

const childTabs = tab.$TST.children;
const lastExpandedTabIndex = childTabs.length - 1;
for (let i = 0, maxi = childTabs.length; i < maxi; i++) {
Expand Down Expand Up @@ -1046,6 +1071,8 @@ async function collapseExpandSubtreeInternal(tab, params = {}) {
anchorId: tab.id,
last: true
});

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
}

export function manualCollapseExpandSubtree(tab, params = {}) {
Expand Down Expand Up @@ -1184,6 +1211,7 @@ export async function collapseExpandTreesIntelligentlyFor(tab, options = {}) {
return;
}
window.doingIntelligentlyCollapseExpandCount++;
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

const expandedAncestors = [tab.id]
.concat(tab.$TST.ancestors.map(ancestor => ancestor.id))
Expand Down Expand Up @@ -1235,6 +1263,7 @@ export async function collapseExpandTreesIntelligentlyFor(tab, options = {}) {
collapsed: false
});
window.doingIntelligentlyCollapseExpandCount--;
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
}

export async function fixupSubtreeCollapsedState(tab, options = {}) {
Expand All @@ -1251,6 +1280,7 @@ export async function fixupSubtreeCollapsedState(tab, options = {}) {
collapsedStateMismatched,
nextIsFirstChild
});
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });
if (collapsedStateMismatched) {
log(' => set collapsed state');
await collapseExpandSubtree(tab, {
Expand All @@ -1264,6 +1294,7 @@ export async function fixupSubtreeCollapsedState(tab, options = {}) {
await followDescendantsToMovedRoot(tab, options);
fixed = true;
}
SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
return fixed;
}

Expand Down
2 changes: 2 additions & 0 deletions webextensions/common/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ export const kCOMMAND_NOTIFY_CONTEXT_ITEM_CHECKED_STATUS_CHANGED = 'treestyletab
export const kCOMMAND_NOTIFY_CONTEXT_OVERRIDDEN = 'treestyletab:notify-context-overridden';
export const kCOMMAND_AUTODETECT_DUPLICATED_TAB_DETECTION_DELAY = 'treestyletab:autodetect-duplicated-tab-detection-delay';
export const kCOMMAND_TEST_DUPLICATED_TAB_DETECTION = 'treestyletab:test-duplicated-tab-detection';
export const kCOMMAND_NOTIFY_START_BATCH_OPERATION = 'treestyletab:start-batch-operation';
export const kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION = 'treestyletab:finish-batch-operation';

export const kCOMMAND_ACTIVATE_TAB = 'treestyletab:activate-tab';
export const kCOMMAND_TOGGLE_MUTED_FROM_SOUND_BUTTON = 'treestyletab:toggle-muted-from-sound-button';
Expand Down
4 changes: 4 additions & 0 deletions webextensions/common/tabs-internal-operation.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ export function removeTabs(tabs, { keepDescendants, byMouseOperation, originalSt
const sortedTabs = Tab.sort(Array.from(tabs));
Tab.onMultipleTabsRemoving.dispatch(sortedTabs, { triggerTab, originalStructure });

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_START_BATCH_OPERATION });

const promisedRemoved = browser.tabs.remove(tabIds).catch(ApiTabs.createErrorHandler(ApiTabs.handleMissingTabError));
if (window) {
promisedRemoved.then(() => {
Expand All @@ -150,6 +152,8 @@ export function removeTabs(tabs, { keepDescendants, byMouseOperation, originalSt
window.keepDescendantsTabs.delete(tab.id);
}
Tab.onMultipleTabsRemoved.dispatch(sortedTabs.filter(tab => !canceledTabs.has(tab)), { triggerTab, originalStructure });

SidebarConnection.sendMessage({ type: Constants.kCOMMAND_NOTIFY_FINISH_BATCH_OPERATION });
});
}
return promisedRemoved;
Expand Down
6 changes: 6 additions & 0 deletions webextensions/sidebar/collapse-expand.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ function log(...args) {

export const onUpdating = new EventListenerManager();
export const onUpdated = new EventListenerManager();
export const onRefreshStarted = new EventListenerManager();
export const onRefreshFinished = new EventListenerManager();

export function setCollapsed(tab, info = {}) {
log('setCollapsed ', tab.id, info);
Expand Down Expand Up @@ -76,6 +78,8 @@ export function setCollapsed(tab, info = {}) {
if (tab.status == 'loading')
tab.$TST.addState(Constants.kTAB_STATE_THROBBER_UNSYNCHRONIZED);

onRefreshStarted.dispatch(tab, { collapsed: info.cpllapsed });

const manager = tab.$TST.collapsedStateChangedManager || new EventListenerManager();

if (tab.$TST.updatingCollapsedStateCanceller) {
Expand Down Expand Up @@ -115,6 +119,7 @@ export function setCollapsed(tab, info = {}) {
anchor: info.anchor,
last: info.last
});
onRefreshFinished.dispatch(tab, { collapsed: info.cpllapsed });
};
manager.addListener(onCompleted);

Expand Down Expand Up @@ -142,6 +147,7 @@ export function setCollapsed(tab, info = {}) {

const onCanceled = () => {
manager.removeListener(onCompleted);
onRefreshFinished.dispatch(tab, { collapsed: info.cpllapsed });
};

nextFrame().then(() => {
Expand Down
Loading

0 comments on commit d3b0898

Please sign in to comment.