import { currency, getHTMLTextDir, getIntlayer, getLocaleName, type Locale, locales, } from 'intlayer'; /** Unit price of a cart item, in the currency below. */ const ITEM_PRICE = 12.5; const ITEM_CURRENCY = 'EUR'; const HTML_ENTITIES: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }; /** * Escapes the characters that would let a translated value break out of the * markup it is interpolated into. */ const escapeHtml = (value: string): string => value.replace( /[&<>"']/g, (character) => HTML_ENTITIES[character] ?? character ); /** * The cart fragment. Every htmx swap re-renders it for the locale of the * request that triggered the swap, so a fragment never keeps the language of * the page it was first rendered into. */ export const renderCart = (locale: Locale, itemCount: number): string => { const content = getIntlayer('app', locale); return `

${escapeHtml(String(content.cartSummary({ count: itemCount })))}

${escapeHtml(String(content.totalLabel))}: ${escapeHtml(currency(itemCount * ITEM_PRICE, { locale, currency: ITEM_CURRENCY }))}

`; }; /** * The locale switcher. Posting it swaps the whole ``, which is what makes * the static labels around the cart change language too. */ const renderLocaleSwitcher = (locale: Locale, itemCount: number): string => { const content = getIntlayer('app', locale); const options = locales .map( (availableLocale: Locale) => `` ) .join(''); return `
`; }; /** * The `` element, rendered on its own so the locale switcher can swap it * whole. `lang` and `dir` are repeated here because a swap cannot reach the * `` element; the script in the head copies them back up after the swap. */ export const renderBody = (locale: Locale, itemCount: number): string => { const content = getIntlayer('app', locale); return `

${escapeHtml(String(content.pageTitle))}

${escapeHtml(String(content.heading))}

${escapeHtml(String(content.greeting({ name: 'Ada' })))}

${renderLocaleSwitcher(locale, itemCount)} ${renderCart(locale, itemCount)}
`; }; /** The full document, served on a normal navigation. */ export const renderPage = (locale: Locale, itemCount: number): string => ` ${escapeHtml(String(getIntlayer('app', locale).pageTitle))} ${renderBody(locale, itemCount)} `;