Skip to content

Commit

Permalink
chore: move ts to js
Browse files Browse the repository at this point in the history
  • Loading branch information
nobkd committed Jun 27, 2024
1 parent 04493de commit 51fb3b8
Show file tree
Hide file tree
Showing 24 changed files with 230 additions and 235 deletions.
Binary file modified bun.lockb
Binary file not shown.
7 changes: 2 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@
"test": "vitest run",
"test:watch": "vitest",
"test:cov": "vitest run --coverage",
"dev": "run-p -rl vite:watch serve:firefox",
"vite:site": "vite",
"vite:watch": "vite build --watch --mode development --minify false",
"build": "tsc && vite build",
"dev": "run-p -rl 'vite build --watch --mode development --minify false' serve:firefox",
"build": "vite build",
"serve:firefox": "web-ext run -s dist",
"serve:chromium": "web-ext run -t chromium -s dist",
"bundle": "web-ext build -s dist -a out --overwrite-dest -n replace_maps.zip",
Expand All @@ -39,7 +37,6 @@
"prettier": "^3.3.2",
"release-it": "^17.4.0",
"release-it-changelogen": "^0.1.0",
"typescript": "^5.5.2",
"vite": "^5.3.2",
"vite-plugin-static-copy": "^1.0.5",
"vitest": "^1.6.0",
Expand Down
4 changes: 2 additions & 2 deletions src/bg.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<!doctype html>
<head>
<meta charset="UTF-8" />
<script src="bg/action.ts" type="module"></script>
<script src="bg/bg.ts" type="module"></script>
<script src="bg/action.js" type="module"></script>
<script src="bg/bg.js" type="module"></script>
</head>
6 changes: 3 additions & 3 deletions src/bg/action.ts → src/bg/action.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { browserAction, /*webNavigation,*/ type Tabs, tabs } from 'webextension-polyfill'
import { browserAction, /*webNavigation,*/ Tabs, tabs } from 'webextension-polyfill'
import { getHostname, invertHostState } from './utils/storage'
//import { matcher as mapsUrlMatcher, runtimeMapUrl } from './bg';

Expand All @@ -10,9 +10,9 @@ import { getHostname, invertHostState } from './utils/storage'
*
* Requests all frames from the current tab, filters them for extension Leaflet frames and Maps frames.
* Reloads the full tab on extension Leaflet or Maps frame match.
* @param tab Currently active tab
* @param {Tabs.Tab} tab Currently active tab
*/
async function actionClick(tab: Tabs.Tab): Promise<void> {
async function actionClick(tab) {
if (!tab.url || !tab.id) return

let hostname = getHostname(tab.url)
Expand Down
12 changes: 6 additions & 6 deletions src/bg/bg.ts → src/bg/bg.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { runtime, tabs, windows, webRequest, type WebRequest } from 'webextension-polyfill'
import { runtime, tabs, windows, webRequest, WebRequest } from 'webextension-polyfill'
import { disabledHosts, getHostname } from './utils/storage'
import { updateActiveTabIcon } from './utils/actionIcon'
import { domainEnds } from './utils/domainEnds'

const gLocales: string = domainEnds.join('|') // TODO: collect more locales
export const matcher: RegExp = new RegExp(
const gLocales = domainEnds.join('|') // TODO: collect more locales
export const matcher = new RegExp(
// TODO: fix regex to fit more patterns
`^(https?:\/\/)?(maps\.google\.(${gLocales})\/maps.*\?.*output=embed|(www\.)?google\.(${gLocales})\/maps\/embed.*\?)`
)
Expand All @@ -14,10 +14,10 @@ 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
* @param {WebRequest.OnBeforeRequestDetailsType} req Web Request from frame
* @returns {WebRequest.BlockingResponse} Redirect to extension map or pass through if extension disabled for website
*/
function redirect(req: WebRequest.OnBeforeRequestDetailsType): WebRequest.BlockingResponse {
function redirect(req) {
// TODO: check if originUrl always matches current tab url -> e.g. in frames with subframes
if (req.originUrl && req.url.match(matcher)) {
if (!disabledHosts.includes(getHostname(req.originUrl))) {
Expand Down
6 changes: 3 additions & 3 deletions src/bg/utils/actionIcon.ts → src/bg/utils/actionIcon.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { disabledHosts, getHostname } from './storage'

/**
* Updates the action icon
* @param hostname Hostname
* @param {string} hostname Hostname
*/
export function updateIcon(hostname: string): void {
export function updateIcon(hostname) {
let disabled = disabledHosts.includes(hostname)

browserAction.setIcon({
Expand All @@ -24,7 +24,7 @@ export function updateIcon(hostname: string): void {
/**
* Async function to update the icon of the currently active tab. Uses `updateIcon` internally
*/
export async function updateActiveTabIcon(): Promise<void> {
export async function updateActiveTabIcon() {
let browserTabs = await tabs.query({ active: true, currentWindow: true })

let tab = browserTabs[0]
Expand Down
2 changes: 1 addition & 1 deletion src/bg/utils/domainEnds.ts → src/bg/utils/domainEnds.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Domain ends of google
export const domainEnds: string[] = [
export const domainEnds = [
'com',
'ac',
'ad',
Expand Down
17 changes: 9 additions & 8 deletions src/bg/utils/storage.ts → src/bg/utils/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { updateIcon } from './actionIcon'
export const KEY_DISABLED_HOSTS = 'disabled_hosts'

// Listens to changes on the storage. Updates disabled hosts list, if stored list changes
export let disabledHosts: string[] = await getDisabledHosts()
/** @type {string[]} */
export let disabledHosts = await getDisabledHosts()
storage.local.onChanged.addListener((changes) => {
if (KEY_DISABLED_HOSTS in changes) {
disabledHosts = changes[KEY_DISABLED_HOSTS].newValue ?? []
Expand All @@ -13,18 +14,18 @@ storage.local.onChanged.addListener((changes) => {

/**
* Async function to get the list of disabled hostnames
* @returns List of disabled hostnames
* @returns {Promise<string[]>} List of disabled hostnames
*/
async function getDisabledHosts(): Promise<string[]> {
async function getDisabledHosts() {
return (await storage.local.get(KEY_DISABLED_HOSTS))[KEY_DISABLED_HOSTS] ?? []
}

/**
* Async function to invert the state of a hostname.
* Adds new entry if not disabled, removes entry, if already disabled
* @param hostname Hostname to invert the state of
* @param {string} hostname Hostname to invert the state of
*/
export async function invertHostState(hostname: string): Promise<void> {
export async function invertHostState(hostname) {
if (disabledHosts.includes(hostname)) {
disabledHosts.splice(disabledHosts.indexOf(hostname), 1)
} else {
Expand All @@ -40,10 +41,10 @@ export async function invertHostState(hostname: string): Promise<void> {

/**
* Retrieves the hostname from a URL
* @param url Full URL string
* @returns Hostname string
* @param {string} url Full URL string
* @returns {string} Hostname string
*/
export function getHostname(url: string): string {
export function getHostname(url) {
url = url.replace(/^\w+:\/\//, '')
url = url.split(/[\/#\?]/, 1)[0]
return url
Expand Down
2 changes: 1 addition & 1 deletion src/map.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@

<body>
<div id="map"></div>
<script src="map/map.ts" type="module"></script>
<script src="map/map.js" type="module"></script>
</body>
</html>
38 changes: 20 additions & 18 deletions src/map/map.ts → src/map/map.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import L from 'leaflet'
import 'leaflet-fullscreen'

import { readPB, readQ, type MapData } from './utils/read'
import { type TileType, tileTypes } from './utils/parsePB'
import { readPB, readQ, MapData } from './utils/read'
import { tileTypes } from './utils/parsePB'

type Tiles = {
[K in TileType]: {
layer: string
attr: string
}
}
/**
* @typedef {object} Tile
* @property {string} layer
* @property {string} attr
*/

// https://leaflet-extras.github.io/leaflet-providers/preview/
const tileProviders: Tiles = {
/** @type {{TileTypes: Tile}} */
const tileProviders = {
roadmap: {
layer: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', // OpenStreetMap.Mapnik
attr: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
Expand All @@ -24,28 +24,30 @@ const tileProviders: Tiles = {
}, // TODO: add street layer etc to satellite
}

const gPos: string = 'pb'
const gQuery: string = 'q'
const gZoom: string = 'z'
const params: URLSearchParams = new URLSearchParams(document.location.search)
const gPos = 'pb'
const gQuery = 'q'
const gZoom = 'z'
const params = new URLSearchParams(document.location.search)

let mapData: MapData = {}
/** @type {MapData} */
const mapData = {}

if (params.has(gPos)) {
mapData = await readPB(params.get(gPos) as string)
mapData = await readPB(params.get(gPos))
} else if (params.has(gQuery)) {
let marker = await readQ(params.get(gQuery) as string)
let marker = await readQ(params.get(gQuery))

if (marker) {
mapData.markers = [marker]
}
}

if (params.has(gZoom)) {
mapData.zoom = parseInt(params.get(gZoom) as string)
mapData.zoom = parseInt(params.get(gZoom))
}

const map: L.Map = L.map('map', {
/** @type {L.Map} */
const map = L.map('map', {
fullscreenControl: true,
scrollWheelZoom: true, // TODO: on pc allow ctrl + scroll
zoom: mapData.zoom ?? 17,
Expand Down
27 changes: 27 additions & 0 deletions src/map/utils/parseDMS.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Converts DMS coordinates to Lat and Lon
* @param {string} input String containing DMS coordinates
* @returns {[number, number]} Array containing Latitude and Longitude
*/
export function parseDMS(input) {
/** @type {string[]} */
const parts = input.split(/[^\d\w\.]+/)
const lat = convertDMSToDD(parts.slice(0, 4))
const lon = convertDMSToDD(parts.slice(4))

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

if (direction === 'S' || direction === 'W') {
dd = dd * -1
} // Don't do anything for N or E
return dd
}
26 changes: 0 additions & 26 deletions src/map/utils/parseDMS.ts

This file was deleted.

31 changes: 18 additions & 13 deletions src/map/utils/parsePB.ts → src/map/utils/parsePB.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
export type TileType = 'roadmap' | 'satellite'
export const tileTypes: TileType[] = ['roadmap', 'satellite']
/**
* @typedef {'roadmap' | 'satellite'} TileType
* @type {TileType[]}
*/
export const tileTypes = ['roadmap', 'satellite']

/**
* Takes one bang operator and decodes it.
Expand All @@ -17,16 +20,18 @@ export const tileTypes: TileType[] = ['roadmap', 'satellite']
*
* 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.
* @param {string} item One bang operator with the structure: position, one character (data type), encoded data
* @returns {[string | TileType | number, boolean]} 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] {
function convertType(item) {
item = item.replace(/^\d+/, '')
const type: string = item.charAt(0)
/** @type {string} */
const type = item.charAt(0)
item = item.substring(1)

// s: string || v: timestamp || b: boolean?/byte?
let val: string | TileType | number = item
/** @type {string | TileType | number} */
let val = item

switch (type) {
case 'f':
Expand Down Expand Up @@ -66,21 +71,21 @@ function convertType(item: string): [string | TileType | number, boolean] {
* - 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
* @param {string[]} items Bang operators (e.g. `!1m13`) split into pieces at `!`
* @param {any[]} out Array for top and recursion levels to save results and return
* @returns {any[]} Filled `out` array with bang operators converted into readable format
*/
export function parsePB(items: string[], out: any[] = []): any[] {
export function parsePB(items, out = []) {
let i = 0
while (i < items.length) {
let [val, isNew] = convertType(items[i])

if (!isNew) {
out.push(val)
} else {
let itemsPart = items.slice(i + 1, i + (val as number) + 1)
let itemsPart = items.slice(i + 1, i + val + 1)
out.push(parsePB(itemsPart))
i += val as number
i += val
}
i++
}
Expand Down
Loading

0 comments on commit 51fb3b8

Please sign in to comment.