elm-pages-v3-beta/generator/static-code/elm-pages.js

103 lines
2.6 KiB
JavaScript
Raw Normal View History

import userInit from "/index.js";
2021-06-25 01:55:41 +03:00
let prefetchedPages = [window.location.pathname];
let initialLocationHash = document.location.hash.replace(/^#/, "");
2021-05-17 22:51:04 +03:00
/**
* @returns
*/
2021-06-25 01:55:41 +03:00
function loadContentAndInitializeApp() {
let path = window.location.pathname.replace(/(\w)$/, "$1/");
if (!path.endsWith("/")) {
path = path + "/";
}
2021-06-25 01:55:41 +03:00
const app = Elm.TemplateModulesBeta.init({
flags: {
secrets: null,
isPrerendering: false,
isDevServer: false,
isElmDebugMode: false,
contentJson: JSON.parse(
document.getElementById("__ELM_PAGES_DATA__").innerHTML
),
2021-06-25 01:55:41 +03:00
userFlags: userInit.flags(),
},
});
2021-06-25 01:55:41 +03:00
app.ports.toJsPort.subscribe((fromElm) => {
loadNamedAnchor();
});
2021-06-25 01:55:41 +03:00
return app;
}
function loadNamedAnchor() {
if (initialLocationHash !== "") {
const namedAnchor = document.querySelector(`[name=${initialLocationHash}]`);
namedAnchor && namedAnchor.scrollIntoView();
}
}
function prefetchIfNeeded(/** @type {HTMLAnchorElement} */ target) {
2021-06-25 01:55:41 +03:00
if (
target.host === window.location.host &&
!prefetchedPages.includes(target.pathname)
) {
prefetchedPages.push(target.pathname);
const link = document.createElement("link");
link.setAttribute("as", "fetch");
link.setAttribute("rel", "prefetch");
link.setAttribute("href", origin + target.pathname + "/content.json");
document.head.appendChild(link);
}
}
2021-06-25 01:55:41 +03:00
const appPromise = new Promise(function (resolve, reject) {
document.addEventListener("DOMContentLoaded", (_) => {
resolve(loadContentAndInitializeApp());
});
2021-06-25 01:55:41 +03:00
});
2021-05-17 22:51:04 +03:00
userInit.load(appPromise);
if (typeof connect === "function") {
connect(function (newContentJson) {
appPromise.then((app) => {
app.ports.fromJsPort.send({ contentJson: newContentJson });
});
});
}
2021-05-15 05:33:52 +03:00
/** @param {MouseEvent} event */
const trigger_prefetch = (event) => {
const a = find_anchor(/** @type {Node} */ (event.target));
if (a && a.href && a.hasAttribute("elm-pages:prefetch")) {
prefetchIfNeeded(a);
}
};
/** @type {NodeJS.Timeout} */
let mousemove_timeout;
/** @param {MouseEvent} event */
const handle_mousemove = (event) => {
clearTimeout(mousemove_timeout);
mousemove_timeout = setTimeout(() => {
trigger_prefetch(event);
}, 20);
};
addEventListener("touchstart", trigger_prefetch);
addEventListener("mousemove", handle_mousemove);
/**
* @param {Node} node
// * @rturns {HTMLAnchorElement | SVGAElement}
* @returns {HTMLAnchorElement}
*/
function find_anchor(node) {
while (node && node.nodeName.toUpperCase() !== "A") node = node.parentNode; // SVG <a> elements have a lowercase name
return /** @type {HTMLAnchorElement} */ (node);
}