Skip to content

Commit 9dffa43

Browse files
authored
Apply a class to <em>'s containing Japanese characters (#94)
* Add Gatsby plugin and CSS rule to fix emphasis issue with Japanese characters * Fix code style issue * Fix hasJapanese unicode codepoints * Fix typo, comment, function rename
1 parent 81db23d commit 9dffa43

File tree

5 files changed

+38
-0
lines changed

5 files changed

+38
-0
lines changed

gatsby-browser.js

+3
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ require('./src/css/reset.css');
1515
require('./src/prism-styles');
1616
require('./src/css/algolia.css');
1717

18+
// Import Japanese style fix CSS
19+
require('./src/css/ja-fix.css');
20+
1821
// Expose React and ReactDOM as globals for console playground
1922
window.React = React;
2023
window.ReactDOM = ReactDOM;

gatsby-config.js

+1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ module.exports = {
5555
maxWidth: 840,
5656
},
5757
},
58+
'gatsby-remark-japanese-fix',
5859
'gatsby-remark-header-custom-ids',
5960
{
6061
resolve: 'gatsby-remark-code-repls',
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const toString = require('mdast-util-to-string');
2+
const visit = require('unist-util-visit');
3+
4+
const hasJapaneseCharacter = str => {
5+
// Detects katakana, hiragana, iteration marks, and CJK unified ideographs
6+
return /[\u30a0-\u30ff\u3040-\u309f\u3005-\u3006\u4e00-\u9fea]/.test(str);
7+
};
8+
9+
/**
10+
* Iterates over emphases (<em>'s) within the AST created by remark.
11+
* Applies 'em-ja' class only when it contains a Japanese character,
12+
* so that it can be displayed with a different style.
13+
*/
14+
15+
module.exports = ({markdownAST}, options) => {
16+
visit(markdownAST, 'emphasis', node => {
17+
const nodeStr = toString(node);
18+
if (hasJapaneseCharacter(nodeStr)) {
19+
// Patch AST
20+
node.data = node.data || {};
21+
node.data.hProperties = node.data.hProperties || {};
22+
node.data.hProperties.class = 'em-ja';
23+
}
24+
});
25+
return markdownAST;
26+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"name": "gatsby-remark-japanese-fix",
3+
"version": "0.0.1"
4+
}

src/css/ja-fix.css

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
.em-ja {
2+
font-weight: bolder;
3+
font-style: normal;
4+
}

0 commit comments

Comments
 (0)