@yhwh-script/create-app
Version:
A yhwh-script web app can become anything you want it to become. Set it up with just one command.
120 lines (104 loc) • 3.37 kB
HTML
<script type="module">
const { getAnimals } = window.Animals;
const { log, error } = window.Logger;
const nav = shadowDocument.querySelector("nav");
window.onscroll = (function stickyNavbar() {
if (window.pageYOffset >= sticky) {
nav.classList.add("sticky")
} else {
nav.classList.remove("sticky");
}
})();
var sticky = nav.offsetTop;
shadowDocument.querySelectorAll("a.navlink").forEach(a => {
a.addEventListener("click", function (event) {
event.preventDefault();
nav.querySelector(".active").classList.remove("active");
event.target.classList.add("active");
const url = event.target.getAttribute("href");
go(url);
});
});
window.addEventListener("popstate", function (event) { // TODO: fix back button click
if (event.state) {
go(event.state.route, false);
}
});
window.go = function (route, addToHistory = true) {
if (addToHistory) {
history.pushState({ route }, null, route);
}
let section = null;
switch (route) {
case "/": {
section = document.createElement("home-switch");
break;
}
case "/animals": {
section = document.createElement("animals-view");
getAnimals()
.then(animals => {
section.dataset.state = JSON.stringify(animals);
}).catch(err => {
error(err.name, err.message);
});
break;
}
case "/sqlite": {
section = document.createElement("sqlite-control");
break;
}
default:
}
shadowDocument.querySelectorAll("a.navlink").forEach(a => {
a.classList.remove("active");
if (a.getAttribute("href") == location.pathname) {
a.classList.add("active");
}
});
if (section) {
shadowDocument.dispatchEvent(new CustomEvent('navigate', { bubbles: true, composed: true, detail: section }));
}
}
// Check initial URL
go(location.pathname);
</script>
<style>
nav {
background-color: #144000;
display: flex;
overflow: hidden;
a {
float: left;
color: #ffd700;
padding: 2vh;
text-decoration: none;
font-size: 4vh;
font-weight: 600;
&:hover {
background-color: #ffff00;
color: #144000;
}
&.active {
background-color: #ffd700;
color: #144000;
text-shadow: none;
}
&.hidden {
display: none;
}
}
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
</style>
<template>
<nav>
<a class="navlink active" href="/">🏠</a>
<a class="navlink" href="/animals">Animals</a>
<a class="navlink" href="/sqlite">SQLite</a>
</nav>
</template>