Skip to content

Commit

Permalink
Remove warm up cache for map to reduce data usage
Browse files Browse the repository at this point in the history
  • Loading branch information
chunlaw committed Jan 18, 2024
1 parent 8436989 commit aa0144b
Show file tree
Hide file tree
Showing 5 changed files with 7 additions and 168 deletions.
12 changes: 1 addition & 11 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { AppContextProvider } from "./AppContext";
import "./i18n";
import { fetchDbFunc } from "./db";
import * as serviceWorkerRegistration from "./serviceWorkerRegistration";
import type { WarnUpMessageData } from "./typing";
import ErrorBoundary from "./ErrorBoundary";
import { CollectionContextProvider } from "./CollectionContext";
import { ReactNativeContextProvider } from "./ReactNativeContext";
Expand Down Expand Up @@ -37,17 +36,8 @@ if (isHuman()) {
// Target: render only if development or prerendering or in registered app or lazy loading page
const prerenderStyle = document.querySelector("style[prerender]");
const workboxPromise = serviceWorkerRegistration.register({
onUpdate: (workbox, skipWaiting) => {
onUpdate: (_, skipWaiting) => {
skipWaiting();
const message: WarnUpMessageData = {
type: "WARN_UP_MAP_CACHE",
retinaDisplay:
(window.devicePixelRatio ||
// @ts-ignore: Property does not exist on type 'Screen'.
window.screen.deviceXDPI / window.screen.logicalXDPI) > 1,
zoomLevels: [14, 15],
};
workbox.messageSW(message);
},
});
const fetchDb = fetchDbFunc();
Expand Down
27 changes: 4 additions & 23 deletions src/pages/RouteEta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import StopDialog from "../components/route-eta/StopDialog";
import AppContext from "../AppContext";
import { useTranslation } from "react-i18next";
import { setSeoHeader, toProperCase, getDistance } from "../utils";
import type { WarnUpMessageData } from "../typing";
import StrSim from "string-similarity";
import {
Company,
Expand All @@ -25,7 +24,6 @@ const RouteEta = () => {
db: { routeList, stopList, stopMap },
updateSelectedRoute,
energyMode,
workbox,
geoPermission,
geolocation,
} = useContext(AppContext);
Expand Down Expand Up @@ -90,10 +88,10 @@ const RouteEta = () => {
}, [panel, stops, defaultStopIdx]);

const [isDialogOpen, setIsDialogOpen] = useState(false);
const dialogStop = useMemo(() => {
console.log(getDialogStops(co, stops, stopMap, stopIdx));
return getDialogStops(co, stops, stopMap, stopIdx);
}, [co, stopIdx, stopMap, stops]);
const dialogStop = useMemo(
() => getDialogStops(co, stops, stopMap, stopIdx),
[co, stopIdx, stopMap, stops]
);

const { t, i18n } = useTranslation();
const navigate = useNavigate();
Expand Down Expand Up @@ -202,23 +200,6 @@ const RouteEta = () => {
t,
]);

useEffect(() => {
if (!energyMode && navigator.userAgent !== "prerendering") {
const message: WarnUpMessageData = {
type: "WARN_UP_MAP_CACHE",
retinaDisplay:
(window.devicePixelRatio ||
// @ts-ignore: Property does not exist on type 'Screen'.
window.screen.deviceXDPI / window.screen.logicalXDPI) > 1,
zoomLevels: [14, 15, 16, 17, 18],
stopList: getStops(co, stops)
.map((id) => stopList[id])
.filter((stop) => stop !== null && stop !== undefined),
};
workbox?.messageSW(message);
}
}, [co, energyMode, stopList, stops, workbox]);

return (
<>
<input hidden id={id} />
Expand Down
66 changes: 0 additions & 66 deletions src/service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ import {
StrategyHandler,
} from "workbox-strategies";
import { CacheableResponsePlugin } from "workbox-cacheable-response";
import { fetchEtaDb } from "hk-bus-eta";
import { getTileListURL, isWarnUpMessageData } from "./utils";
import type { StopListEntry } from "hk-bus-eta";

declare var self: ServiceWorkerGlobalScope & typeof globalThis;
clientsClaim();
Expand Down Expand Up @@ -133,52 +130,6 @@ registerRoute(
})
);

const warnUpCache = async (
zoomLevels: Array<number>,
event: ExtendableEvent,
retina: boolean,
stopListInput?: Array<StopListEntry>
) => {
try {
let stopList;
if (stopListInput === undefined) {
const eta = await fetchEtaDb();
stopList = Object.values(eta.stopList);
} else {
stopList = stopListInput;
}
await Promise.all(
zoomLevels.map(async (i) => {
const generate = function* () {
const list = getTileListURL(i, stopList, retina);
for (let k = 0; k < list.length; k = k + 1) {
yield mapCacheStrategy.handleAll({
event,
request: new Request(list[k], {}),
})[1];
}
};
const a = generate();
let result = a.next();
const pendingPromise: Set<Promise<void>> = new Set();
while (result.done !== true) {
const value = result.value;
pendingPromise.add(value);
value.then(() => pendingPromise.delete(value));
// limit pending fetch to 10
if (pendingPromise.size >= 10) {
await Promise.any(pendingPromise);
}
result = a.next();
}
return;
})
);
} catch (e) {
console.error("error on warn cache", e);
}
};

// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener("message", (event) => {
Expand All @@ -197,21 +148,4 @@ self.addEventListener("message", (event) => {
)
);
}
const data: unknown = event.data;
if (isWarnUpMessageData(data)) {
console.log("warm up map cache", data);
const warnCache = async () => {
try {
await warnUpCache(
data.zoomLevels,
event,
data.retinaDisplay,
data.stopList
);
} catch (e) {
console.error("error on warn cache", e);
}
};
event.waitUntil(warnCache());
}
});
9 changes: 0 additions & 9 deletions src/typing.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
import type { StopListEntry } from "hk-bus-eta";

export interface WarnUpMessageData {
type: "WARN_UP_MAP_CACHE";
retinaDisplay: boolean;
zoomLevels: number[];
stopList?: StopListEntry[];
}

export interface DaySchedule {
day: number;
// use start, end only if allDay is false
Expand Down
61 changes: 2 additions & 59 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import type {
Company,
EtaDb,
Location,
RouteList,
StopList,
StopListEntry,
} from "hk-bus-eta";
import type { Company, EtaDb, Location, RouteList, StopList } from "hk-bus-eta";
import type { Location as GeoLocation } from "hk-bus-eta";
import type { TransportType, WarnUpMessageData } from "./typing";
import type { TransportType } from "./typing";
import { isRouteAvaliable } from "./timetable";
export const getDistance = (a: GeoLocation, b: GeoLocation) => {
const R = 6371e3; // metres
Expand Down Expand Up @@ -229,56 +222,6 @@ export const binarySearch = <T>(
return -m - 1;
};

interface TempEntry {
key: number;
x: number;
y: number;
}

export const getTileListURL = (
zoomLevel: number,
stopLists: Array<StopListEntry>,
retinaDisplay: boolean
) => {
const high = 255 * (zoomLevel + 5) * (zoomLevel + 5);
const compare = (a: TempEntry, b: TempEntry) => b.key - a.key;
return stopLists
.map((stop) => {
const x = lon2tile(stop.location.lng, zoomLevel);
const y = lat2tile(stop.location.lat, zoomLevel);
return {
key: x * high + y,
x: x,
y: y,
};
})
.sort(compare)
.reduce((prev: TempEntry[], curr) => {
if (binarySearch(prev, curr, compare) < 0) {
prev.push(curr);
}
return prev;
}, [])
.flatMap((entry) => [
process.env.REACT_APP_OSM_PROVIDER_URL.replace(/\{s\}/g, "a")
.replace(/\{x\}/g, String(entry.x))
.replace(/\{y\}/g, String(entry.y))
.replace(/\{z\}/g, String(zoomLevel))
.replace(/\{r\}/g, retinaDisplay ? "@2x" : ""),
process.env.REACT_APP_OSM_PROVIDER_URL_DARK.replace(/\{s\}/g, "a")
.replace(/\{x\}/g, String(entry.x))
.replace(/\{y\}/g, String(entry.y))
.replace(/\{z\}/g, String(zoomLevel))
.replace(/\{r\}/g, retinaDisplay ? "@2x" : ""),
]);
};

export const isWarnUpMessageData = (
value: unknown
): value is WarnUpMessageData => {
return typeof value === "object" && value["type"] === "WARN_UP_MAP_CACHE";
};

export const checkAppInstalled = () => {
if (window.matchMedia("(display-mode: standalone)").matches) return true;
// @ts-ignore
Expand Down

0 comments on commit aa0144b

Please sign in to comment.