import { readActivePrefsSlot, type ActivePrefs, type ActivePrefsSlot } from '$prefs'; import type { Direction } from '$libs/direction'; import type { LocaleSource } from '$libs/locale'; export interface ActiveUixPrefsView { getDir(): Direction; onPreferenceChange(handler: () => void): () => void; } const DEFAULT_DIR: Direction = 'ltr'; export const readActiveUixPrefsSlot = readActivePrefsSlot as ( prefs: unknown, key: string ) => ActivePrefsSlot | undefined; export function createLocaleSourceFromPrefs(prefs: ActivePrefs): LocaleSource | undefined { const localeSlot = readActiveUixPrefsSlot(prefs, 'locale'); if (!localeSlot) return undefined; return { get: () => localeSlot.get(), onChange: (handler) => localeSlot.onChange(handler) }; } export function connectLangsToPrefs( langs: { setLocale(locale: string): void }, prefs: ActivePrefs ): (() => void) | undefined { const languageSlot = readActiveUixPrefsSlot(prefs, 'language'); if (!languageSlot) return undefined; langs.setLocale(languageSlot.get()); return languageSlot.onChange((value) => langs.setLocale(value)); } export function createActiveUixPrefsView(prefs: ActivePrefs): ActiveUixPrefsView { return { getDir(): Direction { return readActiveUixPrefsSlot(prefs, 'direction')?.get() ?? DEFAULT_DIR; }, onPreferenceChange(handler: () => void): () => void { const detachers = [ readActiveUixPrefsSlot(prefs, 'direction')?.onChange(handler) ].filter((off): off is () => void => typeof off === 'function'); return () => { for (const detach of detachers) detach(); }; } }; }