| 1 |
<?php |
| 2 |
/** |
| 3 |
* Utilities to manage editor settings. |
| 4 |
* |
| 5 |
* @package gutenberg |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Initialize a block-based editor. |
| 10 |
* |
| 11 |
* @param string $editor_name Editor name. |
| 12 |
* @param string $editor_script_handle Editor script handle. |
| 13 |
* @param array $settings { |
| 14 |
* Elements to initialize a block-based editor. |
| 15 |
* |
| 16 |
* @type array $preload_paths Array of paths to preload. |
| 17 |
* @type string $initializer_name Editor initialization function name. |
| 18 |
* @type array $editor_settings Editor settings. |
| 19 |
* } |
| 20 |
* @return void |
| 21 |
*/ |
| 22 |
function gutenberg_initialize_editor( $editor_name, $editor_script_handle, $settings ) { |
| 23 |
|
| 24 |
$defaults = array( |
| 25 |
'preload_paths' => array(), |
| 26 |
'initializer_name' => 'initialize', |
| 27 |
'editor_settings' => array(), |
| 28 |
); |
| 29 |
|
| 30 |
$settings = wp_parse_args( $settings, $defaults ); |
| 31 |
|
| 32 |
/** |
| 33 |
* Preload common data by specifying an array of REST API paths that will be preloaded. |
| 34 |
* |
| 35 |
* Filters the array of paths that will be preloaded. |
| 36 |
* |
| 37 |
* @param string[] $preload_paths Array of paths to preload. |
| 38 |
*/ |
| 39 |
$preload_paths = apply_filters( "{$editor_name}_preload_paths", $settings['preload_paths'] ); |
| 40 |
|
| 41 |
$preload_data = array_reduce( |
| 42 |
$preload_paths, |
| 43 |
'rest_preload_api_request', |
| 44 |
array() |
| 45 |
); |
| 46 |
|
| 47 |
wp_add_inline_script( |
| 48 |
'wp-api-fetch', |
| 49 |
sprintf( |
| 50 |
'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );', |
| 51 |
wp_json_encode( $preload_data ) |
| 52 |
), |
| 53 |
'after' |
| 54 |
); |
| 55 |
wp_add_inline_script( |
| 56 |
"wp-{$editor_script_handle}", |
| 57 |
sprintf( |
| 58 |
'wp.domReady( function() { |
| 59 |
wp.%s.%s( "%s", %s ); |
| 60 |
} );', |
| 61 |
lcfirst( str_replace( '-', '', ucwords( $editor_script_handle, '-' ) ) ), |
| 62 |
$settings['initializer_name'], |
| 63 |
str_replace( '_', '-', $editor_name ), |
| 64 |
wp_json_encode( $settings['editor_settings'] ) |
| 65 |
) |
| 66 |
); |
| 67 |
|
| 68 |
// Preload server-registered block schemas. |
| 69 |
wp_add_inline_script( |
| 70 |
'wp-blocks', |
| 71 |
'wp.blocks.unstable__bootstrapServerSideBlockDefinitions(' . wp_json_encode( get_block_editor_server_block_settings() ) . ');' |
| 72 |
); |
| 73 |
|
| 74 |
} |
| 75 |
|