4
4
*/
5
5
6
6
/**
7
- * Stringify one nlcst node or list of nodes.
7
+ * Get the text content of a node or list of nodes.
8
8
*
9
- * @param {Root|Content|Array<Content> } node
10
- * @param {string } [separator='']
9
+ * Prefers the node’s plain-text fields, otherwise serializes its children, and
10
+ * if the given value is an array, serialize the nodes in it.
11
+ *
12
+ * @param {Root | Content | Array<Content> } value
13
+ * Node or list of nodes to serialize.
14
+ * @param {string | null | undefined } [separator='']
15
+ * Separator to use.
11
16
* @returns {string }
17
+ * Result.
12
18
*/
13
- export function toString ( node , separator = '' ) {
19
+ // To do next major: remove `separator`.
20
+ export function toString ( value , separator ) {
14
21
let index = - 1
15
22
16
- if ( ! node || ( ! Array . isArray ( node ) && ! node . type ) ) {
17
- throw new Error ( 'Expected node, not `' + node + '`' )
23
+ if ( ! value || ( ! Array . isArray ( value ) && ! value . type ) ) {
24
+ throw new Error ( 'Expected node, not `' + value + '`' )
18
25
}
19
26
20
27
// @ts -expect-error Looks like a literal.
21
- if ( typeof node . value === 'string' ) return node . value
28
+ if ( typeof value . value === 'string' ) return value . value
22
29
23
30
/** @type {Array<Content|Root> } */
24
31
// @ts -expect-error Looks like a list of nodes or parent.
25
- const children = ( Array . isArray ( node ) ? node : node . children ) || [ ]
32
+ const children = ( Array . isArray ( value ) ? value : value . children ) || [ ]
26
33
27
34
// Shortcut: This is pretty common, and a small performance win.
28
35
if ( children . length === 1 && 'value' in children [ 0 ] ) {
@@ -36,5 +43,5 @@ export function toString(node, separator = '') {
36
43
values [ index ] = toString ( children [ index ] , separator )
37
44
}
38
45
39
- return values . join ( separator )
46
+ return values . join ( separator || '' )
40
47
}
0 commit comments