2023-07-29 17:57:14 +01:00
|
|
|
import clamp from 'just-clamp';
|
|
|
|
|
import { persisted } from 'svelte-local-storage-store';
|
|
|
|
|
|
|
|
|
|
export interface UserPreferences {
|
|
|
|
|
playback_rate: number;
|
|
|
|
|
volume: number;
|
2026-07-21 18:57:26 -04:00
|
|
|
muted: boolean;
|
2023-07-29 17:57:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The default user preferences
|
|
|
|
|
*/
|
|
|
|
|
const DEFAULT_USER_PREFERENCES: UserPreferences = {
|
|
|
|
|
playback_rate: 1,
|
|
|
|
|
volume: 1,
|
2026-07-21 18:57:26 -04:00
|
|
|
muted: false,
|
2023-07-29 17:57:14 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The user preferences store
|
|
|
|
|
*/
|
|
|
|
|
export const USER_PREFERENCES_STORE = persisted<UserPreferences>(
|
|
|
|
|
'USER_PREFERENCE',
|
|
|
|
|
DEFAULT_USER_PREFERENCES,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Sets the playback rate for the user
|
|
|
|
|
* @param value - The playback rate value
|
|
|
|
|
*/
|
|
|
|
|
const set_playback_rate = (value: number) => {
|
|
|
|
|
const playback_rate = clamp(value, 0.5, 5);
|
|
|
|
|
return USER_PREFERENCES_STORE.update((prefs) => ({
|
|
|
|
|
...prefs,
|
|
|
|
|
playback_rate,
|
|
|
|
|
}));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Sets the volume for the user
|
|
|
|
|
* @param value - The volume value
|
|
|
|
|
*/
|
|
|
|
|
const set_volume = (value: number) => {
|
|
|
|
|
const volume = clamp(value, 0, 1);
|
|
|
|
|
return USER_PREFERENCES_STORE.update((prefs) => ({ ...prefs, volume }));
|
|
|
|
|
};
|
|
|
|
|
|
2026-07-21 18:57:26 -04:00
|
|
|
/**
|
|
|
|
|
* Sets the muted state for the user. This is the single source of truth
|
|
|
|
|
* for mute: the audio element is kept in sync with it.
|
|
|
|
|
* @param value - The muted value
|
|
|
|
|
*/
|
|
|
|
|
const set_muted = (value: boolean) => {
|
|
|
|
|
return USER_PREFERENCES_STORE.update((prefs) => ({ ...prefs, muted: value }));
|
|
|
|
|
};
|
|
|
|
|
|
2023-07-29 17:57:14 +01:00
|
|
|
/**
|
|
|
|
|
* Clears user preferences store
|
|
|
|
|
*/
|
|
|
|
|
const clear_store = () => USER_PREFERENCES_STORE.set(DEFAULT_USER_PREFERENCES);
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The user preferences object
|
|
|
|
|
*/
|
|
|
|
|
export const user_preferences = {
|
|
|
|
|
subscribe: USER_PREFERENCES_STORE.subscribe,
|
|
|
|
|
set_playback_rate,
|
|
|
|
|
set_volume,
|
2026-07-21 18:57:26 -04:00
|
|
|
set_muted,
|
2023-07-29 17:57:14 +01:00
|
|
|
clear: clear_store,
|
|
|
|
|
};
|