Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ If that profile already has a window open, ProfileBar brings it forward, even fr

Install the [ProfileBar for Chrome](https://chromewebstore.google.com/detail/pkibfaoenoibogibnlkkpmgagjckjijh) extension to move tabs from the
right-click menu. Right-click a page and choose **Move tab to profile**, or
right-click a tab and choose **Move tabs to profile**. The extension closes the
right-click a tab and choose **Move tabs to profile**. Right-clicking the
extension's toolbar icon offers the same moves for the tab you're on, including
**Move group to profile** when that tab is in a group. The extension closes the
original tabs after ProfileBar reports success. ProfileBar registers the local
Chrome helper when it launches. If the extension cannot find it, launch
ProfileBar and choose **Refresh profiles** from the extension menu.
Expand Down
71 changes: 57 additions & 14 deletions extension/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@ const MENU_REFRESH = "refresh-profiles";
const PROFILE_PREFIX = "profile:";
const ALWAYS_MENU_ROOT = "always-open-site";
const ALWAYS_PREFIX = "always:";
const ACTION_GROUP_ROOT = "action-group";

importScripts("routing-rules.js", "router.js");

let menuRefresh = Promise.resolve();
// Chrome does not say which tab was right-clicked before it shows the menu, so the group actions
// appear while the focused window has a group. Null until this service worker builds the menu.
let groupMenuIds = null;
// The toolbar menu acts on the active tab, so its items follow that tab.
let activeTabMenuIds = { webPage: [], inGroup: [] };

chrome.runtime.onInstalled.addListener(({ reason }) => {
if (reason === "install") {
Expand All @@ -33,9 +36,15 @@ for (const event of [
chrome.tabGroups.onCreated, chrome.tabGroups.onRemoved, chrome.tabs.onAttached, chrome.tabs.onDetached,
]) {
event.addListener(() => {
void updateGroupMenu();
void updateTabMenus();
});
}
chrome.tabs.onActivated.addListener(() => {
void updateTabMenus();
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (tab.active && (changeInfo.url || "groupId" in changeInfo)) void updateTabMenus();
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === "check-profilebar") {
void refreshProfileMenu().then(sendResponse);
Expand All @@ -49,7 +58,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
const itemId = String(info.menuItemId);
const menuId = itemId.replace(/^(tab:|group:)/, "");
const menuId = itemId.replace(/^(tab:|group:|action-group:)/, "");
if (menuId === MENU_SETUP) {
void chrome.runtime.openOptionsPage();
return;
Expand All @@ -63,7 +72,7 @@ chrome.contextMenus.onClicked.addListener((info, tab) => {
return;
}
if (menuId.startsWith(PROFILE_PREFIX)) {
const mode = itemId.startsWith("group:") ? "group" : itemId.startsWith("tab:") ? "tab" : "page";
const mode = /^(action-)?group:/.test(itemId) ? "group" : itemId.startsWith("tab:") ? "tab" : "page";
void moveToProfile(decodeURIComponent(menuId.slice(PROFILE_PREFIX.length)), info, tab, mode);
}
});
Expand All @@ -72,12 +81,22 @@ function refreshProfileMenu() {
return queueMenuUpdate(buildProfileMenu);
}

function updateGroupMenu() {
return queueMenuUpdate(async () => {
if (groupMenuIds === null) return buildProfileMenu();
const visible = await focusedWindowHasGroup();
await Promise.all(groupMenuIds.map((id) => updateMenu(id, { visible })));
});
function updateTabMenus() {
return queueMenuUpdate(() => (groupMenuIds === null ? buildProfileMenu() : showTabActions()));
}

async function showTabActions() {
const [hasGroup, [activeTab]] = await Promise.all([
focusedWindowHasGroup(),
chrome.tabs.query({ active: true, lastFocusedWindow: true }),
]);
const onWebPage = RoutingRules.isWebUrl(activeTab?.url);
const inGroup = Number.isInteger(activeTab?.groupId) && activeTab.groupId !== -1;
await Promise.all([
...groupMenuIds.map((id) => updateMenu(id, { visible: hasGroup })),
...activeTabMenuIds.webPage.map((id) => updateMenu(id, { enabled: onWebPage })),
...activeTabMenuIds.inGroup.map((id) => updateMenu(id, { visible: inGroup })),
]);
}

function queueMenuUpdate(update) {
Expand Down Expand Up @@ -125,19 +144,30 @@ async function buildProfileMenu() {

await removeMenus();
groupMenuIds = [];
activeTabMenuIds = { webPage: [], inGroup: [] };
const named = namedProfiles(allProfiles);
await buildPageMenu(state, destinations);
if (state === "ready" && named.length > 0) {
await buildAlwaysOpenMenu(named);
activeTabMenuIds.webPage.push(ALWAYS_MENU_ROOT);
}
if (state === "ready" && destinations.length > 0) {
// Set up and Refresh work on any tab, so only the page menu's destinations follow the active tab.
activeTabMenuIds.webPage.push(...namedProfiles(destinations)
.map(({ directory }) => `${PROFILE_PREFIX}${encodeURIComponent(directory)}`));
await buildGroupActionMenu(namedProfiles(destinations));
activeTabMenuIds.inGroup.push(ACTION_GROUP_ROOT);
}
if (chrome.contextMenus.ContextType?.TAB) {
await buildTabMenu(state, destinations);
}
await showTabActions();
return { state, destinationCount: destinations?.length ?? 0, sharedNameProfiles, profiles: named };
}

// The page menu also appears on the toolbar icon, where it acts on the active tab.
async function buildPageMenu(state, profiles) {
const contexts = ["page"];
const contexts = ["page", "action"];
const parentId = PAGE_MENU_ROOT;
await createMenu({ id: parentId, title: "Move tab to profile", contexts });
if (state === "unsupported") {
Expand All @@ -164,7 +194,7 @@ async function buildPageMenu(state, profiles) {

// Lists every profile, including this one, because a rule can keep a site here.
async function buildAlwaysOpenMenu(profiles) {
const contexts = ["page"];
const contexts = ["page", "action"];
await createMenu({ id: ALWAYS_MENU_ROOT, title: "Always open this site in", contexts });
for (const profile of profiles) {
await createMenu({
Expand Down Expand Up @@ -196,10 +226,9 @@ async function buildTabMenu(state, profiles) {
title: `Move group to ${profile.title}`,
}));
groupMenuIds = ["tab:group-divider", ...groupItems.map(({ id }) => id)];
const visible = await focusedWindowHasGroup();
await createTabDivider("tab:group-divider", { visible });
await createTabDivider("tab:group-divider");
for (const item of groupItems) {
await createMenu({ ...item, parentId, contexts, visible });
await createMenu({ ...item, parentId, contexts });
}
} else {
let option;
Expand All @@ -219,6 +248,20 @@ async function buildTabMenu(state, profiles) {
}
}

// The tab strip's group moves need a right-clicked tab, so the toolbar has its own for the active tab's group.
async function buildGroupActionMenu(profiles) {
const contexts = ["action"];
await createMenu({ id: ACTION_GROUP_ROOT, title: "Move group to profile", contexts });
for (const profile of profiles) {
await createMenu({
id: `action-group:${PROFILE_PREFIX}${encodeURIComponent(profile.directory)}`,
parentId: ACTION_GROUP_ROOT,
title: profile.title,
contexts,
});
}
}

function createTabDivider(id, properties = {}) {
// Chrome hides native separators in tab submenus; this short rule matches the page menu.
return createMenu({ id, parentId: TAB_MENU_ROOT, title: "───────", enabled: false, contexts: ["tab"], ...properties });
Expand Down
1 change: 1 addition & 0 deletions extension/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"tabs",
"webNavigation"
],
"action": {},
"background": {
"service_worker": "background.js"
},
Expand Down
67 changes: 64 additions & 3 deletions extension/test/background.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,17 @@ function menuHarness({
onAttached: { addListener(listener) { listeners.tabAttached = listener; } },
onDetached: { addListener(listener) { listeners.tabDetached = listener; } },
onCreated: { addListener(listener) { listeners.tabCreated = listener; } },
onUpdated: { addListener(listener) { listeners.tabUpdated = listener; } },
onActivated: { addListener(listener) { listeners.tabActivated = listener; } },
onUpdated: {
addListener(listener) {
const previous = listeners.tabUpdated;
// Chrome always passes the updated tab.
listeners.tabUpdated = (tabId, changeInfo, tab = tabs.get(tabId) ?? { id: tabId }) => {
previous?.(tabId, changeInfo, tab);
listener(tabId, changeInfo, tab);
};
},
},
onRemoved: { addListener(listener) { listeners.tabRemoved = listener; } },
async create(tab) {
openedTabs.push(tab);
Expand Down Expand Up @@ -247,7 +257,7 @@ test("a missing ProfileBar shows setup and keeps a page fallback", async () => {
assert.deepEqual(harness.menus.map((item) => item.id), [
"move-to-profile", "setup-profilebar", "profiles-refresh-divider", "refresh-profiles",
]);
assert.equal(harness.menus[0].contexts.join(","), "page");
assert.equal(harness.menus[0].contexts.join(","), "page,action");
harness.listeners.clicked({ menuItemId: "setup-profilebar" });
assert.equal(harness.optionsOpened, 1);
});
Expand Down Expand Up @@ -294,6 +304,57 @@ test("group moves appear only while the focused window has a group", async () =>
assert.equal(harness.nativeMessages.length, 1, "visibility changes must not contact ProfileBar");
});

test("the toolbar menu offers the moves that suit the active tab", async () => {
const harness = menuHarness({ hostResponse: { ok: true, profiles: [{ directory: "Profile 2", name: "Work" }] } });
const item = (id) => harness.menus.find((menu) => menu.id === id);
const toolbar = () => ({
moveTab: item("profile:Profile%202").enabled, alwaysOpen: item("always-open-site").enabled,
moveGroup: item("action-group").visible,
});
harness.setTab({ id: 30, windowId: 1, active: true, url: "chrome://settings/", groupId: -1 });
await harness.refresh();
for (const id of ["move-to-profile", "profile:Profile%202", "always-open-site", "action-group",
"action-group:profile:Profile%202"]) {
assert.ok(item(id).contexts.includes("action"), id);
}
assert.deepEqual(toolbar(), { moveTab: false, alwaysOpen: false, moveGroup: false });
assert.notEqual(item("move-to-profile").enabled, false, "Refresh profiles stays reachable on any tab");

harness.setGroup({ id: 8, windowId: 1, title: "Research", color: "blue", collapsed: false });
harness.setTab({ id: 30, windowId: 1, active: false, url: "chrome://settings/", groupId: -1 });
harness.setTab({ id: 31, windowId: 1, active: true, url: "https://example.com/", groupId: 8, index: 0 });
harness.listeners.tabActivated({ tabId: 31, windowId: 1 });
await harness.settle();
assert.deepEqual(toolbar(), { moveTab: true, alwaysOpen: true, moveGroup: true });

const ungrouped = { id: 31, windowId: 1, active: true, url: "https://example.com/", groupId: -1, index: 0 };
harness.setTab(ungrouped);
harness.listeners.tabUpdated(31, { groupId: -1 }, ungrouped);
await harness.settle();
assert.equal(toolbar().moveGroup, false);
assert.equal(harness.nativeMessages.length, 1, "following the active tab must not contact ProfileBar");
});

test("the toolbar menu keeps setup reachable on pages that cannot move", async () => {
const harness = menuHarness();
harness.setNativeError(new Error("ProfileBar is not installed"));
harness.setTab({ id: 30, windowId: 1, active: true, url: "chrome://extensions/", groupId: -1 });
await harness.refresh();
const setup = harness.menus.find((menu) => menu.id === "setup-profilebar");
assert.ok(setup.contexts.includes("action"));
assert.notEqual(harness.menus.find((menu) => menu.id === "move-to-profile").enabled, false);
});

test("moving a group from the toolbar menu moves the active tab's group", async () => {
const harness = menuHarness({ hostResponse: { ok: true } });
harness.setGroup({ id: 8, windowId: 7, title: "Research", color: "blue", collapsed: false });
harness.setTab({ id: 1, windowId: 7, groupId: 8, index: 0, url: "https://example.com/first" });
harness.listeners.clicked({ menuItemId: "action-group:profile:Default" }, { id: 1, windowId: 7, groupId: 8 });
await new Promise(setImmediate);
assert.equal(harness.nativeMessages.at(-1).message.type, "openGroup");
assert.deepEqual(harness.removedTabs, [1]);
});

test("profiles that share a name are labelled by folder and reported to the setup page", async () => {
const harness = menuHarness({ hostResponse: { ok: true, profiles: [
{ directory: "Profile 3", name: "Taylor" },
Expand Down Expand Up @@ -391,7 +452,7 @@ test("a successful handoff closes the clicked tab after opening it in the select

const profiles = harness.menus.filter((item) => item.id.startsWith("profile:"));
assert.deepEqual(profiles.map((item) => item.title), ["Work (Default)", "Work (Profile 2)"]);
assert.equal(harness.menus[0].contexts.join(","), "page");
assert.equal(harness.menus[0].contexts.join(","), "page,action");
const tabRoot = harness.menus.find((item) => item.id === "tab-actions");
assert.equal(tabRoot.title, "Move tabs to profile");
assert.equal(tabRoot.contexts.join(","), "tab");
Expand Down
Loading