Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created April 11, 2020 12:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nexpr/862dbb5277ccfa19b2a2d093b2dc8429 to your computer and use it in GitHub Desktop.
Save nexpr/862dbb5277ccfa19b2a2d093b2dc8429 to your computer and use it in GitHub Desktop.
lit-html routing example
export const navigate = url => eve => {
eve.preventDefault()
const nav_url = url || eve.target.href
history.pushState(null, "", nav_url)
window.dispatchEvent(new Event("pushstate"))
}
import { html } from "https://unpkg.com/lit-html?module"
import { navigate } from "./common.js"
export const view = data => {
const id = data.route.id
const content = data.contents.find(e => e.id === id)
return html`
<a href="list" @click=${navigate()}>Back to list</a>
<h1>Detail</h1>
<h2>${content ? content.title : "Not Found"}</h2>
<p>${content ? content.body : ""}</p>
`
}
export const route = (path, query) => {
return { page: "detail", id: ~~path[1] }
}
<!doctype html>
<meta charset="utf-8" />
<base href="/" />
<script type="module">
import { html, render } from "https://unpkg.com/lit-html?module"
import * as page_list from "./list.js"
import * as page_detail from "./detail.js"
const data = {
contents: [
{ id: 10, title: "aa", body: "aaaaaaaa aaaaaaaa" },
{ id: 20, title: "bbbb", body: "bbbbbbbb bbbbbb bbbbbbbb" },
{ id: 24, title: "ccc", body: "cccc ccccc ccccc" },
{ id: 45, title: "d", body: "dddddddd" },
],
route: null,
}
const onNavigate = () => {
const url = new URL(location)
const base = new URL(document.baseURI)
const matched = base.pathname.match(/^.*\//)
const base_str = matched ? matched[0] : ""
const route_path = url.pathname.substr(base_str.length).split("/")
const page = {
list: page_list,
detail: page_detail,
}[route_path[0]]
if (page) {
data.route = page.route(route_path, url.searchParams)
} else {
data.route = null
}
renderView()
}
window.addEventListener("pushstate", onNavigate)
window.addEventListener("popstate", onNavigate)
const view = data => {
const page = {
list: page_list,
detail: page_detail,
}[data.route?.page]
if (page) {
return page.view(data)
} else {
return html`page not found`
}
}
const renderView = () => render(view(data), document.getElementById("root"))
onNavigate()
</script>
<div id="root"></div>
import { html } from "https://unpkg.com/lit-html?module"
import { navigate } from "./common.js"
export const view = data => html`
<h1>List</h1>
<div>
${
data.contents.map(e => html`
<div>
<a href="detail/${e.id}" @click=${navigate()}>${e.title}</a>
</div>
`)
}
</div>
`
export const route = (path, query) => {
return { page: "list" }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment