mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-02-17 07:00:57 -05:00
79 lines
1.9 KiB
JavaScript
79 lines
1.9 KiB
JavaScript
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 };
|