UNPKG

ttabs-svelte

Version:

A flexible layout management system with draggable, resizable tiles and tabs for Svelte applications. Like in VSCode

92 lines (91 loc) 2.79 kB
/** * LocalStorage adapter for Ttabs */ export class LocalStorageAdapter { storageKey; debounceTimer = null; debounceDelay; /** * Create a LocalStorage adapter * @param storageKey Key to use in localStorage * @param debounceMs Debounce delay in milliseconds (default: 500ms) */ constructor(storageKey, debounceMs = 500) { this.storageKey = storageKey; this.debounceDelay = debounceMs; } /** * Save ttabs state to localStorage with debounce * @param state The tiles state */ save(state) { // Clear any existing timer if (this.debounceTimer) { clearTimeout(this.debounceTimer); } // Set a new timer this.debounceTimer = setTimeout(() => { this.saveToStorage(state); this.debounceTimer = null; }, this.debounceDelay); } /** * Perform the actual save to localStorage */ saveToStorage(state) { if (typeof window === 'undefined' || !window.localStorage) { return; } try { // Extract focused tab from state if needed const focusedTab = this.findFocusedTab(state); const serialized = JSON.stringify({ tiles: Object.values(state), focusedTab }); localStorage.setItem(this.storageKey, serialized); } catch (error) { console.error('Failed to save ttabs state:', error); } } /** * Helper method to find focused tab from state */ findFocusedTab(state) { // Find panels with active tabs const panels = Object.values(state).filter((tile) => tile.type === 'panel' && !!tile.activeTab); // Find the active panel (could be based on other criteria) const activePanel = panels[0]; return activePanel?.activeTab || undefined; } /** * Load ttabs state from localStorage */ load() { if (typeof window === 'undefined' || !window.localStorage) { return null; } try { const stored = localStorage.getItem(this.storageKey); if (!stored) return null; const parsed = JSON.parse(stored); if (!parsed || !Array.isArray(parsed.tiles)) return null; // Convert array to record const tiles = {}; parsed.tiles.forEach((tile) => { tiles[tile.id] = tile; }); return { tiles, focusedTab: parsed.focusedTab }; } catch (error) { console.error('Failed to load ttabs state:', error); return null; } } }