mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-05 09:01:18 -04:00
feat(client,challenge-parser): render Chinese as ruby markup (#63424)
Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user