22
33import { pointEnd , pointStart } from 'unist-util-position' ;
44
5+ /**
6+ * Escapes HTML entities ("<" and ">") in a string
7+ * @param {string } string The string
8+ */
9+ const escapeHTMLEntities = string =>
10+ string . replace ( / < / g, '<' ) . replace ( / > / g, '>' ) ;
11+
512/**
613 * Extracts text content from a node recursively
714 *
815 * @param {import('unist').Node } node The Node to be transformed into a string
16+ * @param {boolean } [escape] Escape HTML entities ("<", ">")?
917 * @returns {string } The transformed Node as a string
1018 */
11- export const transformNodeToString = node => {
19+ export const transformNodeToString = ( node , escape ) => {
1220 switch ( node . type ) {
1321 case 'inlineCode' :
14- return `\`${ node . value } \`` ;
22+ return `\`${ escape ? escapeHTMLEntities ( node . value ) : node . value } \`` ;
1523 case 'strong' :
16- return `**${ transformNodesToString ( node . children ) } **` ;
24+ return `**${ transformNodesToString ( node . children , escape ) } **` ;
1725 case 'emphasis' :
18- return `_${ transformNodesToString ( node . children ) } _` ;
26+ return `_${ transformNodesToString ( node . children , escape ) } _` ;
1927 default : {
2028 if ( node . children ) {
21- return transformNodesToString ( node . children ) ;
29+ return transformNodesToString ( node . children , escape ) ;
2230 }
2331
32+ const string = node . value ?. replace ( / \n / g, ' ' ) || '' ;
33+
2434 // Replace line breaks (\n) with spaces to keep text in a single line
25- return node . value ?. replace ( / \n / g , ' ' ) || '' ;
35+ return escape ? escapeHTMLEntities ( string ) : string ;
2636 }
2737 }
2838} ;
@@ -32,10 +42,11 @@ export const transformNodeToString = node => {
3242 * and transfor them back to what their source would look like
3343 *
3444 * @param {Array<import('unist').Parent & import('unist').Literal> } nodes Nodes to parsed and joined
45+ * @param {boolean } [escape] Escape HTML entities ("<", ">")?
3546 * @returns {string } The parsed and joined nodes as a string
3647 */
37- export const transformNodesToString = nodes => {
38- const mappedChildren = nodes . map ( node => transformNodeToString ( node ) ) ;
48+ export const transformNodesToString = ( nodes , escape ) => {
49+ const mappedChildren = nodes . map ( node => transformNodeToString ( node , escape ) ) ;
3950
4051 return mappedChildren . join ( '' ) ;
4152} ;
0 commit comments