blocks.php
19.6 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
<?php
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
// Register store.
acf_register_store( 'block-types' );
acf_register_store( 'block-cache' );
/**
* acf_register_block_type
*
* Registers a block type.
*
* @date 18/2/19
* @since 5.8.0
*
* @param array $block The block settings.
* @return (array|false)
*/
function acf_register_block_type( $block ) {
// Validate block type settings.
$block = acf_validate_block_type( $block );
/**
* Filters the arguments for registering a block type.
*
* @since 5.8.9
*
* @param array $block The array of arguments for registering a block type.
*/
$block = apply_filters( 'acf/register_block_type_args', $block );
// Require name.
if ( ! $block['name'] ) {
$message = __( 'Block type name is required.', 'acf' );
_doing_it_wrong( __FUNCTION__, $message, '5.8.0' );
return false;
}
// Bail early if already exists.
if ( acf_has_block_type( $block['name'] ) ) {
$message = sprintf( __( 'Block type "%s" is already registered.' ), $block['name'] );
_doing_it_wrong( __FUNCTION__, $message, '5.8.0' );
return false;
}
// Add to storage.
acf_get_store( 'block-types' )->set( $block['name'], $block );
// Register block type in WP.
if ( function_exists( 'register_block_type' ) ) {
register_block_type(
$block['name'],
array(
'attributes' => acf_get_block_type_default_attributes( $block ),
'uses_context' => $block['usesContext'],
'api_version' => 2,
'render_callback' => 'acf_render_block_callback',
)
);
}
// Register action.
add_action( 'enqueue_block_editor_assets', 'acf_enqueue_block_assets' );
// Return block.
return $block;
}
/**
* acf_register_block
*
* See acf_register_block_type().
*
* @date 18/2/19
* @since 5.7.12
*
* @param array $block The block settings.
* @return (array|false)
*/
function acf_register_block( $block ) {
return acf_register_block_type( $block );
}
/**
* acf_has_block_type
*
* Returns true if a block type exists for the given name.
*
* @date 18/2/19
* @since 5.7.12
*
* @param string $name The block type name.
* @return bool
*/
function acf_has_block_type( $name ) {
return acf_get_store( 'block-types' )->has( $name );
}
/**
* acf_get_block_types
*
* Returns an array of all registered block types.
*
* @date 18/2/19
* @since 5.7.12
*
* @param void
* @return array
*/
function acf_get_block_types() {
return acf_get_store( 'block-types' )->get();
}
/**
* acf_get_block_types
*
* Returns a block type for the given name.
*
* @date 18/2/19
* @since 5.7.12
*
* @param string $name The block type name.
* @return (array|null)
*/
function acf_get_block_type( $name ) {
return acf_get_store( 'block-types' )->get( $name );
}
/**
* acf_remove_block_type
*
* Removes a block type for the given name.
*
* @date 18/2/19
* @since 5.7.12
*
* @param string $name The block type name.
* @return void
*/
function acf_remove_block_type( $name ) {
acf_get_store( 'block-types' )->remove( $name );
}
/**
* acf_get_block_type_default_attributes
*
* Returns an array of default attribute settings for a block type.
*
* @date 19/11/18
* @since 5.8.0
*
* @param void
* @return array
*/
function acf_get_block_type_default_attributes( $block_type ) {
$attributes = array(
'id' => array(
'type' => 'string',
'default' => '',
),
'name' => array(
'type' => 'string',
'default' => '',
),
'data' => array(
'type' => 'object',
'default' => array(),
),
'align' => array(
'type' => 'string',
'default' => '',
),
'mode' => array(
'type' => 'string',
'default' => '',
),
);
if ( ! empty( $block_type['supports']['align_text'] ) ) {
$attributes['align_text'] = array(
'type' => 'string',
'default' => '',
);
}
if ( ! empty( $block_type['supports']['align_content'] ) ) {
$attributes['align_content'] = array(
'type' => 'string',
'default' => '',
);
}
return $attributes;
}
/**
* acf_validate_block_type
*
* Validates a block type ensuring all settings exist.
*
* @date 10/4/18
* @since 5.8.0
*
* @param array $block The block settings.
* @return array
*/
function acf_validate_block_type( $block ) {
// Add default settings.
$block = wp_parse_args(
$block,
array(
'name' => '',
'title' => '',
'description' => '',
'category' => 'common',
'icon' => '',
'mode' => 'preview',
'align' => '',
'keywords' => array(),
'supports' => array(),
'post_types' => array(),
'usesContext' => array(),
'render_template' => false,
'render_callback' => false,
'enqueue_style' => false,
'enqueue_script' => false,
'enqueue_assets' => false,
)
);
// Restrict keywords to 3 max to avoid JS error in older versions.
if ( acf_version_compare( 'wp', '<', '5.2' ) ) {
$block['keywords'] = array_slice( $block['keywords'], 0, 3 );
}
// Generate name with prefix.
if ( $block['name'] ) {
$block['name'] = 'acf/' . acf_slugify( $block['name'] );
}
// Add default 'supports' settings.
$block['supports'] = wp_parse_args(
$block['supports'],
array(
'align' => true,
'html' => false,
'mode' => true,
)
);
// Add default 'usesContext' settings.
$block['usesContext'] = wp_parse_args(
$block['usesContext'],
array(
'postId',
'postType',
)
);
// Correct "Experimental" flags.
if ( isset( $block['supports']['__experimental_jsx'] ) ) {
$block['supports']['jsx'] = $block['supports']['__experimental_jsx'];
}
// Return block.
return $block;
}
/**
* acf_prepare_block
*
* Prepares a block for use in render_callback by merging in all settings and attributes.
*
* @date 19/11/18
* @since 5.8.0
*
* @param array $block The block props.
* @return array
*/
function acf_prepare_block( $block ) {
// Bail early if no name.
if ( ! isset( $block['name'] ) ) {
return false;
}
// Get block type and return false if doesn't exist.
$block_type = acf_get_block_type( $block['name'] );
if ( ! $block_type ) {
return false;
}
// Generate default attributes.
$attributes = array();
foreach ( acf_get_block_type_default_attributes( $block_type ) as $k => $v ) {
$attributes[ $k ] = $v['default'];
}
// Merge together arrays in order of least to most specific.
$block = array_merge( $block_type, $attributes, $block );
// Return block.
return $block;
}
/**
* The render callback for all ACF blocks.
*
* @date 28/10/20
* @since 5.9.2
*
* @param array $attributes The block attributes.
* @param string $content The block content.
* @param WP_Block $wp_block The block instance (since WP 5.5).
* @return string The block HTML.
*/
function acf_render_block_callback( $attributes, $content = '', $wp_block = null ) {
$is_preview = false;
$post_id = get_the_ID();
// Set preview flag to true when rendering for the block editor.
if ( is_admin() && acf_is_block_editor() ) {
$is_preview = true;
}
// Return rendered block HTML.
return acf_rendered_block( $attributes, $content, $is_preview, $post_id, $wp_block );
}
/**
* Returns the rendered block HTML.
*
* @date 28/2/19
* @since 5.7.13
*
* @param array $attributes The block attributes.
* @param string $content The block content.
* @param bool $is_preview Whether or not the block is being rendered for editing preview.
* @param int $post_id The current post being edited or viewed.
* @param WP_Block $wp_block The block instance (since WP 5.5).
* @param array $context The block context array.
* @return string The block HTML.
*/
function acf_rendered_block( $attributes, $content = '', $is_preview = false, $post_id = 0, $wp_block = null, $context = false ) {
$mode = isset( $attributes['mode'] ) ? $attributes['mode'] : 'auto';
// If context is available from the WP_Block class object and we have no context of our own, use that.
if ( empty( $context ) && ! empty( $wp_block->context ) ) {
$context = $wp_block->context;
}
ob_start();
// if ( 'edit' === $mode && $is_preview ) {
// Load the block form since we're in edit mode.
// $block = acf_prepare_block( $attributes );
// acf_setup_meta( $block['data'], $block['id'], true );
// $fields = acf_get_block_fields( $block );
// acf_prefix_fields( $fields, "acf-{$block['id']}" );
//
// echo '<div class="acf-block-fields acf-fields">';
// acf_render_fields( $fields, $block['id'], 'div', 'field' );
// echo '</div>';
// } else {
// Capture block render output.
acf_render_block( $attributes, $content, $is_preview, $post_id, $wp_block, $context );
// }
$html = ob_get_clean();
//if ( in_array( $mode, array( 'preview', 'auto' ) ) && $is_preview ) {
if ( $is_preview ) {
$html = '<div class="acf-block-preview">' . $html . '</div>';
}
// Replace <InnerBlocks /> placeholder on front-end.
if ( ! $is_preview ) {
// Escape "$" character to avoid "capture group" interpretation.
$content = str_replace( '$', '\$', $content );
$html = preg_replace( '/<InnerBlocks([\S\s]*?)\/>/', $content, $html );
}
// Store in cache for preloading.
acf_get_store( 'block-cache' )->set( $attributes['id'], $html );
return $html;
}
/**
* Renders the block HTML.
*
* @date 19/2/19
* @since 5.7.12
*
* @param array $attributes The block attributes.
* @param string $content The block content.
* @param bool $is_preview Whether or not the block is being rendered for editing preview.
* @param int $post_id The current post being edited or viewed.
* @param WP_Block $wp_block The block instance (since WP 5.5).
* @param array $context The block context array.
* @return void
*/
function acf_render_block( $attributes, $content = '', $is_preview = false, $post_id = 0, $wp_block = null, $context = false ) {
// Prepare block ensuring all settings and attributes exist.
$block = acf_prepare_block( $attributes );
if ( ! $block ) {
return '';
}
// Find post_id if not defined.
if ( ! $post_id ) {
$post_id = get_the_ID();
}
// Enqueue block type assets.
acf_enqueue_block_type_assets( $block );
// Setup postdata allowing get_field() to work.
acf_setup_meta( $block['data'], $block['id'], true );
// Call render_callback.
if ( is_callable( $block['render_callback'] ) ) {
call_user_func( $block['render_callback'], $block, $content, $is_preview, $post_id, $wp_block, $context );
// Or include template.
} elseif ( $block['render_template'] ) {
// Locate template.
if ( file_exists( $block['render_template'] ) ) {
$path = $block['render_template'];
} else {
$path = locate_template( $block['render_template'] );
}
// Include template.
if ( file_exists( $path ) ) {
include $path;
}
}
// Reset postdata.
acf_reset_meta( $block['id'] );
}
/**
* acf_get_block_fields
*
* Returns an array of all fields for the given block.
*
* @date 24/10/18
* @since 5.8.0
*
* @param array $block The block props.
* @return array
*/
function acf_get_block_fields( $block ) {
// Vars.
$fields = array();
// Get field groups for this block.
$field_groups = acf_get_field_groups(
array(
'block' => $block['name'],
)
);
// Loop over results and append fields.
if ( $field_groups ) {
foreach ( $field_groups as $field_group ) {
$fields = array_merge( $fields, acf_get_fields( $field_group ) );
}
}
// Return fields.
return $fields;
}
/**
* acf_enqueue_block_assets
*
* Enqueues and localizes block scripts and styles.
*
* @date 28/2/19
* @since 5.7.13
*
* @param void
* @return void
*/
function acf_enqueue_block_assets() {
// Localize text.
acf_localize_text(
array(
'Switch to Edit' => __( 'Switch to Edit', 'acf' ),
'Switch to Preview' => __( 'Switch to Preview', 'acf' ),
'Change content alignment' => __( 'Change content alignment', 'acf' ),
/* translators: %s: Block type title */
'%s settings' => __( '%s settings', 'acf' ),
)
);
// Get block types.
$block_types = acf_get_block_types();
// Localize data.
acf_localize_data(
array(
'blockTypes' => array_values( $block_types ),
'postType' => get_post_type(),
)
);
// Enqueue script.
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
if ( acf_version_compare( 'wp', '<', '5.6' ) ) {
$blocks_js_path = acf_get_url( "assets/build/js/pro/acf-pro-blocks-legacy{$min}.js" );
} else {
$blocks_js_path = acf_get_url( "assets/build/js/pro/acf-pro-blocks{$min}.js" );
}
wp_enqueue_script( 'acf-blocks', $blocks_js_path, array( 'acf-input', 'wp-blocks' ), ACF_VERSION, true );
// Enqueue block assets.
array_map( 'acf_enqueue_block_type_assets', $block_types );
// During the edit screen loading, WordPress renders all blocks in its own attempt to preload data.
// Retrieve any cached block HTML and include this in the localized data.
if ( acf_get_setting( 'preload_blocks' ) ) {
$preloaded_blocks = acf_get_store( 'block-cache' )->get_data();
acf_localize_data(
array(
'preloadedBlocks' => $preloaded_blocks,
)
);
}
}
/**
* acf_enqueue_block_type_assets
*
* Enqueues scripts and styles for a specific block type.
*
* @date 28/2/19
* @since 5.7.13
*
* @param array $block_type The block type settings.
* @return void
*/
function acf_enqueue_block_type_assets( $block_type ) {
// Generate handle from name.
$handle = 'block-' . acf_slugify( $block_type['name'] );
// Enqueue style.
if ( $block_type['enqueue_style'] ) {
wp_enqueue_style( $handle, $block_type['enqueue_style'], array(), false, 'all' );
}
// Enqueue script.
if ( $block_type['enqueue_script'] ) {
wp_enqueue_script( $handle, $block_type['enqueue_script'], array(), false, true );
}
// Enqueue assets callback.
if ( $block_type['enqueue_assets'] && is_callable( $block_type['enqueue_assets'] ) ) {
call_user_func( $block_type['enqueue_assets'], $block_type );
}
}
/**
* acf_ajax_fetch_block
*
* Handles the ajax request for block data.
*
* @date 28/2/19
* @since 5.7.13
*
* @param void
* @return void
*/
function acf_ajax_fetch_block() {
// Validate ajax request.
if ( ! acf_verify_ajax() ) {
wp_send_json_error();
}
// Get request args.
$args = acf_request_args(
array(
'block' => false,
'post_id' => 0,
'query' => array(),
'context' => array(),
)
);
$block = $args['block'];
$query = $args['query'];
$raw_context = $args['context'];
$post_id = $args['post_id'];
// Bail early if no block.
if ( ! $block ) {
wp_send_json_error();
}
// Unslash and decode $_POST data for block and context.
$block = wp_unslash( $block );
$block = json_decode( $block, true );
$context = false;
if ( ! empty( $raw_context ) ) {
$raw_context = wp_unslash( $raw_context );
$raw_context = json_decode( $raw_context, true );
if ( is_array( $raw_context ) ) {
$context = $raw_context;
// Check if a postId is set in the context, otherwise try and use it the default post_id.
$post_id = isset( $context['postId'] ) ? intval( $context['postId'] ) : intval( $args['post_id'] );
}
}
// Prepare block ensuring all settings and attributes exist.
if ( ! $block = acf_prepare_block( $block ) ) {
wp_send_json_error();
}
// Load field defaults when first previewing a block.
if ( ! empty( $query['preview'] ) && ! $block['data'] ) {
$fields = acf_get_block_fields( $block );
foreach ( $fields as $field ) {
$block['data'][ "_{$field['name']}" ] = $field['key'];
}
}
// Setup postdata allowing form to load meta.
acf_setup_meta( $block['data'], $block['id'], true );
// Setup main postdata for post_id.
global $post;
$post = get_post( $post_id );
setup_postdata( $post );
// Vars.
$response = array();
// Query form.
if ( ! empty( $query['form'] ) ) {
// Load fields for form.
$fields = acf_get_block_fields( $block );
// Prefix field inputs to avoid multiple blocks using the same name/id attributes.
acf_prefix_fields( $fields, "acf-{$block['id']}" );
// Start Capture.
ob_start();
// Render.
echo '<div class="acf-block-fields acf-fields">';
acf_render_fields( $fields, $block['id'], 'div', 'field' );
echo '</div>';
// Store Capture.
$response['form'] = ob_get_contents();
ob_end_clean();
}
// Query preview.
if ( ! empty( $query['preview'] ) ) {
// Render_callback vars.
$content = '';
$is_preview = true;
// Render and store HTML.
$response['preview'] = acf_rendered_block( $block, $content, $is_preview, $post_id, null, $context );
}
// Send response.
wp_send_json_success( $response );
}
// Register ajax action.
acf_register_ajax( 'fetch-block', 'acf_ajax_fetch_block' );
/**
* acf_parse_save_blocks
*
* Parse content that may contain HTML block comments and saves ACF block meta.
*
* @date 27/2/19
* @since 5.7.13
*
* @param string $text Content that may contain HTML block comments.
* @return string
*/
function acf_parse_save_blocks( $text = '' ) {
// Search text for dynamic blocks and modify attrs.
return addslashes(
preg_replace_callback(
'/<!--\s+wp:(?P<name>[\S]+)\s+(?P<attrs>{[\S\s]+?})\s+(?P<void>\/)?-->/',
'acf_parse_save_blocks_callback',
stripslashes( $text )
)
);
}
// Hook into saving process.
add_filter( 'content_save_pre', 'acf_parse_save_blocks', 5, 1 );
/**
* acf_parse_save_blocks_callback
*
* Callback used in preg_replace to modify ACF Block comment.
*
* @date 1/3/19
* @since 5.7.13
*
* @param array $matches The preg matches.
* @return string
*/
function acf_parse_save_blocks_callback( $matches ) {
// Defaults
$name = isset( $matches['name'] ) ? $matches['name'] : '';
$attrs = isset( $matches['attrs'] ) ? json_decode( $matches['attrs'], true ) : '';
$void = isset( $matches['void'] ) ? $matches['void'] : '';
// Bail early if missing data or not an ACF Block.
if ( ! $name || ! $attrs || ! acf_has_block_type( $name ) ) {
return $matches[0];
}
// Convert "data" to "meta".
// No need to check if already in meta format. Local Meta will do this for us.
if ( isset( $attrs['data'] ) ) {
$attrs['data'] = acf_setup_meta( $attrs['data'], $attrs['id'] );
}
/**
* Filters the block attributes before saving.
*
* @date 18/3/19
* @since 5.7.14
*
* @param array $attrs The block attributes.
*/
$attrs = apply_filters( 'acf/pre_save_block', $attrs );
// Gutenberg expects a specific encoding format.
$attrs = acf_serialize_block_attributes( $attrs );
return '<!-- wp:' . $name . ' ' . $attrs . ' ' . $void . '-->';
}
/**
* This directly copied from the WordPress core `serialize_block_attributes()` function.
*
* We need this in order to make sure that block attributes are stored in a way that is
* consistent with how Gutenberg sends them over from JS, and so that things like wp_kses()
* work as expected. Copied from core to get around a bug that was fixed in 5.8.1 or on the off chance
* that folks are still using WP 5.3 or below.
*
* TODO: Remove this when we refactor `acf_parse_save_blocks_callback()` to use `serialize_block()`,
* or when we're confident that folks aren't using WP versions prior to 5.8.
*
* @since 5.12
*
* @param array $block_attributes Attributes object.
* @return string Serialized attributes.
*/
function acf_serialize_block_attributes( $block_attributes ) {
$encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
$encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes );
$encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes );
$encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes );
$encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes );
// Regex: /\\"/
$encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes );
return $encoded_attributes;
}