From 706dc1d71091e90ce188dda30509606092496f02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vojt=C4=9Bch=20Srde=C4=8Dn=C3=BD?= Date: Mon, 11 Nov 2019 16:03:09 +0100 Subject: [PATCH] Move TextNode escaping to a separate rule, escapes to options and simplify node processing. --- src/commonmark-rules.js | 11 +++++++++++ src/turndown.js | 26 +++----------------------- 2 files changed, 14 insertions(+), 23 deletions(-) diff --git a/src/commonmark-rules.js b/src/commonmark-rules.js index f009aca8..35445f67 100644 --- a/src/commonmark-rules.js +++ b/src/commonmark-rules.js @@ -2,6 +2,17 @@ import { repeat } from './utilities' var rules = {} +rules.text = { + filter: '#text', + + replacement: function (content, node, options) { + if (node.isCode) return node.nodeValue + return options.escapes.reduce(function (accumulator, escape) { + return accumulator.replace(escape[0], escape[1]) + }, node.nodeValue).trim() + } +} + rules.paragraph = { filter: 'p', diff --git a/src/turndown.js b/src/turndown.js index bcd4d60b..1cc76101 100644 --- a/src/turndown.js +++ b/src/turndown.js @@ -6,7 +6,7 @@ import Node from './node' var reduce = Array.prototype.reduce var leadingNewLinesRegExp = /^\n*/ var trailingNewLinesRegExp = /\n*$/ -var escapes = [ +var DEFAULT_ESCAPES = [ [/\\/g, '\\\\'], [/\*/g, '\\*'], [/^-/g, '\\-'], @@ -27,6 +27,7 @@ export default function TurndownService (options) { var defaults = { rules: COMMONMARK_RULES, + escapes: DEFAULT_ESCAPES, headingStyle: 'setext', hr: '* * *', bulletListMarker: '*', @@ -130,20 +131,6 @@ TurndownService.prototype = { remove: function (filter) { this.rules.remove(filter) return this - }, - - /** - * Escapes Markdown syntax - * @public - * @param {String} string The string to escape - * @returns A string with Markdown syntax escaped - * @type String - */ - - escape: function (string) { - return escapes.reduce(function (accumulator, escape) { - return accumulator.replace(escape[0], escape[1]) - }, string) } } @@ -159,14 +146,7 @@ function process (parentNode) { var self = this return reduce.call(parentNode.childNodes, function (output, node) { node = new Node(node) - - var replacement = '' - if (node.nodeType === 3) { - replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue) - } else if (node.nodeType === 1) { - replacement = replacementForNode.call(self, node) - } - + var replacement = replacementForNode.call(self, node) return join(output, replacement) }, '') }