-
Notifications
You must be signed in to change notification settings - Fork 384
/
amp-block-validation.js
365 lines (322 loc) · 11.2 KB
/
amp-block-validation.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/**
* Validates blocks for AMP compatibility.
*
* This uses the REST API response from saving a page to find validation errors.
* If one exists for a block, it display it inline with a Notice component.
*/
/* exported ampBlockValidation */
/* global wp, _ */
var ampBlockValidation = ( function() {
'use strict';
var module = {
/**
* Data exported from server.
*
* @param {Object}
*/
data: {
i18n: {},
ampValidityRestField: ''
},
/**
* Name of the store.
*
* @param {string}
*/
storeName: 'amp/blockValidation',
/**
* Boot module.
*
* @param {Object} data - Module data.
* @return {void}
*/
boot: function boot( data ) {
module.data = data;
wp.i18n.setLocaleData( module.data.i18n, 'amp' );
wp.hooks.addFilter(
'blocks.BlockEdit',
'amp/add-notice',
module.conditionallyAddNotice
);
module.store = module.registerStore();
wp.data.subscribe( module.handleValidationErrorsStateChange );
},
/**
* Register store.
*
* @return {Object} Store.
*/
registerStore: function registerStore() {
return wp.data.registerStore( module.storeName, {
reducer: function( _state, action ) {
var state = _state || {
blockValidationErrorsByUid: {}
};
switch ( action.type ) {
case 'UPDATE_BLOCKS_VALIDATION_ERRORS':
return _.extend( {}, state, {
blockValidationErrorsByUid: action.blockValidationErrorsByUid
} );
default:
return state;
}
},
actions: {
updateBlocksValidationErrors: function( blockValidationErrorsByUid ) {
return {
type: 'UPDATE_BLOCKS_VALIDATION_ERRORS',
blockValidationErrorsByUid: blockValidationErrorsByUid
};
}
},
selectors: {
getBlockValidationErrors: function( state, uid ) {
return state.blockValidationErrorsByUid[ uid ] || [];
}
}
} );
},
/**
* Handle state change regarding validation errors.
*
* @return {void}
*/
handleValidationErrorsStateChange: function handleValidationErrorsStateChange() {
var currentPost, validationErrors, blockValidationErrors, noticeElement, noticeMessage, blockErrorCount, ampValidity;
// @todo Gutenberg currently is not persisting isDirty state if changes are made during save request. Block order mismatch.
// We can only align block validation errors with blocks in editor when in saved state, since only here will the blocks be aligned with the validation errors.
if ( wp.data.select( 'core/editor' ).isEditedPostDirty() ) {
return;
}
currentPost = wp.data.select( 'core/editor' ).getCurrentPost();
ampValidity = currentPost[ module.data.ampValidityRestField ] || {};
validationErrors = ampValidity.errors;
// Short-circuit if there was no change to the validation errors.
if ( ! validationErrors || _.isEqual( module.lastValidationErrors, validationErrors ) ) {
return;
}
module.lastValidationErrors = validationErrors;
// Remove any existing notice.
if ( module.validationWarningNoticeId ) {
wp.data.dispatch( 'core/editor' ).removeNotice( module.validationWarningNoticeId );
module.validationWarningNoticeId = null;
}
// If there are no validation errors then just make sure the validation notices are cleared from the blocks.
if ( ! validationErrors.length ) {
wp.data.dispatch( module.storeName ).updateBlocksValidationErrors( {} );
return;
}
noticeMessage = wp.i18n.sprintf(
wp.i18n._n(
'There is %s issue from AMP validation.',
'There are %s issues from AMP validation.',
validationErrors.length,
'amp'
),
validationErrors.length
);
try {
blockValidationErrors = module.getBlocksValidationErrors();
wp.data.dispatch( module.storeName ).updateBlocksValidationErrors( blockValidationErrors.byUid );
blockErrorCount = validationErrors.length - blockValidationErrors.other.length;
if ( blockErrorCount > 0 ) {
noticeMessage += ' ' + wp.i18n.sprintf(
wp.i18n._n(
'And %s is directly due to content here.',
'And %s are directly due to content here.',
blockErrorCount,
'amp'
),
blockErrorCount
);
} else {
noticeMessage += ' ' + wp.i18n.sprintf(
wp.i18n._n(
'But it is not directly due to content here.',
'But none are directly due to content here.',
validationErrors.length,
'amp'
),
validationErrors.length
);
}
} catch ( e ) {
// Clear out block validation errors in case the block sand errors cannot be aligned.
wp.data.dispatch( module.storeName ).updateBlocksValidationErrors( {} );
noticeMessage += ' ' + wp.i18n._n(
'It may not be due to content here.',
'Some may be due to content here.',
validationErrors.length,
'amp'
);
}
noticeMessage += ' ' + wp.i18n.__( 'Invalid code is stripped when displaying AMP.', 'amp' );
noticeElement = wp.element.createElement( 'p', {}, [
noticeMessage + ' ',
ampValidity.link && wp.element.createElement(
'a',
{ key: 'details', href: ampValidity.link, target: '_blank' },
wp.i18n.__( 'Details', 'amp' )
)
] );
module.validationWarningNoticeId = wp.data.dispatch( 'core/editor' ).createWarningNotice( noticeElement, { spokenMessage: noticeMessage } ).notice.id;
},
/**
* Get flattened block order.
*
* @param {Object[]} blocks - List of blocks which maty have nested blocks inside them.
* @return {string[]} Block IDs in flattened order.
*/
getFlattenedBlockOrder: function getFlattenedBlockOrder( blocks ) {
var blockOrder = [];
_.each( blocks, function( block ) {
blockOrder.push( block.uid );
if ( block.innerBlocks.length > 0 ) {
Array.prototype.push.apply( blockOrder, module.getFlattenedBlockOrder( block.innerBlocks ) );
}
} );
return blockOrder;
},
/**
* Update blocks' validation errors in the store.
*
* @return {Object} Validation errors grouped by block ID other ones.
*/
getBlocksValidationErrors: function getBlocksValidationErrors() {
var blockValidationErrorsByUid, editorSelect, currentPost, blockOrder, validationErrors, otherValidationErrors;
editorSelect = wp.data.select( 'core/editor' );
currentPost = editorSelect.getCurrentPost();
validationErrors = currentPost[ module.data.ampValidityRestField ].errors;
blockOrder = module.getFlattenedBlockOrder( editorSelect.getBlocks() );
otherValidationErrors = [];
blockValidationErrorsByUid = {};
_.each( blockOrder, function( uid ) {
blockValidationErrorsByUid[ uid ] = [];
} );
_.each( validationErrors, function( validationError ) {
var i, source, uid, block, matched;
if ( ! validationError.sources ) {
otherValidationErrors.push( validationError );
return;
}
// Find the inner-most nested block source only; ignore any nested blocks.
matched = false;
for ( i = validationError.sources.length - 1; 0 <= i; i-- ) {
source = validationError.sources[ i ];
// Skip sources that are not for blocks.
if ( ! source.block_name || _.isUndefined( source.block_content_index ) || currentPost.id !== source.post_id ) {
continue;
}
// Look up the block ID by index, assuming the blocks of content in the editor are the same as blocks rendered on frontend.
uid = blockOrder[ source.block_content_index ];
if ( _.isUndefined( uid ) ) {
throw new Error( 'undefined_block_index' );
}
// Sanity check that block exists for uid.
block = editorSelect.getBlock( uid );
if ( ! block ) {
throw new Error( 'block_lookup_failure' );
}
// Check the block type in case a block is dynamically added/removed via the_content filter to cause alignment error.
if ( block.name !== source.block_name ) {
throw new Error( 'ordered_block_alignment_mismatch' );
}
blockValidationErrorsByUid[ uid ].push( validationError );
matched = true;
// Stop looking for sources, since we aren't looking for parent blocks.
break;
}
if ( ! matched ) {
otherValidationErrors.push( validationError );
}
} );
return {
byUid: blockValidationErrorsByUid,
other: otherValidationErrors
};
},
/**
* Get message for validation error.
*
* @param {Object} validationError - Validation error.
* @param {string} validationError.code - Validation error code.
* @param {string} [validationError.node_name] - Node name.
* @param {string} [validationError.message] - Validation error message.
* @return {wp.element.Component[]|string[]} Validation error message.
*/
getValidationErrorMessage: function getValidationErrorMessage( validationError ) {
if ( validationError.message ) {
return validationError.message;
}
if ( 'invalid_element' === validationError.code && validationError.node_name ) {
return [
wp.i18n.__( 'Invalid element: ' ),
wp.element.createElement( 'code', { key: 'name' }, validationError.node_name )
];
} else if ( 'invalid_attribute' === validationError.code && validationError.node_name ) {
return [
wp.i18n.__( 'Invalid attribute: ' ),
wp.element.createElement( 'code', { key: 'name' }, validationError.parent_name ? wp.i18n.sprintf( '%s[%s]', validationError.parent_name, validationError.node_name ) : validationError.node_name )
];
}
return [
wp.i18n.__( 'Error code: ', 'amp' ),
wp.element.createElement( 'code', { key: 'name' }, validationError.code || wp.i18n.__( 'unknown' ) )
];
},
/**
* Wraps the edit() method of a block, and conditionally adds a Notice.
*
* @param {Function} BlockEdit - The original edit() method of the block.
* @return {Function} The edit() method, conditionally wrapped in a notice for AMP validation error(s).
*/
conditionallyAddNotice: function conditionallyAddNotice( BlockEdit ) {
function AmpNoticeBlockEdit( props ) {
var edit, details;
edit = wp.element.createElement(
BlockEdit,
props
);
if ( 0 === props.ampBlockValidationErrors.length ) {
return edit;
}
details = wp.element.createElement( 'details', { className: 'amp-block-validation-errors' }, [
wp.element.createElement( 'summary', { key: 'summary', className: 'amp-block-validation-errors__summary' }, wp.i18n.sprintf(
wp.i18n._n(
'There is %s issue from AMP validation.',
'There are %s issues from AMP validation.',
props.ampBlockValidationErrors.length,
'amp'
),
props.ampBlockValidationErrors.length
) ),
wp.element.createElement(
'ul',
{ key: 'list', className: 'amp-block-validation-errors__list' },
_.map( props.ampBlockValidationErrors, function( error, key ) {
return wp.element.createElement( 'li', { key: key }, module.getValidationErrorMessage( error ) );
} )
)
] );
return wp.element.createElement(
wp.element.Fragment, {},
wp.element.createElement(
wp.components.Notice,
{
status: 'warning',
isDismissible: false
},
details
),
edit
);
}
return wp.data.withSelect( function( select, ownProps ) {
return _.extend( {}, ownProps, {
ampBlockValidationErrors: select( module.storeName ).getBlockValidationErrors( ownProps.id )
} );
} )( AmpNoticeBlockEdit );
}
};
return module;
}() );