Skip to content

Commit

Permalink
general updates
Browse files Browse the repository at this point in the history
  • Loading branch information
codediodeio committed Aug 13, 2022
1 parent 76455f9 commit 01fd503
Show file tree
Hide file tree
Showing 22 changed files with 2,414 additions and 250 deletions.
7 changes: 7 additions & 0 deletions .firebase/hosting.ZXhhbXBsZQ.cache
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
404.html,1660355774737,daa499dd96d8229e73235345702ba32f0793f0c8e5c0d30e40e37a5872be57aa
script2.js,1660353082942,9fc61023c132f480ca8aa2a15020d9862c7cd033b30c3f16388e0f665a60da67
test/index.html,1660352552045,b58c96ffe52a79ef1155e535d83e2257b2ed754560655bcaa7dbb5b68f4ba344
flamethrower.js,1660363180345,6797435a47b62827ba28aeb8ebecc76a2d2091c8fdc58ed05c9a0832fbecaf70
about/index.html,1660357528355,ea2005a3fc92e245a65f1a0d30ba01676d8749adb7e344bb184d468f48571ef1
index.html,1660362476397,4cc7813b8344667d071d2ab4917aab4edb9afe35807c079a130739a8e2ff5df8
script1.js,1660359863695,ca7ea3da9b13b2e2020d80b214e17088649042a64053aa78966395e8637674d7
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,8 @@ typings/

# parcel-bundler cache (https://parceljs.org/)
.cache
/test-results/
/playwright-report/
/playwright/.cache/
firebase.json
.firebaserc
7 changes: 7 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2021 Fireship LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
88 changes: 85 additions & 3 deletions REAMDME.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,88 @@

# Flamethrower 🔥

##
Status: Meme

- Scripts inside the body tag will always run.
- Scripts in the head will only run
An 1.5kB zero-config router and prefetcher that makes static sites feel like a blazingly fast SPA.

## Why?

**Problem** Static sites cannot easily share state between pages. This makes it hard to create a good UX with JavaScript libraries because each new page needs to reboot your JS from scratch.

## How?

1. It tells the browser to prefetch links in the current page.
2. Intercepts click and popstate events, then updates the HTML5 history on route changes.
3. Uses `fetch` to get the next page, swaps the `<body>` out, merges the `<head>`, but does not re-exectute head scripts (unless asked to).

This means you can have long-lived JavaScript behaviors between navigations. It works especially well with native web components.

## QuickStart

```
npm i flamethrower
```

```js
import flamethrower from 'flamethrower';
const router = flamethrower();
```

That's it. Your site now feels blazingly fast.


## Advanced Usage

```js
// with opts
const router = flamethrower({ prefetch: true, log: false, pageTransitions: false });

// Navigate manually
router.go('/somewhere');
router.back();
router.forward();

// Listen to events
window.addEventListener('router:fetch', showLoader);
window.addEventListener('router:end', hideLoader);

// Disable it
router.enabled = false;
```

Opt-out of specific links for full page load.

```html
<a href="/somewhere" data-cold></a>
```

Force scripts in the head to run.

```html
<script src="..." data-reload></script>
```

If using Google Analytics, events will need to be sent manually, i.e:

```js
window.addEventListener('router:end', (e) => {
const page_path = new URL(window.history.state['url']).pathname;
gtag('config', 'UA-YOUR_ID', { page_path });
});
```

### Misc

**Supported in all browsers?** Yes. It will fallback to standard naviation if `window.history` does not exist.

**Does it work with Next.js?** No, any framework that fully hydrates to an SPA does not need this - you already have a client-side router.

**Does it work with Astro** I think so. It can share state between routes, but partially hydrated components may flash between routes.

**Other things to know:**

- `<head>` scripts run only on the first page load. `<body>` scripts will still run on every page change (by design).
- It's a good idea to show a global loading bar in case of a slow page load.
- This library is inspired by [Turbo](https://github.com/hotwired/turbo) Drive, just much lighter.
- Google analytics will not be updated on page change, you'll need to listen to `router:end` and send the GA event manually.
- This project is experimental.
33 changes: 33 additions & 0 deletions example/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page Not Found</title>

<style media="screen">
body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
#message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px 16px; border-radius: 3px; }
#message h3 { color: #888; font-weight: normal; font-size: 16px; margin: 16px 0 12px; }
#message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
#message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
#message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
#message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
#message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
#load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
@media (max-width: 600px) {
body, #message { margin-top: 0; background: white; box-shadow: none; }
body { border-top: 16px solid #ffa100; }
}
</style>
</head>
<body>
<div id="message">
<h2>404</h2>
<h1>Page Not Found</h1>
<p>The specified file was not found on this website. Please check the URL for mistakes and try again.</p>
<h3>Why am I seeing this?</h3>
<p>This page was generated by the Firebase Command-Line Interface. To modify it, edit the <code>404.html</code> file in your project's configured <code>public</code> directory.</p>
</div>
</body>
</html>
39 changes: 27 additions & 12 deletions example/about/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,41 @@
flamethrower({ log: true, pageTransitions: true });
</script>

<script data-reload defer>
console.log('✔️ head script with data-reload attr works')
</script>
<script>console.log('this should NOT run on soft nav')</script>

<script src="/lib.js"></script>
<script defer data-reload src="/script1.js"></script>
<script defer src="/script2.js"></script>

</head>
<body>
<h1>About</h1>
<a href="/">Home</a>
<a href="/test">test</a>
<a href="#heading">Heading</a>
<a href="https://google.com">External</a>
<script>
console.log('✔️ script in body works');
<a href="/">Home</a> |
<a href="/test">Test</a> |
<a href="#heading">Heading</a> |
<a href="https://google.com">External</a> |
<button id="go">Go</button>
<button id="back">Back</button>
<script type="module">
const router = window.flamethrower;
document.getElementById('go').onclick = () => {
router.go('/');
};

document.getElementById('back').onclick = () => router.back();
</script>

<h3>Scripts</h3>
<p>Scripts from body or head with data-reload attr should always run</p>
<p id="bodyCheck"></p>
<p id="headCheck"></p>
<p id="headCheck2">default text</p>

<div style="margin-top: 1000px;"></div>
<h3 id="heading">Heading</h3>
<a href="/">Home</a>
<div style="margin-top: 1000px;"></div>

<script>
console.log('body script');
document.getElementById('bodyCheck').innerText = '✔️ body script works';
</script>
</body>
</html>
139 changes: 80 additions & 59 deletions example/flamethrower.js
Original file line number Diff line number Diff line change
@@ -1,104 +1,125 @@
function h(t) {
["link", "go"].includes(t) && window.scrollTo({ top: 0 });
function u(e) {
["link", "go"].includes(e) && window.scrollTo({ top: 0 });
}
function c(t) {
const e = new URL(t || window.location.href).href;
return e.endsWith("/") ? e : `${e}/`;
function c(e) {
const t = new URL(e || window.location.href).href;
return t.endsWith("/") ? t : `${t}/`;
}
function l(t) {
(!window.history.state || window.history.state.url !== t) && window.history.pushState({ url: t }, "internalLink", t);
function h(e) {
(!window.history.state || window.history.state.url !== e) && window.history.pushState({ url: e }, "internalLink", e);
}
function u(t) {
document.querySelector(t).scrollIntoView({ behavior: "smooth", block: "start" });
function f(e) {
document.querySelector(e).scrollIntoView({ behavior: "smooth", block: "start" });
}
function f(t) {
const e = c();
return l(e), { type: "popstate", next: e };
function p(e) {
const t = c();
return { type: "popstate", next: t };
}
function p(t) {
let e;
if (t.altKey || t.ctrlKey || t.metaKey || t.shiftKey)
function w(e) {
let t;
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey)
return { type: "disqualified" };
for (var o = t.target; o.parentNode; o = o.parentNode)
for (var o = e.target; o.parentNode; o = o.parentNode)
if (o.nodeName === "A") {
e = o;
t = o;
break;
}
if (e && e.host !== location.host)
return e.target = "_blank", { type: "external" };
if (e && e.hasAttribute("href")) {
const n = e.getAttribute("href"), r = new URL(n, location.origin);
if (t.preventDefault(), n && n.startsWith("#"))
return u(n), { type: "scrolled" };
if (t && t.host !== location.host)
return t.target = "_blank", { type: "external" };
if (t && "cold" in (t == null ? void 0 : t.dataset))
return { type: "disqualified" };
if (t != null && t.hasAttribute("href")) {
const n = t.getAttribute("href"), r = new URL(n, location.origin);
if (e.preventDefault(), n != null && n.startsWith("#"))
return f(n), { type: "scrolled" };
{
const s = c(r.href), i = c();
return l(s), { type: "link", next: s, prev: i };
return { type: "link", next: s, prev: i };
}
} else
return { type: "noop" };
}
function d(t) {
const e = document.createElement("script"), o = Array.from(t.attributes);
for (const { name: n, value: r } of o)
e.setAttribute(n, r);
e.appendChild(document.createTextNode(t.innerHTML)), t.parentNode.replaceChild(e, t);
function m(e) {
var t = new DOMParser();
return t.parseFromString(e, "text/html");
}
function m(t) {
var e = new DOMParser();
return e.parseFromString(t, "text/html");
function a(e) {
document.body.innerHTML = e.body.innerHTML;
}
function a(t) {
document.body.innerHTML = t.body.innerHTML, Array.from(document.body.querySelectorAll("script")).forEach(d);
function y(e) {
const t = document.head;
t.querySelectorAll('link[rel="prefetch"]').forEach((n) => e.head.appendChild(n)), t.innerHTML = e.head.innerHTML;
}
function w(t) {
const e = document.head;
e.querySelectorAll('link[rel="prefetch"]').forEach((r) => t.head.appendChild(r)), e.innerHTML = t.head.innerHTML, Array.from(e.querySelectorAll("[data-reload]")).forEach(d);
function l() {
Array.from(
document.head.querySelectorAll("[data-reload]")
).forEach(d), Array.from(document.body.querySelectorAll("script")).forEach(d);
}
async function d(e) {
const t = document.createElement("script"), o = Array.from(e.attributes);
for (const { name: n, value: r } of o)
t.setAttribute(n, r);
t.appendChild(document.createTextNode(e.innerHTML)), e.parentNode.replaceChild(t, e);
}
const y = {
const g = {
log: !1,
prefetch: !0,
pageTransitions: !1
};
class g {
constructor(e) {
this.opts = e, this.enabled = !0, this.prefetched = /* @__PURE__ */ new Set(), this.opts = { ...y, ...e }, window.history ? (document.addEventListener("click", (o) => this.onClick(o)), window.addEventListener("popstate", (o) => this.onPop(o))) : console.warn("flamethrower router not supported by browser"), this.prefetch();
class E {
constructor(t) {
this.opts = t, this.enabled = !0, this.prefetched = /* @__PURE__ */ new Set(), this.opts = { ...g, ...t }, window != null && window.history ? (document.addEventListener("click", (o) => this.onClick(o)), window.addEventListener("popstate", (o) => this.onPop(o))) : console.warn(
"flamethrower router not supported in this browser or environment"
), this.prefetch();
}
go(e) {
const o = window.location.href, n = new URL(e, location.origin).href;
return this.replaceDOM({ type: "go", next: n, prev: o });
go(t) {
const o = window.location.href, n = new URL(t, location.origin).href;
return this.reconstructDOM({ type: "go", next: n, prev: o });
}
disable() {
this.enabled = !1;
back() {
window.history.back();
}
forward() {
window.history.forward();
}
log(...t) {
console.log(...t);
}
prefetch() {
Array.from(document.links).map((o) => o.href).filter(
this.opts.prefetch && Array.from(document.links).map((o) => o.href).filter(
(o) => o.includes(document.location.origin) && !o.includes("#") && o !== (document.location.href || document.location.href + "/") && !this.prefetched.has(o)
).forEach((o) => {
const n = document.createElement("link");
n.rel = "prefetch", n.href = o, n.onload = () => this.opts.log && console.log("\u{1F329}\uFE0F prefetched", o), n.onerror = () => this.opts.log && console.error("\u{1F915} can't prefetch", o), document.head.appendChild(n), this.prefetched.add(o);
n.rel = "prefetch", n.href = o, n.onload = () => this.log("\u{1F329}\uFE0F prefetched", o), n.onerror = (r) => this.log("\u{1F915} can't prefetch", o, r), document.head.appendChild(n), this.prefetched.add(o);
});
}
onClick(e) {
this.enabled && this.replaceDOM(p(e));
onClick(t) {
this.reconstructDOM(w(t));
}
onPop(e) {
this.enabled && this.replaceDOM(f());
onPop(t) {
this.reconstructDOM(p());
}
async replaceDOM({ type: e, next: o, prev: n }) {
async reconstructDOM({ type: t, next: o, prev: n }) {
if (!this.enabled) {
this.log("router disabled");
return;
}
try {
if (this.opts.log && console.log("\u26A1", e), ["popstate", "link", "go"].includes(e) && o !== n) {
this.opts.log && console.time("\u23F1\uFE0F"), window.dispatchEvent(new CustomEvent("router:fetch"));
if (this.log("\u26A1", t), ["popstate", "link", "go"].includes(t) && o !== n) {
this.opts.log && console.time("\u23F1\uFE0F"), window.dispatchEvent(new CustomEvent("router:fetch")), h(o);
const s = await (await fetch(o)).text(), i = m(s);
w(i), this.opts.pageTransitions && document.createDocumentTransition ? document.createDocumentTransition().start(() => a(i)) : a(i), h(e), window.dispatchEvent(new CustomEvent("router:end")), this.prefetch(), this.opts.log && console.timeEnd("\u23F1\uFE0F");
y(i), this.opts.pageTransitions && document.createDocumentTransition ? document.createDocumentTransition().start(() => {
a(i), l();
}) : (a(i), l()), u(t), window.dispatchEvent(new CustomEvent("router:end")), this.prefetch(), this.opts.log && console.timeEnd("\u23F1\uFE0F");
}
} catch (r) {
return window.dispatchEvent(new CustomEvent("router:error", r)), this.opts.log && console.timeEnd("\u23F1\uFE0F"), console.error("\u{1F4A5} router fetch failed", r), !1;
}
}
}
const b = (t) => {
const e = new g(t);
return t.log && console.log("\u{1F525} flamethrower engaged"), e;
const b = (e) => {
const t = new E(e);
return e.log && console.log("\u{1F525} flamethrower engaged"), window && (window.flamethrower = t), t;
};
export {
b as default
Expand Down
Loading

0 comments on commit 01fd503

Please sign in to comment.