@messageformat/fluent
Version:
Conversion & compatibility tools for using Fluent with MessageFormat 2
39 lines (38 loc) • 1.52 kB
JavaScript
import { getLocaleDir } from 'messageformat/functions';
import { valueToMessageRef } from "./message-to-fluent.js";
/**
* Build a custom function for Fluent message and term references.
*
* By default, {@link fluentToResource} uses this with the id `fluent:message`.
*
* @param res - A Map of {@link MessageFormat} instances,
* one for each referrable message and term.
* This Map may be passed in as initially empty, and later filled out by the caller.
*/
export const getMessageFunction = (res) => function message(ctx, options, input) {
const onError = ctx.onError.bind(ctx);
const locale = ctx.locales[0];
const dir = ctx.dir ?? getLocaleDir(locale);
const { msgId, msgAttr } = valueToMessageRef(input ? String(input) : '');
const mf = res.get(msgId)?.get(msgAttr ?? '');
if (!mf)
throw new Error(`Message not available: ${msgId}`);
let str;
return {
type: 'fluent-message',
dir,
selectKey(keys) {
str ??= mf.format(options, onError);
return keys.has(str) ? str : null;
},
toParts() {
const parts = mf.formatToParts(options, onError);
const res = dir === 'ltr' || dir === 'rtl'
? { type: 'fluent-message', dir, locale, parts }
: { type: 'fluent-message', locale, parts };
return [res];
},
toString: () => (str ??= mf.format(options, onError)),
valueOf: () => (str ??= mf.format(options, onError))
};
};