A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(email): use recipient time zone, isolate values in rtl mail
Hampus7d7ab5386ebc
diff --git a/fluxer_api/pkgs/email/src/email_i18n/EmailI18n.ts b/fluxer_api/pkgs/email/src/email_i18n/EmailI18n.tsindex c979a9435..541de3c21 100644--- a/fluxer_api/pkgs/email/src/email_i18n/EmailI18n.ts+++ b/fluxer_api/pkgs/email/src/email_i18n/EmailI18n.ts@@ -4,6 +4,7 @@ import {compileMessage} from '@fluxer/i18n/src/runtime/CompileMessage';import {createStaticI18n} from '@fluxer/i18n/src/runtime/CreateStaticI18n';import type {I18nResult} from '@fluxer/i18n/src/runtime/I18nTypes';import {validateMessageTemplateVariables} from '@fluxer/i18n/src/runtime/MessageCatalogTypes';+import {getEmailTextDirection, inertEmailValue, isolateEmailValue} from '@pkgs/email/src/email_html/EmailHtmlRenderer';import {EMAIL_I18N_LOCALE_MESSAGES} from '@pkgs/email/src/email_i18n/EmailI18nLocales';import {EMAIL_I18N_MESSAGES} from '@pkgs/email/src/email_i18n/EmailI18nMessages';import type {EmailTemplateVariables} from '@pkgs/email/src/email_i18n/EmailI18nTypes';@@ -12,8 +13,45 @@ import type {EmailTemplate, EmailTemplateKey} from '@pkgs/email/src/email_i18n/Econst DEFAULT_LOCALE = 'en-US';const DOUBLED_PERIOD = /(?<!\.)\.\.(?!\.)/g;-function formatEmailDate(value: unknown, locale: string, style: string | null): string {- const options: Intl.DateTimeFormatOptions = {timeZone: 'UTC', day: 'numeric', month: 'short', year: 'numeric'};+const CALENDAR_DAY = /^\d{4}-\d{2}-\d{2}$/;+const INERT_VARIABLES = new Set(['otherName', 'recipientName', 'senderName', 'statement', 'username', 'wallName']);+const ISOLATED_VARIABLES = new Set([+ 'amount',+ 'amountFormatted',+ 'priceFormatted',+ 'founderName',+ 'otherName',+ 'recipientName',+ 'senderName',+ 'username',+ 'wallName',+ 'consentText',+ 'appeal_deadline',+ 'deletion_date',+]);++function isolateForLocale(value: string, locale: string): string {+ return getEmailTextDirection(locale) === 'rtl' ? isolateEmailValue(value) : value;+}++function resolveEmailTimeZone(timeZone: string | null | undefined): string | null {+ if (!timeZone) return null;+ try {+ new Intl.DateTimeFormat('en-US', {timeZone});+ return timeZone;+ } catch {+ return null;+ }+}++function formatEmailDate(value: unknown, locale: string, style: string | null, timeZone: string | null): string {+ const calendarDay = typeof value === 'string' && CALENDAR_DAY.test(value);+ const options: Intl.DateTimeFormatOptions = {+ timeZone: calendarDay ? 'UTC' : (timeZone ?? 'UTC'),+ day: 'numeric',+ month: 'short',+ year: 'numeric',+ };if (style === 'full') {options.weekday = 'long';options.month = 'long';@@ -22,53 +60,103 @@ function formatEmailDate(value: unknown, locale: string, style: string | null):} else if (style === 'short') {options.month = 'numeric';}- return new Date(value as string | number | Date).toLocaleDateString(locale, options);+ const date = calendarDay ? new Date(`${value}T00:00:00Z`) : new Date(value as string | number | Date);+ return date.toLocaleDateString(locale, options);}-function formatEmailTime(value: unknown, locale: string, style: string | null): string {+function formatEmailTime(value: unknown, locale: string, style: string | null, timeZone: string | null): string {const options: Intl.DateTimeFormatOptions = {- timeZone: 'UTC',- timeZoneName: 'short',+ timeZone: timeZone ?? 'UTC',hour: 'numeric',minute: 'numeric',+ ...(timeZone ? {} : {timeZoneName: 'short'}),};if (style === 'full' || style === 'long') {options.second = 'numeric';}- return new Date(value as string | number | Date).toLocaleTimeString(locale, options);+ const parts = new Intl.DateTimeFormat(locale, options).formatToParts(new Date(value as string | number | Date));+ const zone = parts.find((part) => part.type === 'timeZoneName');+ if (!zone) return parts.map((part) => part.value).join('');+ const time = parts+ .filter((part) => part.type !== 'timeZoneName')+ .map((part) => part.value)+ .join('')+ .replace(/[\s;,[\]()]+$/u, '')+ .replace(/^[\s;,[\]()]+/u, '');+ return parts.indexOf(zone) === 0 ? `${zone.value} ${time}` : `${time} ${zone.value}`;}-const emailI18n = createStaticI18n<EmailTemplateKey, EmailTemplate, Record<string, unknown>>(- {- defaultLocale: DEFAULT_LOCALE,- defaultMessages: EMAIL_I18N_MESSAGES,- localeMessages: EMAIL_I18N_LOCALE_MESSAGES,- onWarning: (message) => {- if (message.startsWith('Unsupported locale, falling back to en-US:')) {- console.warn(- `Unsupported locale for email translations, falling back to en-US: ${message.split(': ').slice(1).join(': ')}`,- );- } else {- console.warn(message);+function createEmailI18n(timeZone: string | null) {+ return createStaticI18n<EmailTemplateKey, EmailTemplate, Record<string, unknown>>(+ {+ defaultLocale: DEFAULT_LOCALE,+ defaultMessages: EMAIL_I18N_MESSAGES,+ localeMessages: EMAIL_I18N_LOCALE_MESSAGES,+ onWarning: (message) => {+ if (message.startsWith('Unsupported locale, falling back to en-US:')) {+ console.warn(+ `Unsupported locale for email translations, falling back to en-US: ${message.split(': ').slice(1).join(': ')}`,+ );+ } else {+ console.warn(message);+ }+ },+ validateVariables: (_key, template, variables) => {+ for (const text of Object.values(template)) {+ const error = validateMessageTemplateVariables(text, variables);+ if (error) {+ return error;+ }+ }+ return null;+ },+ messageFormatOptions: {+ customFormatters: {+ date: (value: unknown, locale: string, style: string | null) =>+ isolateForLocale(formatEmailDate(value, locale, style, timeZone), locale),+ time: (value: unknown, locale: string, style: string | null) =>+ isolateForLocale(formatEmailTime(value, locale, style, timeZone), locale),+ },+ },+ },+ (template, variables, mf) => {+ const compiled: EmailTemplate = {subject: '', intro: ''};+ for (const [field, text] of Object.entries(template)) {+ compiled[field] = String(compileMessage(mf, text)(variables)).replace(DOUBLED_PERIOD, '.');}+ return compiled;},- validateVariables: (_key, template, variables) =>- validateMessageTemplateVariables(template.subject, variables) ??- validateMessageTemplateVariables(template.body, variables),- messageFormatOptions: {customFormatters: {date: formatEmailDate, time: formatEmailTime}},- },- (template, variables, mf) => {- const compiledSubject = String(compileMessage(mf, template.subject)(variables)).replace(DOUBLED_PERIOD, '.');- const compiledBody = String(compileMessage(mf, template.body)(variables)).replace(DOUBLED_PERIOD, '.');- return {subject: compiledSubject, body: compiledBody};- },-);+ );+}++const emailI18nByTimeZone = new Map<string | null, ReturnType<typeof createEmailI18n>>();++function getEmailI18n(timeZone: string | null): ReturnType<typeof createEmailI18n> {+ let instance = emailI18nByTimeZone.get(timeZone);+ if (!instance) {+ instance = createEmailI18n(timeZone);+ emailI18nByTimeZone.set(timeZone, instance);+ }+ return instance;+}export function getEmailTemplate<T extends EmailTemplateKey>(templateKey: T,locale: string | null,variables: EmailTemplateVariables[T],productName: string,+ timeZone: string | null = null,): I18nResult<EmailTemplateKey, EmailTemplate> {- return emailI18n.getTemplate(templateKey, locale, {...variables, product_name: productName});+ const resolvedLocale = locale ?? DEFAULT_LOCALE;+ const isolated = Object.fromEntries(+ Object.entries(variables as Record<string, unknown>).map(([name, value]) => {+ if (typeof value !== 'string') return [name, value];+ const inert = INERT_VARIABLES.has(name) ? inertEmailValue(value) : value;+ return [name, ISOLATED_VARIABLES.has(name) ? isolateForLocale(inert, resolvedLocale) : inert];+ }),+ );+ return getEmailI18n(resolveEmailTimeZone(timeZone)).getTemplate(templateKey, locale, {+ ...isolated,+ product_name: productName,+ });}diff --git a/fluxer_api/pkgs/email/src/email_i18n/EmailI18nTimeZone.test.ts b/fluxer_api/pkgs/email/src/email_i18n/EmailI18nTimeZone.test.tsnew file mode 100644index 000000000..87705e359--- /dev/null+++ b/fluxer_api/pkgs/email/src/email_i18n/EmailI18nTimeZone.test.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {getEmailTemplate} from '@pkgs/email/src/email_i18n/EmailI18n';+import {describe, expect, it} from 'vitest';++function render<T extends Parameters<typeof getEmailTemplate>[0]>(+ key: T,+ locale: string,+ variables: Parameters<typeof getEmailTemplate<T>>[2],+ timeZone: string | null,+) {+ const result = getEmailTemplate(key, locale, variables, 'Fluxer', timeZone);+ expect(result.ok).toBe(true);+ if (!result.ok) throw new Error(result.error.message);+ return result.value;+}++describe('email dates and times', () => {+ it('words the code expiry relative to now', () => {+ const template = render('sign_in_code', 'sv-SE', {minutes: 10}, null);+ expect(template.expiry).toBe('Koden går ut om 10 minuter.');+ expect(render('reauth_code', 'en-US', {minutes: 1}, null).expiry).toBe('This code expires in 1 minute.');+ });+});