Auto-expand sidebar category and add sitemap categories
This commit is contained in:
@@ -1,9 +1,23 @@
|
||||
<script lang="ts">
|
||||
import { browser } from '$app/environment';
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import { categories, getCalculatorsByCategory, type CalculatorDef } from '$lib/data/calculators';
|
||||
|
||||
let expandedCategory = '';
|
||||
let expandedUnits: Record<string, string> = {};
|
||||
let isDesktop = false;
|
||||
let navBreakpoint: MediaQueryList | null = null;
|
||||
let lastPath = '';
|
||||
let lastDesktop = isDesktop;
|
||||
let autoExpandedCategory = '';
|
||||
|
||||
const categoryPathRegex = /^\/category\/([^/]+)(?:\/|$)/;
|
||||
|
||||
function getCategorySlugFromPath(path: string) {
|
||||
const match = path.match(categoryPathRegex);
|
||||
return match?.[1] ?? '';
|
||||
}
|
||||
|
||||
$: currentPath = $page.url.pathname;
|
||||
|
||||
@@ -61,6 +75,49 @@
|
||||
};
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (!browser) return;
|
||||
|
||||
navBreakpoint = window.matchMedia('(max-width: 1024px)');
|
||||
const updateDesktop = (event?: MediaQueryListEvent) => {
|
||||
const matches = event?.matches ?? navBreakpoint!.matches;
|
||||
isDesktop = !matches;
|
||||
};
|
||||
|
||||
updateDesktop();
|
||||
|
||||
const handleNavChange = (event: MediaQueryListEvent) => updateDesktop(event);
|
||||
if ('addEventListener' in navBreakpoint) {
|
||||
navBreakpoint.addEventListener('change', handleNavChange);
|
||||
} else {
|
||||
navBreakpoint.addListener(handleNavChange);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (!navBreakpoint) return;
|
||||
if ('removeEventListener' in navBreakpoint) {
|
||||
navBreakpoint.removeEventListener('change', handleNavChange);
|
||||
} else {
|
||||
navBreakpoint.removeListener(handleNavChange);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
$: if (browser && (currentPath !== lastPath || isDesktop !== lastDesktop)) {
|
||||
const slug = getCategorySlugFromPath(currentPath);
|
||||
if (isDesktop && slug) {
|
||||
expandedCategory = slug;
|
||||
autoExpandedCategory = slug;
|
||||
} else if (autoExpandedCategory && (!isDesktop || !slug)) {
|
||||
if (expandedCategory === autoExpandedCategory) {
|
||||
expandedCategory = '';
|
||||
}
|
||||
autoExpandedCategory = '';
|
||||
}
|
||||
lastPath = currentPath;
|
||||
lastDesktop = isDesktop;
|
||||
}
|
||||
|
||||
export let open = false;
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user