-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
serializer.js
284 lines (250 loc) · 8.69 KB
/
serializer.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/**
* External dependencies
*/
import { isEmpty, reduce, isObject, castArray, startsWith } from 'lodash';
/**
* WordPress dependencies
*/
import { Component, cloneElement, renderToString } from '@wordpress/element';
import { hasFilter, applyFilters } from '@wordpress/hooks';
import isShallowEqual from '@wordpress/is-shallow-equal';
/**
* Internal dependencies
*/
import {
getBlockType,
getFreeformContentHandlerName,
getUnregisteredTypeHandlerName,
} from './registration';
import BlockContentProvider from '../block-content-provider';
/**
* Returns the block's default classname from its name.
*
* @param {string} blockName The block name.
*
* @return {string} The block's default class.
*/
export function getBlockDefaultClassName( blockName ) {
// Generated HTML classes for blocks follow the `wp-block-{name}` nomenclature.
// Blocks provided by WordPress drop the prefixes 'core/' or 'core-' (used in 'core-embed/').
const className = 'wp-block-' + blockName.replace( /\//, '-' ).replace( /^core-/, '' );
return applyFilters( 'blocks.getBlockDefaultClassName', className, blockName );
}
/**
* Returns the block's default menu item classname from its name.
*
* @param {string} blockName The block name.
*
* @return {string} The block's default menu item class.
*/
export function getBlockMenuDefaultClassName( blockName ) {
// Generated HTML classes for blocks follow the `editor-block-list-item-{name}` nomenclature.
// Blocks provided by WordPress drop the prefixes 'core/' or 'core-' (used in 'core-embed/').
const className = 'editor-block-list-item-' + blockName.replace( /\//, '-' ).replace( /^core-/, '' );
return applyFilters( 'blocks.getBlockMenuDefaultClassName', className, blockName );
}
/**
* Given a block type containing a save render implementation and attributes, returns the
* enhanced element to be saved or string when raw HTML expected.
*
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
* @param {?Array} innerBlocks Nested blocks.
*
* @return {Object|string} Save element or raw HTML string.
*/
export function getSaveElement( blockType, attributes, innerBlocks = [] ) {
let { save } = blockType;
// Component classes are unsupported for save since serialization must
// occur synchronously. For improved interoperability with higher-order
// components which often return component class, emulate basic support.
if ( save.prototype instanceof Component ) {
const instance = new save( { attributes } );
save = instance.render.bind( instance );
}
let element = save( { attributes, innerBlocks } );
if ( isObject( element ) && hasFilter( 'blocks.getSaveContent.extraProps' ) ) {
/**
* Filters the props applied to the block save result element.
*
* @param {Object} props Props applied to save element.
* @param {WPBlockType} blockType Block type definition.
* @param {Object} attributes Block attributes.
*/
const props = applyFilters(
'blocks.getSaveContent.extraProps',
{ ...element.props },
blockType,
attributes
);
if ( ! isShallowEqual( props, element.props ) ) {
element = cloneElement( element, props );
}
}
/**
* Filters the save result of a block during serialization.
*
* @param {WPElement} element Block save result.
* @param {WPBlockType} blockType Block type definition.
* @param {Object} attributes Block attributes.
*/
element = applyFilters( 'blocks.getSaveElement', element, blockType, attributes );
return (
<BlockContentProvider innerBlocks={ innerBlocks }>
{ element }
</BlockContentProvider>
);
}
/**
* Given a block type containing a save render implementation and attributes, returns the
* static markup to be saved.
*
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
* @param {?Array} innerBlocks Nested blocks.
*
* @return {string} Save content.
*/
export function getSaveContent( blockType, attributes, innerBlocks ) {
return renderToString( getSaveElement( blockType, attributes, innerBlocks ) );
}
/**
* Returns attributes which are to be saved and serialized into the block
* comment delimiter.
*
* When a block exists in memory it contains as its attributes both those
* parsed the block comment delimiter _and_ those which matched from the
* contents of the block.
*
* This function returns only those attributes which are needed to persist and
* which cannot be matched from the block content.
*
* @param {Object<string,*>} blockType Block type.
* @param {Object<string,*>} attributes Attributes from in-memory block data.
*
* @return {Object<string,*>} Subset of attributes for comment serialization.
*/
export function getCommentAttributes( blockType, attributes ) {
return reduce( blockType.attributes, ( result, attributeSchema, key ) => {
const value = attributes[ key ];
// Ignore undefined values.
if ( undefined === value ) {
return result;
}
// Ignore all attributes but the ones with an "undefined" source
// "undefined" source refers to attributes saved in the block comment.
if ( attributeSchema.source !== undefined ) {
return result;
}
// Ignore default value.
if ( 'default' in attributeSchema && attributeSchema.default === value ) {
return result;
}
// Otherwise, include in comment set.
result[ key ] = value;
return result;
}, {} );
}
/**
* Given an attributes object, returns a string in the serialized attributes
* format prepared for post content.
*
* @param {Object} attributes Attributes object.
*
* @return {string} Serialized attributes.
*/
export function serializeAttributes( attributes ) {
return JSON.stringify( attributes )
// Don't break HTML comments.
.replace( /--/g, '\\u002d\\u002d' )
// Don't break non-standard-compliant tools.
.replace( /</g, '\\u003c' )
.replace( />/g, '\\u003e' )
.replace( /&/g, '\\u0026' )
// Bypass server stripslashes behavior which would unescape stringify's
// escaping of quotation mark.
//
// See: https://developer.wordpress.org/reference/functions/wp_kses_stripslashes/
.replace( /\\"/g, '\\u0022' );
}
/**
* Given a block object, returns the Block's Inner HTML markup.
*
* @param {Object} block Block instance.
*
* @return {string} HTML.
*/
export function getBlockContent( block ) {
// @todo why not getBlockInnerHtml?
const blockType = getBlockType( block.name );
// If block was parsed as invalid or encounters an error while generating
// save content, use original content instead to avoid content loss. If a
// block contains nested content, exempt it from this condition because we
// otherwise have no access to its original content and content loss would
// still occur.
let saveContent = block.originalContent;
if ( block.isValid || block.innerBlocks.length ) {
try {
saveContent = getSaveContent( blockType, block.attributes, block.innerBlocks );
} catch ( error ) {}
}
return saveContent;
}
/**
* Returns the content of a block, including comment delimiters.
*
* @param {string} rawBlockName Block name.
* @param {Object} attributes Block attributes.
* @param {string} content Block save content.
*
* @return {string} Comment-delimited block content.
*/
export function getCommentDelimitedContent( rawBlockName, attributes, content ) {
const serializedAttributes = ! isEmpty( attributes ) ?
serializeAttributes( attributes ) + ' ' :
'';
// Strip core blocks of their namespace prefix.
const blockName = startsWith( rawBlockName, 'core/' ) ?
rawBlockName.slice( 5 ) :
rawBlockName;
// @todo make the `wp:` prefix potentially configurable.
if ( ! content ) {
return `<!-- wp:${ blockName } ${ serializedAttributes }/-->`;
}
return (
`<!-- wp:${ blockName } ${ serializedAttributes }-->\n` +
content +
`\n<!-- /wp:${ blockName } -->`
);
}
/**
* Returns the content of a block, including comment delimiters, determining
* serialized attributes and content form from the current state of the block.
*
* @param {Object} block Block instance.
*
* @return {string} Serialized block.
*/
export function serializeBlock( block ) {
const blockName = block.name;
const blockType = getBlockType( blockName );
const saveContent = getBlockContent( block );
const saveAttributes = getCommentAttributes( blockType, block.attributes );
switch ( blockName ) {
case getFreeformContentHandlerName():
case getUnregisteredTypeHandlerName():
return saveContent;
default:
return getCommentDelimitedContent( blockName, saveAttributes, saveContent );
}
}
/**
* Takes a block or set of blocks and returns the serialized post content.
*
* @param {Array} blocks Block(s) to serialize.
*
* @return {string} The post content.
*/
export default function serialize( blocks ) {
return castArray( blocks ).map( serializeBlock ).join( '\n\n' );
}