Skip to content

Commit

Permalink
feat: add context menus
Browse files Browse the repository at this point in the history
  • Loading branch information
AXeL-dev committed Mar 9, 2022
1 parent f05c09c commit 654e251
Show file tree
Hide file tree
Showing 11 changed files with 259 additions and 31 deletions.
12 changes: 12 additions & 0 deletions public/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -423,5 +423,17 @@
},
"timerCompleted": {
"message": "Timer completed!"
},
"blockCurrentDomain": {
"message": "Block the current domain name"
},
"blockCurrentUrl": {
"message": "Block the current url"
},
"blacklistSettings": {
"message": "Settings > Blacklist"
},
"whitelistSettings": {
"message": "Settings > Whitelist"
}
}
12 changes: 12 additions & 0 deletions public/_locales/fr/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -423,5 +423,17 @@
},
"timerCompleted": {
"message": "Minuteur terminé!"
},
"blockCurrentDomain": {
"message": "Bloquer le nom de domaine courant"
},
"blockCurrentUrl": {
"message": "Bloquer l'url courante"
},
"blacklistSettings": {
"message": "Réglages > Liste noire"
},
"whitelistSettings": {
"message": "Réglages > Liste blanche"
}
}
12 changes: 12 additions & 0 deletions public/_locales/nl/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -423,5 +423,17 @@
},
"timerCompleted": {
"message": "Timer voltooid!"
},
"blockCurrentDomain": {
"message": "Blokkeer de huidige domeinnaam"
},
"blockCurrentUrl": {
"message": "Blokkeer de huidige url"
},
"blacklistSettings": {
"message": "Instellingen > Zwarte lijst"
},
"whitelistSettings": {
"message": "Instellingen > Witte lijst"
}
}
3 changes: 2 additions & 1 deletion public/manifest.firefox.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"https://*/*",
"webRequest",
"webRequestBlocking",
"<all_urls>"
"<all_urls>",
"contextMenus"
]
}
3 changes: 2 additions & 1 deletion public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"https://*/*",
"webRequest",
"webRequestBlocking",
"<all_urls>"
"<all_urls>",
"contextMenus"
]
}
9 changes: 7 additions & 2 deletions src/components/AddWebsitePrompt/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export class AddWebsitePrompt extends Component {
super(props);
const params = props.location ? queryString.parse(props.location.search) : {};
this.mode = params.mode || Mode.blacklist;
this.tabId = +params.tabId || null;
this.state = {
url: params.url || '',
disabled: false,
Expand Down Expand Up @@ -43,8 +44,12 @@ export class AddWebsitePrompt extends Component {
} else {
this.setState({ disabled: true });
try {
await blockUrl(this.state.url, this.mode);
window.close();
const blocked = await blockUrl(this.state.url, this.mode, this.tabId);
if (blocked) {
window.close();
} else {
throw new Error(translate('urlAlreadyExists'));
}
} catch (error) {
toaster.danger(error.message, { id: 'add-website-toaster' });
this.setState({ disabled: false });
Expand Down
160 changes: 154 additions & 6 deletions src/components/Background/index.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import React, { Component } from 'react';
import { storage, nativeAPI, indexUrl, getTab, sendNotification } from 'helpers/webext';
import {
storage,
nativeAPI,
indexUrl,
getTab,
sendNotification,
openExtensionPage,
getActiveTab,
} from 'helpers/webext';
import {
Mode,
Action,
Expand All @@ -11,6 +19,8 @@ import {
defaultMode,
defaultAction,
defaultIsEnabled,
addCurrentWebsite,
addCurrentUrl,
} from 'helpers/block';
import { defaultSchedule, getTodaySchedule, isScheduleAllowed } from 'helpers/schedule';
import { hasValidProtocol, getValidUrl, getHostName } from 'helpers/url';
Expand All @@ -20,6 +30,39 @@ import { defaultTimerSettings, unactiveTimerRuntimeSettings } from 'helpers/time
import { now } from 'helpers/date';
import { translate } from 'helpers/i18n';

const contextMenus = [
{
title: translate('blockCurrentDomain'),
id: 'block_current_domain',
enabled: false,
contexts: ['page'],
},
{
title: translate('blockCurrentUrl'),
id: 'block_current_url',
enabled: false,
contexts: ['page'],
},
{
title: translate('settings'),
id: 'settings',
enabled: true,
contexts: ['page'],
},
{
title: translate('blacklistSettings'),
id: 'blacklist_settings',
enabled: true,
contexts: ['page'],
},
{
title: translate('whitelistSettings'),
id: 'whitelist_settings',
enabled: true,
contexts: ['page'],
},
];

export class Background extends Component {
constructor(props) {
super(props);
Expand All @@ -40,6 +83,9 @@ export class Background extends Component {
this.hasBeenEnabledOnStartup = false;
this.tmpAllowed = [];
this.timerTimeout = null;
this.contextMenusSettings = {
ignoreNextTabEvents: false,
};

this.init();
}
Expand Down Expand Up @@ -93,8 +139,11 @@ export class Background extends Component {
return this.isEnabled;
};

setBlacklist = (blist) => {
setBlacklist = (blist, tabId = null) => {
this.blacklist = transformList(blist);
if (tabId && this.isEnabled) {
this.checkTabById(tabId, 'setBlacklist');
}
};

getBlacklist = () => {
Expand All @@ -117,8 +166,11 @@ export class Background extends Component {
return this.whitelistKeywords;
};

setWhitelist = (wlist) => {
setWhitelist = (wlist, tabId = null) => {
this.whitelist = transformList(wlist);
if (tabId && this.isEnabled) {
this.checkTabById(tabId, 'setWhitelist');
}
};

getWhitelist = () => {
Expand Down Expand Up @@ -226,8 +278,8 @@ export class Background extends Component {
this.unblock = { ...this.unblock, ...items.unblock }; // merge
this.schedule = {
...this.schedule,
...(!items.schedule.time ? items.schedule : {}),
}; // omit old schedule settings in version <= 2.3.0
...(!items.schedule.time ? items.schedule : {}), // omit old schedule settings in version <= 2.3.0
};
this.redirectUrl = getValidUrl(items.redirectUrl);
this.enableLogs = items.enableLogs;
logger.maxLength = items.logsLength;
Expand All @@ -243,6 +295,44 @@ export class Background extends Component {
});
browser.runtime.onStartup.addListener(this.onBrowserStartup);
browser.runtime.onMessage.addListener(this.handleMessage);
browser.contextMenus.onClicked.addListener(this.handleContextMenusClick);
this.initContextMenus();
};

initContextMenus = async () => {
const activeTab = await getActiveTab();
for (const menu of contextMenus) {
browser.contextMenus.create({
...menu,
enabled: this.isContextMenuEnablable(menu, activeTab),
});
}
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
if (this.contextMenusSettings.ignoreNextTabEvents) {
this.contextMenusSettings.ignoreNextTabEvents = false;
} else {
this.updateContextMenus(tab);
}
}
});
browser.tabs.onReplaced.addListener((addedTabId, removedTabId) => {
browser.tabs.get(addedTabId).then((tab) => {
if (tab) {
this.updateContextMenus(tab);
}
});
});
browser.tabs.onActivated.addListener((activeInfo) => {
if (this.contextMenusSettings.ignoreNextTabEvents) {
return;
}
browser.tabs.get(activeInfo.tabId).then((tab) => {
if (tab) {
this.updateContextMenus(tab);
}
});
});
};

updateIcon = () => {
Expand Down Expand Up @@ -319,6 +409,53 @@ export class Background extends Component {
});
};

handleContextMenusClick = (info, tab) => {
switch (info.menuItemId) {
case 'block_current_domain':
this.contextMenusSettings.ignoreNextTabEvents = true;
addCurrentWebsite(this.mode, true, tab.id);
break;
case 'block_current_url':
this.contextMenusSettings.ignoreNextTabEvents = true;
addCurrentUrl(this.mode, true, tab.id);
break;
case 'settings':
openExtensionPage('/settings');
break;
case 'blacklist_settings':
openExtensionPage('/settings?tab=blacklist');
break;
case 'whitelist_settings':
openExtensionPage('/settings?tab=whitelist');
break;
default:
this.debug('unknown context menu action:', info, tab);
break;
}
};

isContextMenuEnablable = (menu, tab) => {
switch (menu.id) {
case 'block_current_domain':
case 'block_current_url':
return tab ? isAccessible(tab.url) : false;
default:
return true;
}
};

updateContextMenus = (tab) => {
for (const menu of contextMenus) {
try {
browser.contextMenus.update(menu.id, {
enabled: this.isContextMenuEnablable(menu, tab),
});
} catch (error) {
this.debug(error);
}
}
};

unblockTab = (tabId, url, timeout) => {
if (timeout > 0) {
this.tmpAllowed.push({
Expand Down Expand Up @@ -580,7 +717,11 @@ export class Background extends Component {
};

onUpdatedHandler = (tabId, changeInfo, tab) => {
if (changeInfo.url && hasValidProtocol(changeInfo.url)) {
if (
changeInfo.status === 'loading' &&
changeInfo.url &&
hasValidProtocol(changeInfo.url)
) {
this.checkTab({ ...changeInfo, tabId: tabId }, 'onUpdatedHandler');
}
};
Expand All @@ -600,6 +741,13 @@ export class Background extends Component {
}
};

checkTabById = async (tabId, caller) => {
const tab = await getTab(tabId);
if (tab) {
this.checkTab({ url: tab.url, tabId }, caller);
}
};

enableEventListeners = () => {
browser.webRequest.onBeforeRequest.addListener(
this.onBeforeRequestHandler,
Expand Down
8 changes: 3 additions & 5 deletions src/components/Settings/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,11 @@ export class Settings extends Component {
blacklistKeywords: [],
whitelistKeywords: [],
})
.then(async (items) => {
.then((items) => {
if (items) {
// Update state
this.setOptions({
isEnabled: items.isEnabled || (await sendMessage('getIsEnabled')),
isEnabled: items.isEnabled,
mode: items.mode,
action: items.action,
blockTab: {
Expand Down Expand Up @@ -375,9 +375,7 @@ export class Settings extends Component {

openPage = (page) => {
if (isWebExtension) {
openExtensionPage(page, {
closeCurrent: false,
});
openExtensionPage(page);
} else {
window.open(`#${page}`, '_blank');
}
Expand Down
4 changes: 3 additions & 1 deletion src/components/shared/SettingsButton/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { IconButton } from 'components';
export class SettingsButton extends Component {
goToSettings = () => {
if (isWebExtension) {
openExtensionPage('/settings');
openExtensionPage('/settings', {
closeCurrent: true,
});
} else {
this.props.history.push('/settings');
}
Expand Down
Loading

0 comments on commit 654e251

Please sign in to comment.