feat: release toolbox portal 0.1.0
This commit is contained in:
47
src/usePreferences.ts
Normal file
47
src/usePreferences.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
PREFERENCES_KEY,
|
||||
defaultPreferences,
|
||||
readPreferences,
|
||||
writePreferences,
|
||||
type Preferences,
|
||||
} from './preferences';
|
||||
|
||||
interface InitialPreferences {
|
||||
preferences: Preferences;
|
||||
storageAvailable: boolean;
|
||||
}
|
||||
|
||||
function initializePreferences(): InitialPreferences {
|
||||
try {
|
||||
const preferences = readPreferences();
|
||||
const probeKey = `${PREFERENCES_KEY}:probe`;
|
||||
localStorage.setItem(probeKey, '1');
|
||||
localStorage.removeItem(probeKey);
|
||||
return { preferences, storageAvailable: true };
|
||||
} catch {
|
||||
return { preferences: { ...defaultPreferences }, storageAvailable: false };
|
||||
}
|
||||
}
|
||||
|
||||
export function usePreferences(): [
|
||||
Preferences,
|
||||
(next: Preferences | ((current: Preferences) => Preferences)) => void,
|
||||
boolean,
|
||||
] {
|
||||
const [initial] = useState(initializePreferences);
|
||||
const [preferences, setPreferences] = useState<Preferences>(
|
||||
initial.preferences
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
writePreferences(preferences);
|
||||
} catch {
|
||||
// The UI already reports storage that was unavailable during initialization.
|
||||
// A later quota/privacy-mode failure leaves this session's in-memory choices intact.
|
||||
}
|
||||
}, [preferences]);
|
||||
|
||||
return [preferences, setPreferences, initial.storageAvailable];
|
||||
}
|
||||
Reference in New Issue
Block a user