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
30 changes: 30 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,36 @@
"windows": "Alt+Shift+E"
},
"description": "Search tabs and bookmarks"
},
"toggle-rule-1": {
"description": "Toggle the rules assigned to shortcut 1"
},
"toggle-rule-2": {
"description": "Toggle the rules assigned to shortcut 2"
},
"toggle-rule-3": {
"description": "Toggle the rules assigned to shortcut 3"
},
"toggle-rule-4": {
"description": "Toggle the rules assigned to shortcut 4"
},
"toggle-rule-5": {
"description": "Toggle the rules assigned to shortcut 5"
},
"toggle-rule-6": {
"description": "Toggle the rules assigned to shortcut 6"
},
"toggle-rule-7": {
"description": "Toggle the rules assigned to shortcut 7"
},
"toggle-rule-8": {
"description": "Toggle the rules assigned to shortcut 8"
},
"toggle-rule-9": {
"description": "Toggle the rules assigned to shortcut 9"
},
"toggle-rule-10": {
"description": "Toggle the rules assigned to shortcut 10"
}
}
}
10 changes: 10 additions & 0 deletions src/Options.vue
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@ onMounted(async () => {

await rulesStore.init();

chrome.runtime.onMessage.addListener(onRuntimeMessage);

emitter.on(GLOBAL_EVENTS.NAVIGATE_TO_SETTINGS, () => {
onMenuClicked(sectionItems.find((item) => item.component === 'SettingsPane')!);
});
Expand All @@ -296,7 +298,15 @@ onMounted(async () => {

onUnmounted(() => {
document.removeEventListener('keydown', handleKeydown);
chrome.runtime.onMessage.removeListener(onRuntimeMessage);
});

// Rules toggled by keyboard shortcut: reload them so the list shows the new state
const onRuntimeMessage = (message: { action?: string }) => {
if (message?.action === 'rulesToggled') {
rulesStore.init();
}
};
</script>

<style scoped>
Expand Down
13 changes: 13 additions & 0 deletions src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { TabGroupsService } from './background/TabGroupsService';
import { TabHiveService } from './background/TabHiveService';
import { WindowService } from './background/WindowService';
import { ContextMenuService } from './background/ContextMenuService';
import { RuleShortcutService } from './background/RuleShortcutService';
import { SpotSearchService } from './background/SpotSearchService';

// Initialize services (Dependency Injection)
Expand All @@ -16,6 +17,7 @@ const tabGroupsService = new TabGroupsService();
const tabHiveService = new TabHiveService();
const windowService = new WindowService();
const contextMenuService = new ContextMenuService();
const ruleShortcutService = new RuleShortcutService();
const spotSearchService = new SpotSearchService();

// =============================================================================
Expand Down Expand Up @@ -379,6 +381,17 @@ chrome.storage.onChanged.addListener((changes, areaName) => {
chrome.commands.onCommand.addListener(async (command, tab) => {
console.log('[Tabee] 🔍 Command received:', command);

// toggle-rule-N: enable/disable the rules assigned to shortcut N
const shortcutSlot = ruleShortcutService.getSlotFromCommand(command);
if (shortcutSlot !== null) {
const enabled = await ruleShortcutService.toggleSlot(shortcutSlot);
await ruleShortcutService.showFeedback(enabled);
if (enabled !== null) {
await ruleShortcutService.propagateChange();
}
return;
}

if (command === 'merge-windows') {
await windowService.mergeAllWindows();
} else if (command === 'spot-search') {
Expand Down
82 changes: 82 additions & 0 deletions src/background/RuleShortcutService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { _getStorageAsync, _setStorage } from '../common/storage';
import { _isRuleEnabled } from '../common/helpers';
import { RULE_SHORTCUT_SLOTS } from '../common/types';

const BADGE_DURATION_MS = 2000;

/**
* Service responsible for toggling rules with keyboard shortcuts
* Users assign keys to the toggle-rule-N commands in chrome://extensions/shortcuts
*/
export class RuleShortcutService {
/**
* Returns the shortcut slot of a toggle-rule-N command, or null for other commands
*/
getSlotFromCommand(command: string): number | null {
const match = command.match(/^toggle-rule-(\d+)$/);
if (!match) return null;

const slot = Number(match[1]);
return slot >= 1 && slot <= RULE_SHORTCUT_SLOTS ? slot : null;
}

/**
* Toggles the rules assigned to a slot as one group:
* if any of them is enabled they are all disabled, otherwise they are all enabled
* @returns the new state, or null if no rule uses this slot
*/
async toggleSlot(slot: number): Promise<boolean | null> {
const tabModifier = await _getStorageAsync();
if (!tabModifier) return null;

const rules = tabModifier.rules.filter((rule) => rule.shortcut === slot);
if (rules.length === 0) return null;

const enable = !rules.some(_isRuleEnabled);
rules.forEach((rule) => {
rule.is_enabled = enable;
});

await _setStorage(tabModifier);

return enable;
}

/**
* Briefly shows the result on the toolbar icon: ON, OFF, or "–" when no rule uses the slot
*/
async showFeedback(enabled: boolean | null): Promise<void> {
const text = enabled === null ? '–' : enabled ? 'ON' : 'OFF';
const color = enabled === null ? '#ef4444' : enabled ? '#10b981' : '#6b7280';

await chrome.action.setBadgeBackgroundColor({ color });
await chrome.action.setBadgeText({ text });

setTimeout(() => {
chrome.action.setBadgeText({ text: '' });
}, BADGE_DURATION_MS);
}

/**
* Shows the change without a reload: open web pages re-apply their rules,
* and an open options page reloads its rule list
*/
async propagateChange(): Promise<void> {
chrome.runtime.sendMessage({ action: 'rulesToggled' }).catch(() => {
// No options page open
});

const tabs = await chrome.tabs.query({ url: ['http://*/*', 'https://*/*'] });

await Promise.all(
tabs.map(async (tab) => {
if (!tab.id) return;
try {
await chrome.tabs.sendMessage(tab.id, { action: 'reapplyRules' });
} catch {
// Content script not loaded in this tab (e.g. opened before the extension)
}
})
);
}
}
148 changes: 148 additions & 0 deletions src/background/__tests__/RuleShortcutService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { RuleShortcutService } from '../RuleShortcutService';
import { RULE_SHORTCUT_SLOTS, type Rule } from '../../common/types';
import manifest from '../../../manifest.json';

const mockChrome = {
action: {
setBadgeText: vi.fn(),
setBadgeBackgroundColor: vi.fn(),
},
tabs: {
query: vi.fn(),
sendMessage: vi.fn(),
},
runtime: {
sendMessage: vi.fn(),
},
};

vi.stubGlobal('chrome', mockChrome);

vi.mock('../../common/storage', () => ({
_getStorageAsync: vi.fn(),
_setStorage: vi.fn(),
}));

import { _getStorageAsync, _setStorage } from '../../common/storage';

const rule = (id: string, shortcut: number | null, is_enabled: boolean) =>
({ id, shortcut, is_enabled, tab: {} }) as unknown as Rule;

const storeWith = (rules: Rule[]) => {
const settings = { rules, groups: [], settings: {} };
vi.mocked(_getStorageAsync).mockResolvedValue(settings as any);
return settings;
};

describe('RuleShortcutService', () => {
let service: RuleShortcutService;

beforeEach(() => {
service = new RuleShortcutService();
vi.mocked(_setStorage).mockResolvedValue(undefined);
});

afterEach(() => {
vi.useRealTimers();
});

describe('getSlotFromCommand', () => {
it('returns the slot of toggle-rule-N commands', () => {
expect(service.getSlotFromCommand('toggle-rule-1')).toBe(1);
expect(service.getSlotFromCommand('toggle-rule-10')).toBe(10);
});

it('returns null for other commands and out-of-range slots', () => {
expect(service.getSlotFromCommand('spot-search')).toBeNull();
expect(service.getSlotFromCommand('toggle-rule-0')).toBeNull();
expect(service.getSlotFromCommand('toggle-rule-11')).toBeNull();
});

it('matches the commands declared in manifest.json', () => {
const slots = Object.keys(manifest.commands)
.map((command) => service.getSlotFromCommand(command))
.filter((slot) => slot !== null);

expect(slots).toEqual(Array.from({ length: RULE_SHORTCUT_SLOTS }, (_, i) => i + 1));
});
});

describe('toggleSlot', () => {
it('disables all rules of the slot when one of them is enabled', async () => {
const settings = storeWith([
rule('news', 1, true),
rule('blogs', 1, false),
rule('other', 2, true),
]);

expect(await service.toggleSlot(1)).toBe(false);
expect(settings.rules.map((r) => r.is_enabled)).toEqual([false, false, true]);
expect(_setStorage).toHaveBeenCalledWith(settings);
});

it('enables all rules of the slot when all are disabled', async () => {
const settings = storeWith([rule('news', 1, false), rule('blogs', 1, false)]);

expect(await service.toggleSlot(1)).toBe(true);
expect(settings.rules.map((r) => r.is_enabled)).toEqual([true, true]);
});

it('treats a rule without is_enabled as enabled', async () => {
const settings = storeWith([{ id: 'legacy', shortcut: 3, tab: {} } as unknown as Rule]);

expect(await service.toggleSlot(3)).toBe(false);
expect(settings.rules[0].is_enabled).toBe(false);
});

it('returns null and saves nothing when no rule uses the slot', async () => {
storeWith([rule('news', 1, true)]);

expect(await service.toggleSlot(5)).toBeNull();
expect(_setStorage).not.toHaveBeenCalled();
});
});

describe('showFeedback', () => {
it('shows ON / OFF / – on the badge, then clears it', async () => {
vi.useFakeTimers();

await service.showFeedback(true);
expect(mockChrome.action.setBadgeText).toHaveBeenLastCalledWith({ text: 'ON' });

await service.showFeedback(false);
expect(mockChrome.action.setBadgeText).toHaveBeenLastCalledWith({ text: 'OFF' });

await service.showFeedback(null);
expect(mockChrome.action.setBadgeText).toHaveBeenLastCalledWith({ text: '–' });

vi.advanceTimersByTime(2000);
expect(mockChrome.action.setBadgeText).toHaveBeenLastCalledWith({ text: '' });
});
});

describe('propagateChange', () => {
it('asks every web tab to re-apply its rules, ignoring tabs without content script', async () => {
mockChrome.runtime.sendMessage.mockResolvedValue(undefined);
mockChrome.tabs.query.mockResolvedValue([{ id: 1 }, { id: 2 }, {}]);
mockChrome.tabs.sendMessage
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new Error('Could not establish connection'));

await expect(service.propagateChange()).resolves.toBeUndefined();

expect(mockChrome.tabs.query).toHaveBeenCalledWith({ url: ['http://*/*', 'https://*/*'] });
expect(mockChrome.tabs.sendMessage).toHaveBeenCalledTimes(2);
expect(mockChrome.tabs.sendMessage).toHaveBeenCalledWith(1, { action: 'reapplyRules' });
});

it('tells an open options page to reload, and ignores it when none is open', async () => {
mockChrome.runtime.sendMessage.mockRejectedValue(new Error('Receiving end does not exist'));
mockChrome.tabs.query.mockResolvedValue([]);

await expect(service.propagateChange()).resolves.toBeUndefined();

expect(mockChrome.runtime.sendMessage).toHaveBeenCalledWith({ action: 'rulesToggled' });
});
});
});
7 changes: 7 additions & 0 deletions src/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,15 @@ export type Rule = {
url_fragment: string;
tab: Tab;
is_enabled: boolean;
// Keyboard shortcut slot (1 to RULE_SHORTCUT_SLOTS) that toggles this rule
shortcut?: number | null;
};

/**
* Number of "toggle-rule-N" commands declared in manifest.json
*/
export const RULE_SHORTCUT_SLOTS = 10;

export type Group = {
id: string;
title: string;
Expand Down
Loading
Loading