i18n: Initialize FormatJS.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2021-04-09 18:11:59 -07:00
committed by Tim Abbott
parent 6cf398f157
commit 4b4cea90a3
7 changed files with 518 additions and 37 deletions

View File

@@ -1,5 +1,59 @@
"use strict";
const {createIntl, createIntlCache} = require("@formatjs/intl");
const _ = require("lodash");
const cache = createIntlCache();
exports.intl = createIntl(
{
locale: "en",
defaultLocale: "en",
defaultRichTextElements: Object.fromEntries(
["b", "code", "em", "i", "kbd", "p", "strong"].map((tag) => [
tag,
(content_html) => `<${tag}>${content_html}</${tag}>`,
]),
),
},
cache,
);
exports.$t = (descriptor, values) =>
"translated: " +
exports.intl.formatMessage(
{
...descriptor,
id: `${descriptor.defaultMessage}#${descriptor.description}`,
},
values,
);
const default_html_elements = Object.fromEntries(
["b", "code", "em", "i", "kbd", "p", "strong"].map((tag) => [
tag,
(content_html) => `<${tag}>${content_html}</${tag}>`,
]),
);
exports.$t_html = (descriptor, values) =>
"translated HTML: " +
exports.intl.formatMessage(
{
...descriptor,
id: `${descriptor.defaultMessage}#${descriptor.description}`,
},
{
...default_html_elements,
...Object.fromEntries(
Object.entries(values ?? {}).map(([key, value]) => [
key,
typeof value === "function" ? value : _.escape(value),
]),
),
},
);
exports.i18n = {};
exports.i18n.t = function (str, context) {
// HAPPY PATH: most translations are a simple string: