1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2026-06-30 01:06:00 -04:00

major refactoring of preact components 🧩 (#689)

This commit is contained in:
2021-12-15 08:35:18 -05:00
committed by GitHub
parent cda7d538a6
commit d119a98a0d
30 changed files with 1005 additions and 1053 deletions
+9 -18
View File
@@ -1,7 +1,7 @@
// Heavily inspired by AnchorJS:
// https://github.com/bryanbraun/anchorjs
import { h, render } from "preact";
import isTouchDevice from "is-touch-device";
// react components:
import Anchor from "./components/Anchor.js";
// loop through each h2, h3, h4 in this page's content area
// prettier-ignore
@@ -9,24 +9,15 @@ document.querySelectorAll([
"div#content h2",
"div#content h3",
"div#content h4",
]).forEach((h) => {
]).forEach((heading) => {
// don't add to elements without a pre-existing ID (e.g. `<h2 id="...">`)
if (!h.hasAttribute("id")) {
if (!heading.hasAttribute("id")) {
return;
}
// build the anchor link (the "#" icon is added via CSS)
const anchor = document.createElement("a");
anchor.className = "anchorjs-link";
anchor.href = `#${h.getAttribute("id")}`;
anchor.ariaLabel = "Anchor";
// TODO: little hacky hack to make the anchor appear AFTER the existing h tag
const linkTarget = document.createElement("a");
heading.appendChild(linkTarget);
// if this is a touchscreen, always show the "#" icon instead waiting for hover
// NOTE: this is notoriously unreliable; see https://github.com/Modernizr/Modernizr/pull/2432
if (isTouchDevice()) {
anchor.style.opacity = "1";
}
// add anchor link to the right of the heading
h.appendChild(anchor);
render(<Anchor id={heading.getAttribute("id")} title={heading.textContent.trim()} />, heading, linkTarget);
});