-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathunist.mjs
More file actions
73 lines (64 loc) · 2.62 KB
/
unist.mjs
File metadata and controls
73 lines (64 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
import { pointEnd, pointStart } from 'unist-util-position';
/**
* Escapes HTML entities ("<" and ">") in a string
* @param {string} string The string
*/
const escapeHTMLEntities = string =>
string.replace(/</g, '<').replace(/>/g, '>');
/**
* Extracts text content from a node recursively
*
* @param {import('unist').Node} node The Node to be transformed into a string
* @param {boolean} [escape] Escape HTML entities ("<", ">")?
* @returns {string} The transformed Node as a string
*/
export const transformNodeToString = (node, escape) => {
switch (node.type) {
case 'inlineCode':
return `\`${escape ? escapeHTMLEntities(node.value) : node.value}\``;
case 'strong':
return `**${transformNodesToString(node.children, escape)}**`;
case 'emphasis':
return `_${transformNodesToString(node.children, escape)}_`;
default: {
if (node.children) {
return transformNodesToString(node.children, escape);
}
const string = node.value?.replace(/\n/g, ' ') || '';
// Replace line breaks (\n) with spaces to keep text in a single line
return escape ? escapeHTMLEntities(string) : string;
}
}
};
/**
* This utility allows us to join children Nodes into one
* and transfor them back to what their source would look like
*
* @param {Array<import('unist').Parent & import('unist').Literal>} nodes Nodes to parsed and joined
* @param {boolean} [escape] Escape HTML entities ("<", ">")?
* @returns {string} The parsed and joined nodes as a string
*/
export const transformNodesToString = (nodes, escape) => {
const mappedChildren = nodes.map(node => transformNodeToString(node, escape));
return mappedChildren.join('');
};
/**
* This method is an utility that allows us to conditionally invoke/call a callback
* based on test conditions related to a Node's position relative to another one
* being before or not the other Node
*
* NOTE: Not yet used, but probably going to be used by the JSON generator.
*
* @param {import('unist').Node | undefined} nodeA The Node to be used as a position reference to check against
* the other Node. If the other Node is before this one, the callback will be called.
* @param {import('unist').Node | undefined} nodeB The Node to be checked against the position of the first Node
* @param {(nodeA: import('unist').Node, nodeB: import('unist').Node) => void} callback The callback to be called
*/
export const callIfBefore = (nodeA, nodeB, callback) => {
const positionA = pointEnd(nodeA);
const positionB = pointStart(nodeB);
if (positionA && positionB && positionA.line > positionB.line) {
callback(nodeA, nodeB);
}
};