blaze/utils.ts

55 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-06-20 23:00:31 +00:00
export const blazeUrl = process.env.DEV_MODE
? "http://localhost:8888"
: "https://blaze.cyclic.app";
2023-06-21 00:26:24 +00:00
export function injectBlazeToPageLinks(blazeUrl: string, currentUrl: string) {
2023-06-22 13:11:10 +00:00
const url = new URL(currentUrl);
2023-06-21 00:26:24 +00:00
const re = new RegExp("^(http|https)://", "i");
2023-06-20 23:00:31 +00:00
window.addEventListener("DOMContentLoaded", () => {
const links = document.querySelectorAll("a");
links.forEach((link) => {
2023-06-21 00:26:24 +00:00
let originalHref = link.getAttribute("href");
if (!originalHref) {
return;
}
const isAbsoluteLink = re.test(originalHref);
if (!isAbsoluteLink) {
2023-06-22 13:11:10 +00:00
originalHref = `${url.protocol}//${url.hostname}${originalHref}`;
2023-06-21 00:26:24 +00:00
}
2023-06-20 23:00:31 +00:00
link.setAttribute("href", `${blazeUrl}/blazed?url=${originalHref}`);
});
});
}
export function blazeFunctionality(blazeUrl: string) {
const t = document.querySelector("button"),
c = document.querySelector("input");
t!.addEventListener("click", () => {
2023-06-22 14:38:38 +00:00
location.href = blazeUrl + "?q=" + encodeURIComponent(c!.value);
});
}
2023-06-23 22:42:39 +00:00
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}`;
}
});
});
});
}