Different URL tree state encoding

This commit is contained in:
2026-07-11 22:51:01 -05:00
parent 291b6028f5
commit af325782a8
5 changed files with 1123 additions and 12 deletions
+32 -3
View File
@@ -1,4 +1,4 @@
import { CheckboxTree } from '../vendor/checkbox-tree/checkbox-tree.js';
import { CheckboxTree, loadManifest } from '../vendor/checkbox-tree/checkbox-tree.js';
import { getSortedKeys } from './sort.js';
const STORAGE_KEY = 'tree-state-v2';
@@ -14,11 +14,29 @@ export function initializeTree(containerId, onSelectionChange) {
productTree = new CheckboxTree(container, {
storageKey: STORAGE_KEY,
initiallyCollapsed: true,
onSelectionChange
onSelectionChange: event => {
onSelectionChange(event);
pushTreeState();
}
});
container.addEventListener('click', event => {
if (event.target.closest('.checkbox-tree__toggle')) {
pushTreeState();
}
});
window.addEventListener('popstate', () => {
productTree?.restoreStateFromLocation();
onSelectionChange({
selectedIds: productTree?.getSelectedIds() ?? [],
selectedNodes: productTree?.getSelectedNodes() ?? []
});
});
}
export function renderProductTree(productsData) {
export async function renderProductTree(productsData) {
const manifestSource = await fetch('data/product-tree-manifest.json').then(response => response.json());
requireTree().options.manifest = loadManifest(manifestSource);
requireTree().setData(toTreeNodes(productsData));
}
@@ -53,6 +71,17 @@ function requireTree() {
return productTree;
}
function pushTreeState() {
if (!productTree?.options.manifest) {
return;
}
const url = new URL(window.location.href);
url.hash = productTree.serializeStateToFragment();
if (url.href !== window.location.href) {
history.pushState(null, '', url);
}
}
function toTreeNodes(value, path = []) {
return getSortedKeys(value)
.filter(key => key !== 'addressed' && key !== 'known')