Implement utility function that recursively localizes based on the config data (implements #54)

This commit is contained in:
Oliver-Akins 2024-02-22 22:49:02 -07:00
parent 34c7dbed87
commit c1fa5b3d9b
3 changed files with 33 additions and 0 deletions

View file

@ -42,6 +42,11 @@ export const syncMilestones = [
export const syncDice = `1d20`;
export const localizerConfig = {
subKeyPattern: /@(?<key>[a-zA-Z\.]+)/gm,
maxDepth: 10,
};
export default {
stats,
statDice,
@ -57,4 +62,5 @@ export default {
itemTiers,
syncMilestones,
syncDice,
localizerConfig
};

View file

@ -0,0 +1,21 @@
import { localizerConfig } from "../config.mjs";
export function localizer(key, args = {}, depth = 0) {
/** @type {string} */
let localized = game.i18n.format(key, args);
const subkeys = localized.matchAll(localizerConfig.subKeyPattern);
// Short-cut to help prevent infinite recursion
if (depth > localizerConfig.maxDepth) {
return localized;
};
for (const match of subkeys) {
const subkey = match.groups.key;
localized =
localized.slice(0, match.index)
+ localizer(subkey.slice(1), args, depth + 1)
+ localized.slice(match.index + subkey.length)
};
return localized;
};

View file

@ -0,0 +1,6 @@
/*
The purpose of this script is to validate all of the language files to ensure
that there are no cycles in them to prevent infinite recursion. This must pull
the pattern to match subkeys on via the config, otherwise this could result in
inconsistencies with the localizer logic.
*/