Skip to content

Apply a class to <em>'s containing Japanese characters #94

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions gatsby-browser.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "gatsby-remark-japanese-fix",
"version": "0.0.1"
}
4 changes: 4 additions & 0 deletions src/css/ja-fix.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.em-ja {
font-weight: bolder;
font-style: normal;
}