Compare commits

...

21 Commits
0.1.1 ... main

Author SHA1 Message Date
Bauke 7c948b67a7
Disable the complexity rule. 2023-11-13 19:21:26 +01:00
Bauke 3d884e09a5
Version 0.3.0! 2022-11-26 10:55:27 +01:00
Bauke 6aec65483e
Add sharing and importing usage details. 2022-11-26 10:45:50 +01:00
Bauke 119d476d5c
Move background color to a custom property so the :hover color cascades correctly. 2022-11-25 19:15:40 +01:00
Bauke 8432825c1e
Remove extra unicode character. 2022-11-23 14:43:04 +01:00
Bauke 42b5c3ece9
Add a share link button to the editor. 2022-11-23 14:14:35 +01:00
Bauke dbff19e2b9
Add a content script to insert the import button into the share page. 2022-11-23 14:14:17 +01:00
Bauke 87e4a28315
Add functionality to encode, decode and share redirects. 2022-11-23 14:13:17 +01:00
Bauke bb806cb561
Improve manual bypass check.
This makes it so http and https, and www and non-www links are the same.
2022-11-21 14:50:55 +01:00
Bauke 48a29eea71
Add a keyboard shortcut to toggle all redirects, default Alt+Shift+R. 2022-11-21 13:25:00 +01:00
Bauke 6bd5bccd6f
Factor toggling all redirects out to its own file. 2022-11-21 13:23:27 +01:00
Bauke 2acb8d804b
Automatically prefix 'https://' to redirected URLs if they fail parsing. 2022-11-21 12:43:56 +01:00
Bauke 6ab041df93
Add version 0.2.0 screenshot to readme. 2022-11-16 12:38:11 +01:00
Bauke cbf1f8e991
Version 0.2.0! 2022-11-16 12:27:01 +01:00
Bauke fd0149c13a
Add usage info for new features. 2022-11-16 12:26:40 +01:00
Bauke 9f414731b9
Move initialization to the bottom of the file. 2022-11-16 12:15:04 +01:00
Bauke a0a11e3647
Remove IDs from input and select elements. 2022-11-15 23:37:03 +01:00
Bauke 645e0e066a
Change the default redirect to hostname. 2022-11-15 12:59:03 +01:00
Bauke a05f54306a
Don't redirect when disabled. 2022-11-15 12:56:27 +01:00
Bauke cd453b3e6f
Add a context menu for toggling all redirects. 2022-11-15 12:46:10 +01:00
Bauke e5bf102aa3
Don't redirect if the current tab is already a redirectable URL. 2022-11-15 12:24:44 +01:00
24 changed files with 1555 additions and 65 deletions

View File

@ -6,7 +6,7 @@
[![Get Re-Nav for Chrome](./images/chrome-web-store.png)](https://chrome.google.com/webstore/detail/efjignaelidacjdhleaojfmkklganjjb)
[![Get Re-Nav for Edge](./images/microsoft.png)](https://microsoftedge.microsoft.com/addons/detail/efnkhmlaemggdlpalglioeolbbhfpiic)
![Latest Re-Nav screenshot](./images/re-nav-version-0-1-0.png)
![Latest Re-Nav screenshot](./images/re-nav-version-0-3-0.png)
## Installation

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 KiB

View File

@ -19,6 +19,7 @@
"@holllo/migration-helper": "^0.1.3",
"@holllo/preact-components": "^0.2.3",
"htm": "^3.1.1",
"js-base64": "^3.7.3",
"modern-normalize": "^1.1.0",
"preact": "^10.11.0",
"webextension-polyfill": "^0.10.0"
@ -78,6 +79,7 @@
"rules": {
"@typescript-eslint/consistent-type-definitions": "off",
"@typescript-eslint/consistent-type-imports": "off",
"complexity": "off",
"n/file-extension-in-import": "off",
"no-await-in-loop": "off"
},

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
import {toggleAllRedirects} from '../utilities/toggle-all-redirects.js';
export async function onCommandsHandler(command: string): Promise<void> {
if (command === 'toggleAllRedirects') {
await toggleAllRedirects();
}
}

View File

@ -0,0 +1,53 @@
import browser from 'webextension-polyfill';
import {toggleAllRedirects} from '../utilities/toggle-all-redirects.js';
type ContextMenu = browser.Menus.CreateCreatePropertiesType;
export function getContextMenus(): ContextMenu[] {
const actionContext =
import.meta.env.VITE_BROWSER === 'chromium' ? 'action' : 'browser_action';
const contextMenus: ContextMenu[] = [
{
id: 're-nav-toggle-redirects',
title: 'Toggle all redirects',
contexts: [actionContext],
},
];
return contextMenus;
}
export async function initializeContextMenus(): Promise<void> {
const contextMenus = getContextMenus();
await browser.contextMenus.removeAll();
for (const contextMenu of contextMenus) {
browser.contextMenus.create(contextMenu, contextCreated);
}
}
function contextCreated(): void {
const error = browser.runtime.lastError;
if (error !== null && error !== undefined) {
console.error('Re-Nav', error.message);
}
}
export async function contextClicked(
contextMenuIds: Set<string>,
info: browser.Menus.OnClickData,
tab?: browser.Tabs.Tab,
): Promise<void> {
const id = info.menuItemId.toString();
if (!contextMenuIds.has(id)) {
return;
}
if (id === 're-nav-toggle-redirects') {
await toggleAllRedirects();
}
}

View File

@ -1,24 +1,39 @@
import browser from 'webextension-polyfill';
import storage from '../redirect/storage.js';
import {updateBadge} from '../utilities/badge.js';
import {onCommandsHandler} from './commands.js';
import {
contextClicked,
getContextMenus,
initializeContextMenus,
} from './context-menus.js';
async function browserActionClicked() {
await browser.runtime.openOptionsPage();
}
if (import.meta.env.VITE_BROWSER === 'chromium') {
browser.action.onClicked.addListener(browserActionClicked);
} else {
browser.browserAction.onClicked.addListener(browserActionClicked);
}
browser.runtime.onInstalled.addListener(async () => {
await initializeContextMenus();
await updateBadge();
if (import.meta.env.DEV) {
await browser.runtime.openOptionsPage();
}
});
browser.runtime.onStartup.addListener(async () => {
await updateBadge();
});
browser.webNavigation.onBeforeNavigate.addListener(async (details) => {
const {redirectsEnabled} = await browser.storage.local.get({
redirectsEnabled: true,
});
if (redirectsEnabled === false) {
return;
}
if (!details.url.startsWith('http') || details.frameId > 0) {
return;
}
@ -29,9 +44,37 @@ browser.webNavigation.onBeforeNavigate.addListener(async (details) => {
return;
}
const tab = await browser.tabs.query({active: true, lastFocusedWindow: true});
const currentTabUrl =
tab[0]?.url === undefined ? undefined : new URL(tab[0].url);
const url = new URL(details.url);
const {latestUrl} = await browser.storage.local.get('latestUrl');
if (redirectDelta < 30_000 && url.href === latestUrl) {
// The undefined.local URL will only be used if no redirects have happened yet.
const {latestUrl: savedLatestUrl} = await browser.storage.local.get({
latestUrl: 'https://undefined.local',
});
const latestUrl = new URL(savedLatestUrl);
// Set the latest URL protocol to always be the same as the current. Since
// only HTTP URLs are checked here, for us HTTP and HTTPS are equivalent.
latestUrl.protocol = url.protocol;
const currentUrlWwwPrefix = url.hostname.startsWith('www.');
const latestUrlWwwPrefix = latestUrl.hostname.startsWith('www.');
if (currentUrlWwwPrefix && !latestUrlWwwPrefix) {
// Then if the current URL is a `www.` URL and the latest one isn't, prefix it
// to the latest URL. This helps the manual bypass check.
latestUrl.hostname = `www.${latestUrl.hostname}`;
} else if (!currentUrlWwwPrefix && latestUrlWwwPrefix) {
// Remove `www.` if the latestUrl starts with it but the current URL doesn't.
latestUrl.hostname = latestUrl.hostname.slice(4);
}
// Manually bypass any redirects if the latest redirected and current URLs are
// the same.
if (redirectDelta < 30_000 && url.href === latestUrl.href) {
return;
}
@ -41,7 +84,25 @@ browser.webNavigation.onBeforeNavigate.addListener(async (details) => {
}
if (redirect.isMatch(url)) {
const redirectedUrl = redirect.redirect(url);
// Don't redirect if the URL before going to a new page is also a match.
// This will happen when the user is already on a website that has a
// redirect, but for whatever reason hasn't redirected. So it's safe to
// assume that they want to stay on this website, rather than get
// redirected.
if (currentTabUrl !== undefined && redirect.isMatch(currentTabUrl)) {
break;
}
let redirectedUrl = redirect.redirect(url);
if (typeof redirectedUrl === 'string') {
try {
redirectedUrl = new URL(redirectedUrl);
} catch {
redirectedUrl = `https://${redirectedUrl as string}`;
redirectedUrl = new URL(redirectedUrl);
}
}
await browser.tabs.update(details.tabId, {url: redirectedUrl.href});
await browser.storage.local.set({
latestTime: Date.now(),
@ -51,3 +112,21 @@ browser.webNavigation.onBeforeNavigate.addListener(async (details) => {
}
}
});
browser.contextMenus.onClicked.addListener(async (info, tab) => {
const contextMenus = getContextMenus();
const contextMenuIds = new Set<string>(
contextMenus.map(({id}) => id ?? 're-nav-unknown'),
);
await contextClicked(contextMenuIds, info, tab);
});
browser.commands.onCommand.addListener(onCommandsHandler);
if (import.meta.env.VITE_BROWSER === 'chromium') {
browser.action.onClicked.addListener(browserActionClicked);
} else {
browser.browserAction.onClicked.addListener(browserActionClicked);
void initializeContextMenus();
}

View File

@ -0,0 +1,104 @@
import './style.scss';
import browser from 'webextension-polyfill';
import {Component, render} from 'preact';
import {html} from 'htm/preact';
import {decodeBase64, fragmentPrefix} from '../../utilities/share-redirect.js';
import {
RedirectParameters,
parseRedirect,
narrowMatcherType,
narrowRedirectType,
} from '../../redirect/exports.js';
import storage from '../../redirect/storage.js';
type Props = Record<string, unknown>;
type State = {
error: string | undefined;
imported: boolean;
};
class ImportButton extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
error: undefined,
imported: false,
};
}
importRedirect = async () => {
const decoded = decodeBase64<RedirectParameters>(
location.hash.slice(fragmentPrefix.length),
);
const invalidRedirectError = "This isn't a valid redirect. ☹";
if (
!narrowMatcherType(decoded.matcherType) ||
!narrowRedirectType(decoded.redirectType) ||
typeof decoded.matcherValue !== 'string' ||
typeof decoded.redirectValue !== 'string'
) {
this.setState({error: invalidRedirectError});
return;
}
const redirect = parseRedirect({
id: -1,
enabled: true,
matcherType: decoded.matcherType,
matcherValue: decoded.matcherValue,
redirectType: decoded.redirectType,
redirectValue: decoded.redirectValue,
});
if (redirect === undefined) {
this.setState({error: invalidRedirectError});
return;
}
const id = await storage.nextRedirectId();
redirect.parameters.id = id;
await storage.save(redirect);
this.setState({imported: true});
};
render() {
const {error, imported} = this.state;
if (error !== undefined) {
return html`<p>${error}</p>`;
}
if (imported) {
return html`
<p class="import-success">The redirect has been imported!</p>
`;
}
return html`
<button class="import-button" onClick=${this.importRedirect}>
Import
</button>
`;
}
}
function main() {
if (!location.hash.startsWith(fragmentPrefix)) {
return;
}
const importRoot = document.querySelector('.re-nav-import')!;
for (const child of Array.from(importRoot.children)) {
child.remove();
}
render(html`<${ImportButton} />`, importRoot);
}
main();

View File

@ -0,0 +1,20 @@
.re-nav-import {
text-align: center;
}
.import-button {
background-color: var(--da-4);
border: none;
color: var(--background-1);
cursor: pointer;
font-weight: bold;
padding: var(--spacing-08) var(--spacing-32);
&:hover {
background-color: var(--foreground-1);
}
}
.import-success {
margin-bottom: var(--spacing-16);
}

View File

@ -6,12 +6,29 @@ export default function createManifest(
const manifest: Record<string, unknown> = {
name: 'Re-Nav',
description: 'Navigation redirects for the masses.',
version: '0.1.1',
permissions: ['storage', 'webNavigation'],
version: '0.3.0',
permissions: ['contextMenus', 'storage', 'tabs', 'webNavigation'],
options_ui: {
page: 'options/index.html',
open_in_tab: true,
},
commands: {
toggleAllRedirects: {
description:
"Toggle all redirects, this does the same as the extension icon's right-click option.",
suggested_key: {
default: 'Alt+Shift+R',
},
},
},
content_scripts: [
{
css: ['generated:content-scripts/share/style.css'],
js: ['content-scripts/share/share.ts'],
matches: ['https://holllo.org/re-nav/share/'],
run_at: 'document_end',
},
],
};
const icons = {

View File

@ -1,4 +1,4 @@
import {ConfirmButton} from '@holllo/preact-components';
import {ConfirmButton, FeedbackButton} from '@holllo/preact-components';
import {html} from 'htm/preact';
import {Component} from 'preact';
import browser from 'webextension-polyfill';
@ -13,6 +13,7 @@ import {
redirectTypes,
} from '../../redirect/exports.js';
import storage from '../../redirect/storage.js';
import {share} from '../../utilities/share-redirect.js';
type Props = {
redirect: Redirect;
@ -124,6 +125,11 @@ export default class Editor extends Component<Props, State> {
this.setState({enabled});
};
copyShareLink = async () => {
const link = share(this.state);
await navigator.clipboard.writeText(link);
};
render() {
const {
enabled,
@ -145,7 +151,6 @@ export default class Editor extends Component<Props, State> {
<div class="editor ${hasBeenEdited ? 'has-been-edited' : ''}">
<select
class="select"
id="matcher-type"
title="Matcher Type"
value=${matcherType}
onChange=${this.onMatcherTypeChange}
@ -155,7 +160,6 @@ export default class Editor extends Component<Props, State> {
<input
class="input"
id="matcher-value"
onInput=${this.onMatcherInput}
placeholder="Matcher Value"
title="Matcher Value"
@ -166,7 +170,6 @@ export default class Editor extends Component<Props, State> {
<select
class="select"
id="redirect-type"
title="Redirect Type"
value=${redirectType}
onChange=${this.onRedirectTypeChange}
@ -176,7 +179,6 @@ export default class Editor extends Component<Props, State> {
<input
class="input"
id="redirect-value"
onInput=${this.onRedirectInput}
placeholder="Redirect Value"
title="Redirect Value"
@ -202,6 +204,13 @@ export default class Editor extends Component<Props, State> {
>
${enabled ? '●' : '○'}
</button>
<${FeedbackButton}
attributes=${{class: 'button share', title: 'Copy share link'}}
click=${this.copyShareLink}
feedbackText="💖"
text="📋"
timeout=${5 * 1000}
/>
</div>
`;
}

View File

@ -68,7 +68,7 @@ export class PageMain extends Component<Props, State> {
id: await storage.nextRedirectId(),
matcherType: 'hostname',
matcherValue: 'example.com',
redirectType: 'simple',
redirectType: 'hostname',
redirectValue: 'example.org',
});
await storage.savePrepared(await storage.prepareForStorage(redirect));

View File

@ -41,9 +41,27 @@ export default class Usage extends Component {
To enable or disable a redirect, click the button with the circle.
If it's filled in the redirect is enabled.
</li>
<li>
You can also toggle redirecting entirely by right-clicking the
extension icon and clicking "Toggle all redirects". This will show a
next to the extension icon indicating Re-Nav is turned off.
</li>
<li>To remove a redirect click the red button with the twice.</li>
</ul>
<p>Sharing & importing redirects:</p>
<ul>
<li>
To share a redirect, click on the button with the clipboard 📋 icon.
This will copy a link that you can share around.
</li>
<li>
When you or someone else heads to a share link, it will show the
redirect's details and if they have Re-Nav installed it will create
an import button on the page.
</li>
</li>
<p>Some miscellaneous notes:</p>
<ul>
<li>Only URLs starting with "http" will be checked.</li>
@ -57,6 +75,11 @@ export default class Usage extends Component {
have to disable redirects in the options page whenever you don't
want to be redirected.
</li>
<li>
If your currently active tab is a website that has a redirect
associated with it, then redirects for that website won't happen
when you click on links or open new tabs from there.
</li>
</ul>
<p>As a quick-start you can also insert the examples from below:</p>

View File

@ -25,11 +25,15 @@
padding: 0;
&.enabled {
background-color: var(--da-4);
--button-background-color: var(--da-4);
}
&.disabled {
background-color: var(--da-2);
--button-background-color: var(--da-2);
}
&.share {
--button-background-color: var(--da-7);
}
}

View File

@ -8,7 +8,7 @@
margin-bottom: 16px;
.button {
background-color: var(--da-3);
background-color: var(--button-background-color, var(--da-3));
border: none;
color: var(--db-1);
cursor: pointer;

View File

@ -48,5 +48,5 @@ export abstract class Redirect {
return false;
}
public abstract redirect(url: URL | string): URL;
public abstract redirect(url: URL | string): URL | string;
}

View File

@ -8,7 +8,7 @@ export * from './hostname.js';
export * from './regex.js';
export * from './simple.js';
export type Redirects = HostnameRedirect | SimpleRedirect;
export type Redirects = HostnameRedirect | RegexRedirect | SimpleRedirect;
export function parseRedirect(
parameters: RedirectParameters,

View File

@ -1,9 +1,9 @@
import {Redirect} from './base.js';
export class RegexRedirect extends Redirect {
public redirect(redirect: URL | string): URL {
public redirect(redirect: URL | string): string {
const url = redirect instanceof URL ? redirect.href : redirect;
const regex = new RegExp(this.parameters.matcherValue, 'gi');
return new URL(url.replace(regex, this.parameters.redirectValue));
return url.replace(regex, this.parameters.redirectValue);
}
}

View File

@ -1,7 +1,7 @@
import {Redirect} from './base.js';
export class SimpleRedirect extends Redirect {
public redirect(): URL {
return new URL(this.parameters.redirectValue);
public redirect(): string {
return this.parameters.redirectValue;
}
}

25
source/utilities/badge.ts Normal file
View File

@ -0,0 +1,25 @@
import browser from 'webextension-polyfill';
export async function updateBadge(redirectsEnabled?: boolean): Promise<void> {
if (redirectsEnabled === undefined) {
const state = await browser.storage.local.get({redirectsEnabled: true});
redirectsEnabled = state.redirectsEnabled as boolean;
}
let action: browser.Action.Static = browser.browserAction;
if (import.meta.env.VITE_BROWSER === 'chromium') {
action = browser.action;
}
await action.setBadgeText({
text: redirectsEnabled ? '' : '✗',
});
await action.setBadgeBackgroundColor({
color: '#f99fb1',
});
if (import.meta.env.VITE_BROWSER === 'firefox') {
action.setBadgeTextColor({color: '#2a2041'});
}
}

View File

@ -0,0 +1,28 @@
import {Base64} from 'js-base64';
import {RedirectParameters} from '../redirect/exports.js';
export const fragmentPrefix = '#json=';
export function decodeBase64<T>(base64: string): T {
return JSON.parse(Base64.decode(base64)) as T;
}
export function encodeBase64(source: any): string {
return Base64.encode(JSON.stringify(source), true);
}
export function share(redirect: RedirectParameters): string {
const url = new URL('https://holllo.org/re-nav/share/');
const encoded = encodeBase64({
matcherType: redirect.matcherType,
matcherValue: redirect.matcherValue,
redirectType: redirect.redirectType,
redirectValue: redirect.redirectValue,
});
url.hash = `${fragmentPrefix}${encoded}`;
return url.href;
}

View File

@ -0,0 +1,10 @@
import browser from 'webextension-polyfill';
import {updateBadge} from './badge.js';
export async function toggleAllRedirects() {
const state = await browser.storage.local.get({redirectsEnabled: true});
const redirectsEnabled = !(state.redirectsEnabled as boolean);
await browser.storage.local.set({redirectsEnabled});
await updateBadge(redirectsEnabled);
}

View File

@ -84,7 +84,7 @@ test('Redirect.redirect', (t) => {
t.snapshot(
{
original: url instanceof URL ? url.href : url,
redirected: redirect.redirect(url).href,
redirected: new URL(redirect.redirect(url)).href,
},
`${index} ${redirect.constructor.name}`,
);