Skip to content

Commit

Permalink
docs: adds some documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
nobkd committed Apr 28, 2023
1 parent 3747239 commit faa7327
Show file tree
Hide file tree
Showing 10 changed files with 128 additions and 13 deletions.
3 changes: 3 additions & 0 deletions src/bg/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { matcher, runtimeMapUrl } from './bg';

const replacedUrlMatcher = new RegExp(`^${runtimeMapUrl}\?`);

/**
*
*/
browserAction.onClicked.addListener(async (tab: Tabs.Tab) => {
if (!tab.url || !tab.id) return;

Expand Down
10 changes: 9 additions & 1 deletion src/bg/bg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ export const matcher: RegExp = new RegExp(
);
export const runtimeMapUrl = runtime.getURL('map.html');

/**
* Checks if `frames` send a request to Maps.
* If they do and the extension isn't disabled for the current site, then the request is redirected to the extension leaflet map with all URL search params.
* Else the request is'nt blocked.
* @param req Web Request from frame
* @returns Redirect to extension map or pass through if extension disabled for website
*/
function redirect(req: WebRequest.OnBeforeRequestDetailsType): WebRequest.BlockingResponse {
// TODO: check if originUrl always matches current tab url -> e.g. in frames with subframes
if (req.originUrl && req.url.match(matcher)) {
Expand All @@ -22,6 +29,7 @@ function redirect(req: WebRequest.OnBeforeRequestDetailsType): WebRequest.Blocki
return {};
}

// Listens to web requests from frames, redirects when fitting `matcher`
webRequest.onBeforeRequest.addListener(
redirect,
{
Expand All @@ -40,5 +48,5 @@ tabs.onActivated.addListener(updateActiveTabIcon);
// listen for window switching
windows.onFocusChanged.addListener(updateActiveTabIcon);

// run at startup
// update icon at startup
updateActiveTabIcon();
7 changes: 7 additions & 0 deletions src/bg/utils/actionIcon.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { browserAction, tabs } from 'webextension-polyfill';
import { disabledHosts, getHostname } from './storage';

/**
*
* @param hostname
*/
export function updateIcon(hostname: string) {
let disabled = disabledHosts.includes(hostname);

Expand All @@ -17,6 +21,9 @@ export function updateIcon(hostname: string) {
});
}

/**
*
*/
export async function updateActiveTabIcon() {
let browserTabs = await tabs.query({ active: true, currentWindow: true });

Expand Down
1 change: 1 addition & 0 deletions src/bg/utils/domainEnds.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Domain ends of google
export const domainEnds: string[] = [
'com',
'ac',
Expand Down
14 changes: 14 additions & 0 deletions src/bg/utils/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,26 @@ import { updateIcon } from './actionIcon';

export const KEY_DISABLED_HOSTS = 'disabled_hosts';

//
export let disabledHosts: string[] = await getDisabledHosts();
storage.local.onChanged.addListener((changes) => {
if (KEY_DISABLED_HOSTS in changes) {
disabledHosts = changes[KEY_DISABLED_HOSTS].newValue ?? [];
}
});

/**
*
* @returns
*/
async function getDisabledHosts(): Promise<string[]> {
return (await storage.local.get(KEY_DISABLED_HOSTS))[KEY_DISABLED_HOSTS] ?? [];
}

/**
*
* @param hostname
*/
export async function invertHostState(hostname: string): Promise<void> {
if (disabledHosts.includes(hostname)) {
disabledHosts.splice(disabledHosts.indexOf(hostname), 1);
Expand All @@ -28,6 +37,11 @@ export async function invertHostState(hostname: string): Promise<void> {
updateIcon(hostname);
}

/**
*
* @param url
* @returns
*/
export function getHostname(url: string): string {
url = url.replace(/^\w+:\/\//, '');
url = url.split(/[\/#\?]/, 1)[0];
Expand Down
19 changes: 14 additions & 5 deletions src/map/utils/parseDMS.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
/**
* Converts DMS coordinates to Lat and Lon
* @param input String containing DMS coordinates
* @returns Array containing Latitude and Longitude
*/
export function parseDMS(input: string): [number, number] {
let parts: string[] = input.split(/[^\d\w\.]+/);
let lat = convertDMSToDD(parts.slice(0, 4));
let lng = convertDMSToDD(parts.slice(4));
let lon = convertDMSToDD(parts.slice(4));

return [lat, lng];
return [lat, lon];
}

function convertDMSToDD(dmsd: string[]): number {
const [degrees, minutes, seconds, direction] = dmsd;
/**
* Converts DMS part to Lat/Lon
* @param dms Array of four strings representing: Degree Minutes Seconds Direction
* @returns DMS part converted to Latitude / Longitude
*/
function convertDMSToDD(dms: string[]): number {
const [degrees, minutes, seconds, direction] = dms;
let dd = Number(degrees) + Number(minutes) / 60 + Number(seconds) / (60 * 60);

if (direction === 'S' || direction === 'W') {
Expand Down
41 changes: 41 additions & 0 deletions src/map/utils/parsePB.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
export type TileType = 'roadmap' | 'satellite';
export const tileTypes: TileType[] = ['roadmap', 'satellite'];

/**
* Takes one bang operator and decodes it.
*
* Possible types are:
* - `s`: string
* - `v`: timestamp => keep as string
* - `b`: boolean? / byte? => keep as string
* - `f`: float
* - `d`: double
* - `i`: int
* - `m`: matrix => length as int
* - `e`: enum
* - `z`: base64 encoded coordinates => Degrees Minutes Seconds Direction
*
* Unknown types are kept as string.
*
* @param item One bang operator with the structure: position, one character (data type), encoded data
* @returns Array of two items. First is the decoded result. Second describes if the result is a new matrix.
*/
function convertType(item: string): [string | TileType | number, boolean] {
item = item.replace(/^\d+/, '');
const type: string = item.charAt(0);
Expand Down Expand Up @@ -29,6 +48,28 @@ function convertType(item: string): [string | TileType | number, boolean] {
return [val, type === 'm'];
}

/**
* Half iterative half recursive function that converts an array of split hashbangs and converts it into a fitting representation.
* Multiple nested arrays possible.
*
* Example input:
* ```ts
* TODO: ['', '', '']
* ```
*
* Example result:
* ```ts
* TODO:
* ```
*
* References:
* - https://andrewwhitby.com/2014/09/09/google-maps-new-embed-format/
* - https://blog.themillhousegroup.com/2016/08/deep-diving-into-google-pb-embedded-map.html
* - https://stackoverflow.com/a/47042514
* @param items Bang operators (e.g. `!1m13`) split into pieces at `!`
* @param out Array for top and recursion levels to save results and return
* @returns Filled `out` array with bang operators converted into readable format
*/
export function parsePB(items: string[], out: any[] = []): any[] {
let i = 0;
while (i < items.length) {
Expand Down
20 changes: 13 additions & 7 deletions src/map/utils/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ export type MapData = {
markers?: Marker[];
};

/**
*
* @param param
* @returns
*/
export async function readPB(param: string): Promise<MapData> {
// https://andrewwhitby.com/2014/09/09/google-maps-new-embed-format/
// https://blog.themillhousegroup.com/2016/08/deep-diving-into-google-pb-embedded-map.html
// https://stackoverflow.com/a/47042514

let mapData: MapData = {
markers: [],
};
Expand All @@ -47,7 +48,7 @@ export async function readPB(param: string): Promise<MapData> {
if (typeof currMarkers !== 'string') {
for (let markers of currMarkers[0] as string[]) {
if (markers.match(cidMatch)) {
// cid
// TODO: understand CID
console.log(markers);
} else if (markers.match(dmsMatch)) {
let [lat, lon] = parseDMS(markers);
Expand All @@ -74,9 +75,14 @@ export async function readPB(param: string): Promise<MapData> {
return mapData;
}

/**
* Makes a request to the Nominatim API to get the coordinates of an address
*
* Reference: https://medium.com/@sowmyaaji/how-to-build-a-backend-with-jquery-and-add-a-leaflet-js-frontend-e77f2079c852
* @param addr An address or place
* @returns The Latitude and Logitude of the address or place
*/
export async function readQ(addr: string): Promise<Marker | null> {
// https://medium.com/@sowmyaaji/how-to-build-a-backend-with-jquery-and-add-a-leaflet-js-frontend-e77f2079c852

let uri = encodeURI(nominatimQ + addr);
let res = await fetch(uri);

Expand Down
5 changes: 5 additions & 0 deletions src/map/utils/zoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
const factor: number = 35200000;
const precision: number = 10;

/**
*
* @param alt
* @returns
*/
export function getMapZoom(alt: number): number {
let zoom = Math.log2(factor / alt) * 1.225;
zoom = Math.round((zoom + Number.EPSILON) * precision) / precision;
Expand Down
21 changes: 21 additions & 0 deletions src/options/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ import {

const table = document.querySelector('.table')!;

/**
*
*/
function buildEntries() {
table.innerHTML = '';
disabledHosts.forEach(createEntry);
}

/**
*
* @returns
*/
async function addEntry() {
const search = new URLSearchParams(document.location.search);
let hostname = search.get('hostname');
Expand All @@ -25,6 +32,10 @@ async function addEntry() {
createEntry(hostname);
}

/**
*
* @param hostname
*/
function createEntry(hostname: string) {
const div = document.createElement('div');

Expand All @@ -38,6 +49,11 @@ function createEntry(hostname: string) {
table.appendChild(div);
}

/**
*
* @param click
* @returns
*/
async function removeEntry(click: MouseEvent) {
let target: EventTarget | null = click.target;
if (target === null) return;
Expand All @@ -48,6 +64,11 @@ async function removeEntry(click: MouseEvent) {
await invertHostState(disabledHosts[index]);
}

/**
*
* @param button
* @returns
*/
function getIndex(button: HTMLButtonElement) {
let div: HTMLDivElement = button.parentElement as HTMLDivElement;
if (div === null) return -1;
Expand Down

0 comments on commit faa7327

Please sign in to comment.