-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add initialization for i18next and handlebars
- Loading branch information
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import Handlebars from "handlebars"; | ||
import i18next from "i18next"; | ||
import ICU from "i18next-icu"; | ||
import Yaml from "js-yaml"; | ||
import { PluginInfo, TrialType } from "jspsych"; | ||
import en_us from "../i18n/en-us.yaml"; | ||
|
||
/** | ||
* Pulled from EFP. Function to convert researcher's text to HTML. | ||
* | ||
* @param text - Text | ||
* @returns Formatted string | ||
*/ | ||
export const expFormat = (text?: string | string[]) => { | ||
if (!text) { | ||
return ""; | ||
} | ||
|
||
if (Array.isArray(text)) { | ||
text = text.join("\n\n"); | ||
} | ||
|
||
return text | ||
.replace(/(\r\n|\n|\r)/gm, "<br>") | ||
.replace(/\t/gm, " "); | ||
}; | ||
|
||
/** | ||
* Initialize i18next with parameters from trial. | ||
* | ||
* @param trial - Trial data including user supplied parameters. | ||
*/ | ||
const initI18next = (trial: TrialType<PluginInfo>) => { | ||
const { locale } = trial; | ||
const translation = Yaml.load(en_us) as Record<string, string>; | ||
const a2Code = locale.split("-")[0]; | ||
const debug = process.env.DEBUG === "true"; | ||
|
||
i18next.use(ICU).init({ | ||
lng: locale, | ||
debug, | ||
resources: { | ||
[a2Code]: { | ||
translation, | ||
}, | ||
}, | ||
}); | ||
}; | ||
|
||
/** | ||
* Initialize handlebars helpers. This could be done globally, but it does go | ||
* hand in hand with initializing i18n. | ||
*/ | ||
const initHandlebars = () => { | ||
Handlebars.registerHelper("t", (context, { hash }) => | ||
i18next.t(context, hash), | ||
); | ||
Handlebars.registerHelper("exp-format", (context) => expFormat(context)); | ||
}; | ||
|
||
/** | ||
* Initialize both i18next and Handlebars. | ||
* | ||
* @param trial - Yup | ||
*/ | ||
export const init = (trial: TrialType<PluginInfo>) => { | ||
initI18next(trial); | ||
initHandlebars(); | ||
}; |