Complete UI foundation and app layout implementation, stabilize container health checks, and archive both OpenSpec changes after verification.
84 lines
2.4 KiB
TypeScript
84 lines
2.4 KiB
TypeScript
import { writable } from 'svelte/store';
|
|
import type { SidebarState, Theme } from '$lib/types/layout';
|
|
|
|
const SIDEBAR_STORAGE_KEY = 'headroom_sidebar_state';
|
|
const THEME_STORAGE_KEY = 'headroom_theme';
|
|
|
|
const DEFAULT_SIDEBAR_STATE: SidebarState = 'expanded';
|
|
const DEFAULT_THEME: Theme = 'light';
|
|
|
|
function isSidebarState(value: string | null): value is SidebarState {
|
|
return value === 'expanded' || value === 'collapsed' || value === 'hidden';
|
|
}
|
|
|
|
function isTheme(value: string | null): value is Theme {
|
|
return value === 'light' || value === 'dark';
|
|
}
|
|
|
|
function getInitialSidebarState(): SidebarState {
|
|
if (typeof localStorage === 'undefined') return DEFAULT_SIDEBAR_STATE;
|
|
|
|
const stored = localStorage.getItem(SIDEBAR_STORAGE_KEY);
|
|
return isSidebarState(stored) ? stored : DEFAULT_SIDEBAR_STATE;
|
|
}
|
|
|
|
function getInitialTheme(): Theme {
|
|
if (typeof localStorage === 'undefined') return DEFAULT_THEME;
|
|
|
|
const stored = localStorage.getItem(THEME_STORAGE_KEY);
|
|
if (isTheme(stored)) return stored;
|
|
|
|
const prefersDark =
|
|
typeof window.matchMedia === 'function' &&
|
|
window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
|
|
return prefersDark ? 'dark' : DEFAULT_THEME;
|
|
}
|
|
|
|
function applyTheme(value: Theme): void {
|
|
if (typeof document === 'undefined') return;
|
|
document.documentElement.setAttribute('data-theme', value);
|
|
}
|
|
|
|
const sidebarStateWritable = writable<SidebarState>(getInitialSidebarState());
|
|
const themeWritable = writable<Theme>(getInitialTheme());
|
|
|
|
if (typeof localStorage !== 'undefined') {
|
|
sidebarStateWritable.subscribe((value) => {
|
|
localStorage.setItem(SIDEBAR_STORAGE_KEY, value);
|
|
});
|
|
|
|
themeWritable.subscribe((value) => {
|
|
localStorage.setItem(THEME_STORAGE_KEY, value);
|
|
applyTheme(value);
|
|
});
|
|
}
|
|
|
|
export const sidebarState = {
|
|
subscribe: sidebarStateWritable.subscribe
|
|
};
|
|
|
|
export const theme = {
|
|
subscribe: themeWritable.subscribe
|
|
};
|
|
|
|
export function toggleSidebar(): void {
|
|
sidebarStateWritable.update((current) => {
|
|
if (current === 'expanded') return 'collapsed';
|
|
if (current === 'collapsed') return 'hidden';
|
|
return 'expanded';
|
|
});
|
|
}
|
|
|
|
export function setSidebarState(state: SidebarState): void {
|
|
sidebarStateWritable.set(state);
|
|
}
|
|
|
|
export function toggleTheme(): void {
|
|
themeWritable.update((current) => (current === 'light' ? 'dark' : 'light'));
|
|
}
|
|
|
|
export function setTheme(newTheme: Theme): void {
|
|
themeWritable.set(newTheme);
|
|
}
|