/FuriganaParser.js Secret
Created
August 31, 2021 19:56
Star
You must be signed in to star a gist
Converts Anki styled Furigana to Ruby style in React
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
import { Fragment } from 'react' | |
export const formatFurigana = (sentenceId, sentence) => { | |
// sentenceId is used for the unique keys for each of the Furigana and Kanji text components | |
if (sentence === undefined) { | |
return '' | |
} | |
let compiled_list = [] | |
let text = ''; | |
let parsing_furigana = false; | |
let finding_kanji = false; | |
let furigana = ''; | |
let kanji = ''; | |
let start; | |
for (let i = sentence.length-1; i >= 0; i--) { | |
if (sentence[i] === ']') { | |
start = i; | |
parsing_furigana = true; | |
if (text.length > 0) { | |
compiled_list.unshift({ | |
furigana: text, | |
kanji: '' | |
}) | |
text = ''; | |
} | |
} else if (sentence[i] === '[') { | |
parsing_furigana = false; | |
finding_kanji = true; | |
} else if (parsing_furigana) { | |
furigana = sentence[i] + furigana; | |
} else if (finding_kanji) { | |
if (i === 0 || sentence[i] === ' ') { | |
kanji = sentence[i] + kanji; | |
compiled_list.unshift({ | |
furigana: furigana, | |
kanji: kanji | |
}) | |
furigana = ''; | |
kanji = ''; | |
finding_kanji = false; | |
} else { | |
kanji = sentence[i] + kanji; | |
} | |
} else { | |
text = sentence[i] + text; | |
} | |
} | |
compiled_list.unshift({ | |
furigana: text, | |
kanji: '' | |
}) | |
return ( | |
compiled_list.map((item, index)=>( | |
item.kanji.length > 0 ? | |
<ruby key={`example_${sentenceId}_item${index}`}> | |
{item.kanji} | |
<rt style={{WebkitUserSelect: 'none'}}>{item.furigana}</rt> | |
</ruby> | |
: | |
<Fragment key={`example_${sentenceId}_item${index}`}> | |
{item.furigana} | |
</Fragment> | |
)) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment