Skip to content

Commit

Permalink
Add code title
Browse files Browse the repository at this point in the history
  • Loading branch information
churabou committed Apr 27, 2020
1 parent 660e608 commit 6b3a888
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
1 change: 1 addition & 0 deletions gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ module.exports = {
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
"gatsby-remark-code-name",
{
resolve: `gatsby-remark-prismjs`,
},
Expand Down
12 changes: 11 additions & 1 deletion index.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
body {
margin: 0px;
--theme-color: hsl(209, 47%, 35%);
}
}

.gatsby-remark-code-name {
margin: 0px 0px -0.5em 0.5em;
}

.gatsby-remark-code-name span {
background: gray;
color: white;
padding: 0.25em;
}
30 changes: 30 additions & 0 deletions plugins/gatsby-remark-code-name/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"use strict"
const visit = require("unist-util-visit")

module.exports = ({ markdownAST }) => {
// copy children to prevent infinity roop when splice node
const children = [...markdownAST.children]
let insertCount = 0
visit(markdownAST, "code", (node, index) => {
const { lang } = node
if (!lang) return
const [name, extension] = lang.split(".")
const title = name && extension ? lang : null
if (title) {
const className = "gatsby-remark-code-name"
const titleNode = {
type: "html",
value: `
<div class=${className}>
<span>${title}</span>
</div>
`.trim(),
}
children.splice(index + insertCount, 0, titleNode)
insertCount += 1
}
node.lang = extension || name
})
markdownAST.children = children
return markdownAST
}
6 changes: 6 additions & 0 deletions plugins/gatsby-remark-code-name/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "gatsby-remark-code-name",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}

0 comments on commit 6b3a888

Please sign in to comment.