5
5
* Configuration (optional).
6
6
* @property {boolean | null | undefined } [includeImageAlt=true]
7
7
* Whether to use `alt` for `image`s.
8
+ * @property {boolean | null | undefined } [includeHtml=true]
9
+ * Whether to use `value` of HTML.
8
10
*/
9
11
12
+ /** @type {Options } */
13
+ const emptyOptions = { }
14
+
10
15
/**
11
16
* Get the text content of a node or list of nodes.
12
17
*
21
26
* Serialized `value`.
22
27
*/
23
28
export function toString ( value , options ) {
24
- const includeImageAlt = ( options || { } ) . includeImageAlt
25
- return one (
26
- value ,
27
- typeof includeImageAlt === 'boolean' ? includeImageAlt : true
28
- )
29
+ const settings = options || emptyOptions
30
+ const includeImageAlt =
31
+ typeof settings . includeImageAlt === 'boolean'
32
+ ? settings . includeImageAlt
33
+ : true
34
+ const includeHtml =
35
+ typeof settings . includeHtml === 'boolean' ? settings . includeHtml : true
36
+
37
+ return one ( value , includeImageAlt , includeHtml )
29
38
}
30
39
31
40
/**
@@ -35,18 +44,31 @@ export function toString(value, options) {
35
44
* Thing to serialize.
36
45
* @param {boolean } includeImageAlt
37
46
* Include image `alt`s.
47
+ * @param {boolean } includeHtml
48
+ * Include HTML.
38
49
* @returns {string }
39
50
* Serialized node.
40
51
*/
41
- function one ( value , includeImageAlt ) {
42
- return (
43
- ( node ( value ) &&
44
- ( ( 'value' in value && value . value ) ||
45
- ( includeImageAlt && 'alt' in value && value . alt ) ||
46
- ( 'children' in value && all ( value . children , includeImageAlt ) ) ) ) ||
47
- ( Array . isArray ( value ) && all ( value , includeImageAlt ) ) ||
48
- ''
49
- )
52
+ function one ( value , includeImageAlt , includeHtml ) {
53
+ if ( node ( value ) ) {
54
+ if ( 'value' in value ) {
55
+ return value . type === 'html' && ! includeHtml ? '' : value . value
56
+ }
57
+
58
+ if ( includeImageAlt && 'alt' in value && value . alt ) {
59
+ return value . alt
60
+ }
61
+
62
+ if ( 'children' in value ) {
63
+ return all ( value . children , includeImageAlt , includeHtml )
64
+ }
65
+ }
66
+
67
+ if ( Array . isArray ( value ) ) {
68
+ return all ( value , includeImageAlt , includeHtml )
69
+ }
70
+
71
+ return ''
50
72
}
51
73
52
74
/**
@@ -56,16 +78,18 @@ function one(value, includeImageAlt) {
56
78
* Thing to serialize.
57
79
* @param {boolean } includeImageAlt
58
80
* Include image `alt`s.
81
+ * @param {boolean } includeHtml
82
+ * Include HTML.
59
83
* @returns {string }
60
84
* Serialized nodes.
61
85
*/
62
- function all ( values , includeImageAlt ) {
86
+ function all ( values , includeImageAlt , includeHtml ) {
63
87
/** @type {Array<string> } */
64
88
const result = [ ]
65
89
let index = - 1
66
90
67
91
while ( ++ index < values . length ) {
68
- result [ index ] = one ( values [ index ] , includeImageAlt )
92
+ result [ index ] = one ( values [ index ] , includeImageAlt , includeHtml )
69
93
}
70
94
71
95
return result . join ( '' )
0 commit comments