blaze/utils.ts
2023-06-24 00:42:39 +02:00

55 lines
1.5 KiB
TypeScript

export const blazeUrl = process.env.DEV_MODE
? "http://localhost:8888"
: "https://blaze.cyclic.app";
export function injectBlazeToPageLinks(blazeUrl: string, currentUrl: string) {
const url = new URL(currentUrl);
const re = new RegExp("^(http|https)://", "i");
window.addEventListener("DOMContentLoaded", () => {
const links = document.querySelectorAll("a");
links.forEach((link) => {
let originalHref = link.getAttribute("href");
if (!originalHref) {
return;
}
const isAbsoluteLink = re.test(originalHref);
if (!isAbsoluteLink) {
originalHref = `${url.protocol}//${url.hostname}${originalHref}`;
}
link.setAttribute("href", `${blazeUrl}/blazed?url=${originalHref}`);
});
});
}
export function blazeFunctionality(blazeUrl: string) {
const t = document.querySelector("button"),
c = document.querySelector("input");
t!.addEventListener("click", () => {
location.href = blazeUrl + "?q=" + encodeURIComponent(c!.value);
});
}
export function highlightBlazedLinks(links: HTMLLinkElement[]) {
links.forEach((link) => {
if (
!link.href ||
link.href === "http://localhost:8888/" ||
link.href === "https://blaze.cyclic.app"
) {
return;
}
const url = new URL(link.href);
caches.open("blaze").then((cache) => {
cache.match(url.href).then((response) => {
if (response) {
link.innerHTML = `${link.textContent}`;
}
});
});
});
}