Skip to content

Commit

Permalink
Apply a class to <em>'s containing Japanese characters (#94)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
smikitky committed Feb 7, 2019
1 parent 81db23d commit 9dffa43
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions gatsby-browser.js
Expand Up @@ -15,6 +15,9 @@ require('./src/css/reset.css');
require('./src/prism-styles');
require('./src/css/algolia.css');

// Import Japanese style fix CSS
require('./src/css/ja-fix.css');

// Expose React and ReactDOM as globals for console playground
window.React = React;
window.ReactDOM = ReactDOM;
Expand Down
1 change: 1 addition & 0 deletions gatsby-config.js
Expand Up @@ -55,6 +55,7 @@ module.exports = {
maxWidth: 840,
},
},
'gatsby-remark-japanese-fix',
'gatsby-remark-header-custom-ids',
{
resolve: 'gatsby-remark-code-repls',
Expand Down
26 changes: 26 additions & 0 deletions plugins/gatsby-remark-japanese-fix/index.js
@@ -0,0 +1,26 @@
const toString = require('mdast-util-to-string');
const visit = require('unist-util-visit');

const hasJapaneseCharacter = str => {
// Detects katakana, hiragana, iteration marks, and CJK unified ideographs
return /[\u30a0-\u30ff\u3040-\u309f\u3005-\u3006\u4e00-\u9fea。、]/.test(str);
};

/**
* Iterates over emphases (<em>'s) within the AST created by remark.
* Applies 'em-ja' class only when it contains a Japanese character,
* so that it can be displayed with a different style.
*/

module.exports = ({markdownAST}, options) => {
visit(markdownAST, 'emphasis', node => {
const nodeStr = toString(node);
if (hasJapaneseCharacter(nodeStr)) {
// Patch AST
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.class = 'em-ja';
}
});
return markdownAST;
};
4 changes: 4 additions & 0 deletions plugins/gatsby-remark-japanese-fix/package.json
@@ -0,0 +1,4 @@
{
"name": "gatsby-remark-japanese-fix",
"version": "0.0.1"
}
4 changes: 4 additions & 0 deletions src/css/ja-fix.css
@@ -0,0 +1,4 @@
.em-ja {
font-weight: bolder;
font-style: normal;
}

0 comments on commit 9dffa43

Please sign in to comment.