Add tree state functionality
This commit is contained in:
+35
-1
@@ -8,20 +8,25 @@
|
||||
<style>
|
||||
body { max-width: 40rem; margin: 2rem auto; padding: 0 1rem; font-family: system-ui, sans-serif; }
|
||||
#selection { padding: 0.75rem; background: #f3f3f3; }
|
||||
#share-status { min-height: 1.5em; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Checkbox Tree</h1>
|
||||
<p>A representative sample of countries, U.S. states, and North Dakota counties.</p>
|
||||
<div id="tree"></div>
|
||||
<p><button id="share" type="button">Copy shareable URL</button></p>
|
||||
<p id="share-status" role="status"></p>
|
||||
<h2>Selected places</h2>
|
||||
<pre id="selection">[]</pre>
|
||||
<script type="module">
|
||||
import { CheckboxTree } from "../src/checkbox-tree.js";
|
||||
import { CheckboxTree, loadManifest } from "../src/checkbox-tree.js";
|
||||
|
||||
const output = document.querySelector("#selection");
|
||||
const manifest = loadManifest(await fetch("./manifest.json").then(response => response.json()));
|
||||
const tree = new CheckboxTree(document.querySelector("#tree"), {
|
||||
initiallySelected: true,
|
||||
manifest,
|
||||
onSelectionChange({ selectedIds }) {
|
||||
output.textContent = JSON.stringify(selectedIds, null, 2);
|
||||
},
|
||||
@@ -72,6 +77,35 @@
|
||||
{ id: "country:south-africa", label: "South Africa" },
|
||||
]);
|
||||
output.textContent = JSON.stringify(tree.getSelectedIds(), null, 2);
|
||||
|
||||
function updateUrl() {
|
||||
const url = new URL(window.location.href);
|
||||
url.hash = tree.serializeStateToFragment();
|
||||
if (url.href !== window.location.href) history.pushState(null, "", url);
|
||||
}
|
||||
|
||||
document.querySelector("#tree").addEventListener("change", updateUrl);
|
||||
document.querySelector("#tree").addEventListener("click", event => {
|
||||
if (event.target.closest('.checkbox-tree__toggle')) updateUrl();
|
||||
});
|
||||
|
||||
window.addEventListener("popstate", () => {
|
||||
tree.restoreStateFromLocation();
|
||||
output.textContent = JSON.stringify(tree.getSelectedIds(), null, 2);
|
||||
document.querySelector("#share-status").textContent = "";
|
||||
});
|
||||
|
||||
document.querySelector("#share").addEventListener("click", async () => {
|
||||
const url = new URL(window.location.href);
|
||||
url.hash = tree.serializeStateToFragment();
|
||||
const status = document.querySelector("#share-status");
|
||||
try {
|
||||
await navigator.clipboard.writeText(url.href);
|
||||
status.textContent = "Shareable URL copied.";
|
||||
} catch {
|
||||
status.textContent = `Share this URL: ${url.href}`;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user