You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.6 KiB
53 lines
1.6 KiB
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 <T>(
|
|
prefs: unknown,
|
|
key: string
|
|
) => ActivePrefsSlot<T> | undefined;
|
|
|
|
export function createLocaleSourceFromPrefs(prefs: ActivePrefs): LocaleSource | undefined {
|
|
const localeSlot = readActiveUixPrefsSlot<string>(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<string>(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<Direction>(prefs, 'direction')?.get() ?? DEFAULT_DIR;
|
|
},
|
|
onPreferenceChange(handler: () => void): () => void {
|
|
const detachers = [
|
|
readActiveUixPrefsSlot<Direction>(prefs, 'direction')?.onChange(handler)
|
|
].filter((off): off is () => void => typeof off === 'function');
|
|
|
|
return () => {
|
|
for (const detach of detachers) detach();
|
|
};
|
|
}
|
|
};
|
|
}
|