import chadApi from '#shared/chad-api' import { createGlobalState, useLocalStorage, watchDebounced } from '@vueuse/core' export interface SyncedPreferences { toggleInputHotkey: string toggleOutputHotkey: string volumes: Record } export const usePreferences = createGlobalState(() => { const { videoInputs, audioInputs, audioOutputs } = useDevices() const synced = ref(false) const inputDeviceId = useLocalStorage('INPUT_DEVICE_ID', 'default') const outputDeviceId = useLocalStorage('OUTPUT_DEVICE_ID', 'default') const autoGainControl = useLocalStorage('AUTO_GAIN_CONTROL', false) const noiseSuppression = useLocalStorage('NOISE_SUPPRESSION', true) const echoCancellation = useLocalStorage('ECHO_CANCELLATION', true) const toggleInputHotkey = ref('') const toggleOutputHotkey = ref('') const inputDeviceExist = computed(() => { return audioInputs.value.some(device => device.deviceId === inputDeviceId.value) }) const outputDeviceExist = computed(() => { return audioOutputs.value.some(device => device.deviceId === outputDeviceId.value) }) watchDebounced( [toggleInputHotkey, toggleOutputHotkey], async ([toggleInputHotkey, toggleOutputHotkey]) => { try { await chadApi( '/preferences', { method: 'PATCH', body: { toggleInputHotkey, toggleOutputHotkey, }, }, ) } catch {} }, { debounce: 1000 }, ) return { synced, inputDeviceId, outputDeviceId, autoGainControl, noiseSuppression, echoCancellation, toggleInputHotkey, toggleOutputHotkey, inputDeviceExist, outputDeviceExist, } })