feat(client,challenge-parser): render Chinese as ruby markup (#63424)

Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
This commit is contained in:
Huyen Nguyen
2025-11-10 11:25:57 -08:00
committed by GitHub
parent 14dd3c6b27
commit 0c844ab007
13 changed files with 601 additions and 128 deletions

View File

@@ -0,0 +1,78 @@
const mdastToHTML = require('./mdast-to-html');
/**
* Parses Chinese text in format: hanzi (pinyin)
* @param {string} text - Text in format: hanzi (pinyin)
* @returns {{ hanzi: string, pinyin: string } | null} Parsed hanzi and pinyin, or null if not matching
*/
function parseChinesePattern(text) {
const match = text.match(/^(.+?)\s*\((.+?)\)$/);
if (!match) {
return null;
}
return {
hanzi: match[1].trim(),
pinyin: match[2].trim()
};
}
/**
* Custom handler for Chinese inline code to render as ruby elements
* @param {object} state - The state object from mdast-util-to-hast
* @param {object} node - The inlineCode node
* @returns {object} Hast element node
*/
function chineseInlineCodeHandler(state, node) {
const parsed = parseChinesePattern(node.value);
if (parsed) {
return {
type: 'element',
tagName: 'ruby',
properties: {},
children: [
{ type: 'text', value: parsed.hanzi },
{
type: 'element',
tagName: 'rp',
properties: {},
children: [{ type: 'text', value: '(' }]
},
{
type: 'element',
tagName: 'rt',
properties: {},
children: [{ type: 'text', value: parsed.pinyin }]
},
{
type: 'element',
tagName: 'rp',
properties: {},
children: [{ type: 'text', value: ')' }]
}
]
};
}
return {
type: 'element',
// TODO: change this to span
// https://github.com/freeCodeCamp/language-curricula/issues/22
tagName: 'code',
properties: {},
children: [{ type: 'text', value: node.value }]
};
}
const rubyOptions = {
handlers: {
inlineCode: chineseInlineCodeHandler
}
};
const createMdastToHtml = lang =>
lang == 'zh-CN' ? x => mdastToHTML(x, rubyOptions) : mdastToHTML;
module.exports = { parseChinesePattern, createMdastToHtml };