Debian Codegraph @

src/turndown.js

raw symbols SCIP
1 import COMMONMARK_RULES from './commonmark-rules'
2 import Rules from './rules'
3 import { escapeMarkdown, extend, trimLeadingNewlines, trimTrailingNewlines } from './utilities'
4 import RootNode from './root-node'
5 import Node from './node'
6 const reduce = Array.prototype.reduce
7
8 export default function TurndownService (options) {
9 if (!(this instanceof TurndownService)) return new TurndownService(options)
10
11 const defaults = {
12 rules: COMMONMARK_RULES,
13 headingStyle: 'setext',
14 hr: '* * *',
15 bulletListMarker: '*',
16 codeBlockStyle: 'indented',
17 fence: '```',
18 emDelimiter: '_',
19 strongDelimiter: '**',
20 linkStyle: 'inlined',
21 linkReferenceStyle: 'full',
22 br: ' ',
23 preformattedCode: false,
24 blankReplacement: function (content, node) {
25 return node.isBlock ? '\n\n' : ''
26 },
27 keepReplacement: function (content, node) {
28 return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML
29 },
30 defaultReplacement: function (content, node) {
31 return node.isBlock ? '\n\n' + content + '\n\n' : content
32 }
33 }
34 this.options = extend({}, defaults, options)
35 this.rules = new Rules(this.options)
36 }
37
38 TurndownService.prototype = {
39 /**
40 * The entry point for converting a string or DOM node to Markdown
41 * @public
42 * @param {String|HTMLElement} input The string or DOM node to convert
43 * @returns A Markdown representation of the input
44 * @type String
45 */
46
47 turndown: function (input) {
48 if (!canConvert(input)) {
49 throw new TypeError(
50 input + ' is not a string, or an element/document/fragment node.'
51 )
52 }
53
54 if (input === '') return ''
55
56 const output = process.call(this, new RootNode(input, this.options))
57 return postProcess.call(this, output)
58 },
59
60 /**
61 * Add one or more plugins
62 * @public
63 * @param {Function|Array} plugin The plugin or array of plugins to add
64 * @returns The Turndown instance for chaining
65 * @type Object
66 */
67
68 use: function (plugin) {
69 if (Array.isArray(plugin)) {
70 for (let i = 0; i < plugin.length; i++) this.use(plugin[i])
71 } else if (typeof plugin === 'function') {
72 plugin(this)
73 } else {
74 throw new TypeError('plugin must be a Function or an Array of Functions')
75 }
76 return this
77 },
78
79 /**
80 * Adds a rule
81 * @public
82 * @param {String} key The unique key of the rule
83 * @param {Object} rule The rule
84 * @returns The Turndown instance for chaining
85 * @type Object
86 */
87
88 addRule: function (key, rule) {
89 this.rules.add(key, rule)
90 return this
91 },
92
93 /**
94 * Keep a node (as HTML) that matches the filter
95 * @public
96 * @param {String|Array|Function} filter The unique key of the rule
97 * @returns The Turndown instance for chaining
98 * @type Object
99 */
100
101 keep: function (filter) {
102 this.rules.keep(filter)
103 return this
104 },
105
106 /**
107 * Remove a node that matches the filter
108 * @public
109 * @param {String|Array|Function} filter The unique key of the rule
110 * @returns The Turndown instance for chaining
111 * @type Object
112 */
113
114 remove: function (filter) {
115 this.rules.remove(filter)
116 return this
117 },
118
119 /**
120 * Escapes Markdown syntax
121 * @public
122 * @param {String} string The string to escape
123 * @returns A string with Markdown syntax escaped
124 * @type String
125 */
126
127 escape: function (string) {
128 return escapeMarkdown(string)
129 }
130 }
131
132 /**
133 * Reduces a DOM node down to its Markdown string equivalent
134 * @private
135 * @param {HTMLElement} parentNode The node to convert
136 * @returns A Markdown representation of the node
137 * @type String
138 */
139
140 function process (parentNode) {
141 const self = this
142 return reduce.call(parentNode.childNodes, function (output, node) {
143 node = new Node(node, self.options)
144
145 let replacement = ''
146 if (node.nodeType === 3) {
147 replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue)
148 } else if (node.nodeType === 1) {
149 replacement = replacementForNode.call(self, node)
150 }
151
152 return join(output, replacement)
153 }, '')
154 }
155
156 /**
157 * Appends strings as each rule requires and trims the output
158 * @private
159 * @param {String} output The conversion output
160 * @returns A trimmed version of the ouput
161 * @type String
162 */
163
164 function postProcess (output) {
165 const self = this
166 this.rules.forEach(function (rule) {
167 if (typeof rule.append === 'function') {
168 output = join(output, rule.append(self.options))
169 }
170 })
171
172 return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
173 }
174
175 /**
176 * Converts an element node to its Markdown equivalent
177 * @private
178 * @param {HTMLElement} node The node to convert
179 * @returns A Markdown representation of the node
180 * @type String
181 */
182
183 function replacementForNode (node) {
184 const rule = this.rules.forNode(node)
185 let content = process.call(this, node)
186 const whitespace = node.flankingWhitespace
187 if (whitespace.leading || whitespace.trailing) content = content.trim()
188 return (
189 whitespace.leading +
190 rule.replacement(content, node, this.options) +
191 whitespace.trailing
192 )
193 }
194
195 /**
196 * Joins replacement to the current output with appropriate number of new lines
197 * @private
198 * @param {String} output The current conversion output
199 * @param {String} replacement The string to append to the output
200 * @returns Joined output
201 * @type String
202 */
203
204 function join (output, replacement) {
205 const s1 = trimTrailingNewlines(output)
206 const s2 = trimLeadingNewlines(replacement)
207 const nls = Math.max(output.length - s1.length, replacement.length - s2.length)
208 const separator = '\n\n'.substring(0, nls)
209
210 return s1 + separator + s2
211 }
212
213 /**
214 * Determines whether an input can be converted
215 * @private
216 * @param {String|HTMLElement} input Describe this parameter
217 * @returns Describe what it returns
218 * @type String|Object|Array|Boolean|Number
219 */
220
221 function canConvert (input) {
222 return (
223 input != null && (
224 typeof input === 'string' ||
225 (input.nodeType && (
226 input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11
227 ))
228 )
229 )
230 }