55 * Configuration (optional).
66 * @property {boolean | null | undefined } [includeImageAlt=true]
77 * Whether to use `alt` for `image`s.
8+ * @property {boolean | null | undefined } [includeHtml=true]
9+ * Whether to use `value` of HTML.
810 */
911
12+ /** @type {Options } */
13+ const emptyOptions = { }
14+
1015/**
1116 * Get the text content of a node or list of nodes.
1217 *
2126 * Serialized `value`.
2227 */
2328export 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 )
2938}
3039
3140/**
@@ -35,18 +44,31 @@ export function toString(value, options) {
3544 * Thing to serialize.
3645 * @param {boolean } includeImageAlt
3746 * Include image `alt`s.
47+ * @param {boolean } includeHtml
48+ * Include HTML.
3849 * @returns {string }
3950 * Serialized node.
4051 */
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 ''
5072}
5173
5274/**
@@ -56,16 +78,18 @@ function one(value, includeImageAlt) {
5678 * Thing to serialize.
5779 * @param {boolean } includeImageAlt
5880 * Include image `alt`s.
81+ * @param {boolean } includeHtml
82+ * Include HTML.
5983 * @returns {string }
6084 * Serialized nodes.
6185 */
62- function all ( values , includeImageAlt ) {
86+ function all ( values , includeImageAlt , includeHtml ) {
6387 /** @type {Array<string> } */
6488 const result = [ ]
6589 let index = - 1
6690
6791 while ( ++ index < values . length ) {
68- result [ index ] = one ( values [ index ] , includeImageAlt )
92+ result [ index ] = one ( values [ index ] , includeImageAlt , includeHtml )
6993 }
7094
7195 return result . join ( '' )
0 commit comments