Skip to content
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

Escape html #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
57 changes: 40 additions & 17 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,52 @@
import mermaid from 'mermaid'

const mermaidChart = (code) => {
try {
function escapeHtml(unsafe)
{
return unsafe
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}

const mermaidChart = (code) =>
{
try
{
mermaid.parse(code)
return `<div class="mermaid">${code}</div>`
} catch ({ str, hash }) {
return `<pre>${str}</pre>`
return `<!-- htmlmin:ignore --><div class="mermaid">${escapeHtml(code)}</div><!-- htmlmin:ignore -->`
} catch ({ str, hash })
{
return `<pre class="mermaid-error">${escapeHtml(str)}</pre>`
}
}

const MermaidPlugin = (md) => {
const MermaidPlugin = (md) =>
{
md.mermaid = mermaid
mermaid.loadPreferences = (preferenceStore) => {
mermaid.loadPreferences = (preferenceStore) =>
{
let mermaidTheme = preferenceStore.get('mermaid-theme')
if (mermaidTheme === undefined) {
if (mermaidTheme === undefined)
{
mermaidTheme = 'default'
}
let ganttAxisFormat = preferenceStore.get('gantt-axis-format')
if (ganttAxisFormat === undefined) {
if (ganttAxisFormat === undefined)
{
ganttAxisFormat = '%Y-%m-%d'
}
mermaid.initialize({
theme: mermaidTheme,
gantt: { axisFormatter: [
[ganttAxisFormat, (d) => {
return d.getDay() === 1
}]
]}
gantt: {
axisFormatter: [
[ganttAxisFormat, (d) =>
{
return d.getDay() === 1
}]
]
}
})
return {
'mermaid-theme': mermaidTheme,
Expand All @@ -35,14 +55,17 @@ const MermaidPlugin = (md) => {
}

const temp = md.renderer.rules.fence.bind(md.renderer.rules)
md.renderer.rules.fence = (tokens, idx, options, env, slf) => {
md.renderer.rules.fence = (tokens, idx, options, env, slf) =>
{
const token = tokens[idx]
const code = token.content.trim()
if (token.info === 'mermaid') {
if (token.info === 'mermaid')
{
return mermaidChart(code)
}
const firstLine = code.split(/\n/)[0].trim()
if (firstLine === 'gantt' || firstLine === 'sequenceDiagram' || firstLine.match(/^graph (?:TB|BT|RL|LR|TD);?$/)) {
if (firstLine === 'gantt' || firstLine === 'sequenceDiagram' || firstLine.match(/^graph (?:TB|BT|RL|LR|TD);?$/))
{
return mermaidChart(code)
}
return temp(tokens, idx, options, env, slf)
Expand Down