35 lines
1 KiB
JavaScript
35 lines
1 KiB
JavaScript
import { html, useEffect, useContext, useState, createContext } from 'https://unpkg.com/htm/preact/standalone.module.js'
|
|
|
|
const LocaleContext = createContext({});
|
|
|
|
export function tr(string, params = {}) {
|
|
const { locales } = useContext(LocaleContext);
|
|
let translated = locales[string] || string;
|
|
|
|
for (const [key, value] of Object.entries(params)) {
|
|
translated = translated.replace(`{${key}}`, value);
|
|
}
|
|
|
|
return html([translated]);
|
|
}
|
|
|
|
export function formatDate(date) {
|
|
const { lang } = useContext(LocaleContext);
|
|
return Intl.DateTimeFormat(lang, {dateStyle: 'medium', timeStyle: 'short'}).format(date);
|
|
}
|
|
|
|
export function Localized({ lang, children }) {
|
|
const [localeStrings, setLocaleStrings] = useState({});
|
|
|
|
useEffect(() => {
|
|
fetch(`static/locales/${lang}.json`)
|
|
.then(response => response.json())
|
|
.then(d => setLocaleStrings(d));
|
|
}, [ lang ]);
|
|
|
|
return html`
|
|
<${LocaleContext.Provider} value="${{locales: localeStrings, lang }}">
|
|
${children}
|
|
<//>
|
|
`;
|
|
}
|