-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathget-rich-text-values.js
97 lines (85 loc) · 2.41 KB
/
get-rich-text-values.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* WordPress dependencies
*/
import { RawHTML, StrictMode, Fragment } from '@wordpress/element';
import {
getSaveElement,
__unstableGetBlockProps as getBlockProps,
} from '@wordpress/blocks';
/**
* Internal dependencies
*/
import InnerBlocks from '../inner-blocks';
import { Content } from './content';
/*
* This function is similar to `@wordpress/element`'s `renderToString` function,
* except that it does not render the elements to a string, but instead collects
* the values of all rich text `Content` elements.
*/
function addValuesForElement( element, ...args ) {
if ( null === element || undefined === element || false === element ) {
return;
}
if ( Array.isArray( element ) ) {
return addValuesForElements( element, ...args );
}
switch ( typeof element ) {
case 'string':
case 'number':
return;
}
const { type, props } = element;
switch ( type ) {
case StrictMode:
case Fragment:
return addValuesForElements( props.children, ...args );
case RawHTML:
// `useInnerBlocksProps.save()` will return a `RawHTML` element,
// so use this as an indicator to recurse into the children.
return addValuesForBlocks( ...args );
case InnerBlocks.Content:
return addValuesForBlocks( ...args );
case Content:
const [ values ] = args;
values.push( props.value );
return;
}
switch ( typeof type ) {
case 'string':
if ( typeof props.children !== 'undefined' ) {
return addValuesForElements( props.children, ...args );
}
return;
case 'function':
if (
type.prototype &&
typeof type.prototype.render === 'function'
) {
return addValuesForElement(
new type( props ).render(),
...args
);
}
return addValuesForElement( type( props ), ...args );
}
}
function addValuesForElements( children, ...args ) {
children = Array.isArray( children ) ? children : [ children ];
for ( let i = 0; i < children.length; i++ ) {
addValuesForElement( children[ i ], ...args );
}
}
function addValuesForBlocks( values, blocks ) {
for ( let i = 0; i < blocks.length; i++ ) {
const { name, attributes, innerBlocks } = blocks[ i ];
const saveElement = getSaveElement( name, attributes, innerBlocks );
addValuesForElement( saveElement, values, innerBlocks );
}
}
export function getRichTextValues( blocks = [] ) {
getBlockProps.skipFilters = true;
const values = [];
addValuesForBlocks( values, blocks );
getBlockProps.skipFilters = false;
return values;
}