import { derived, type Readable } from 'svelte/store'; import { json } from 'svelte-i18n'; import type { Locale } from '$lib/Locale/layout'; type FormatXMLElementFn = (parts: Array) => R; type InterpolationValue = | string | number | boolean | Date | FormatXMLElementFn | null | undefined; type InterpolationValues = Record | undefined; interface Options { id?: string; locale?: string; format?: string; default?: string; values?: InterpolationValues; } const createLocale = () => { return derived(json, ($json) => { return (options: Options = {}) => new Proxy( {}, { get(_target, key) { const localisation = $json(key.toString(), options.locale); if (localisation === key.toString()) return undefined; const replaceValues = ( localisation: InterpolationValues, values: InterpolationValues ) => { if (typeof localisation !== 'object' || localisation === null) return localisation; const updatedLocalisation: InterpolationValues = {}; for (const [key, value] of Object.entries(localisation)) { if (typeof value === 'string') { updatedLocalisation[key] = value.replace( /\{(\w+)\}/g, (match, name) => (values ? values[name] : match) as string ); } else { updatedLocalisation[key] = replaceValues( value as InterpolationValues, values ) as InterpolationValue; } } return updatedLocalisation; }; if (options.values) return replaceValues(localisation as unknown as InterpolationValues, options.values); return localisation; } } ); }) as Readable<(options?: Options) => Locale>; }; const locale = createLocale(); export default locale;