PluginProbe
Gutenberg / 5.6.1
Gutenberg v5.6.1
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / lib / client-assets.php

client-assets.php in Gutenberg 5.6.1, at lib/client-assets.php

592 lines 19.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Functions to register client-side assets (scripts and stylesheets) for the
4 * Gutenberg editor plugin.
5 *
6 * @package gutenberg
7 */
8
9 if ( ! defined( 'ABSPATH' ) ) {
10 die( 'Silence is golden.' );
11 }
12
13 /**
14 * Retrieves the root plugin path.
15 *
16 * @return string Root path to the gutenberg plugin.
17 *
18 * @since 0.1.0
19 */
20 function gutenberg_dir_path() {
21 return plugin_dir_path( dirname( __FILE__ ) );
22 }
23
24 /**
25 * Retrieves a URL to a file in the gutenberg plugin.
26 *
27 * @param string $path Relative path of the desired file.
28 *
29 * @return string Fully qualified URL pointing to the desired file.
30 *
31 * @since 0.1.0
32 */
33 function gutenberg_url( $path ) {
34 return plugins_url( $path, dirname( __FILE__ ) );
35 }
36
37 /**
38 * Registers a script according to `wp_register_script`. Honors this request by
39 * reassigning internal dependency properties of any script handle already
40 * registered by that name. It does not deregister the original script, to
41 * avoid losing inline scripts which may have been attached.
42 *
43 * @since 4.1.0
44 *
45 * @param string $handle Name of the script. Should be unique.
46 * @param string $src Full URL of the script, or path of the script relative to the WordPress root directory.
47 * @param array $deps Optional. An array of registered script handles this script depends on. Default empty array.
48 * @param string|bool|null $ver Optional. String specifying script version number, if it has one, which is added to the URL
49 * as a query string for cache busting purposes. If version is set to false, a version
50 * number is automatically added equal to current installed WordPress version.
51 * If set to null, no version is added.
52 * @param bool $in_footer Optional. Whether to enqueue the script before </body> instead of in the <head>.
53 * Default 'false'.
54 */
55 function gutenberg_override_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false ) {
56 global $wp_scripts;
57
58 $script = $wp_scripts->query( $handle, 'registered' );
59 if ( $script ) {
60 /*
61 * In many ways, this is a reimplementation of `wp_register_script` but
62 * bypassing consideration of whether a script by the given handle had
63 * already been registered.
64 */
65
66 // See: `_WP_Dependency::__construct` .
67 $script->src = $src;
68 $script->deps = $deps;
69 $script->ver = $ver;
70
71 /*
72 * The script's `group` designation is an indication of whether it is
73 * to be printed in the header or footer. The behavior here defers to
74 * the arguments as passed. Specifically, group data is not assigned
75 * for a script unless it is designated to be printed in the footer.
76 */
77
78 // See: `wp_register_script` .
79 unset( $script->extra['group'] );
80 if ( $in_footer ) {
81 $script->add_data( 'group', 1 );
82 }
83 } else {
84 wp_register_script( $handle, $src, $deps, $ver, $in_footer );
85 }
86
87 /*
88 * `WP_Dependencies::set_translations` will fall over on itself if setting
89 * translations on the `wp-i18n` handle, since it internally adds `wp-i18n`
90 * as a dependency of itself, exhausting memory. The same applies for the
91 * polyfill script, which is a dependency _of_ `wp-i18n`.
92 *
93 * See: https://core.trac.wordpress.org/ticket/46089
94 */
95 if ( 'wp-i18n' !== $handle && 'wp-polyfill' !== $handle ) {
96 wp_set_script_translations( $handle, 'default' );
97 }
98 }
99
100 /**
101 * Filters the default translation file load behavior to load the Gutenberg
102 * plugin translation file, if available.
103 *
104 * @param string|false $file Path to the translation file to load. False if
105 * there isn't one.
106 * @param string $handle Name of the script to register a translation
107 * domain to.
108 *
109 * @return string|false Filtered path to the Gutenberg translation file, if
110 * available.
111 */
112 function gutenberg_override_translation_file( $file, $handle ) {
113 if ( ! $file ) {
114 return $file;
115 }
116
117 // Only override script handles generated from the Gutenberg plugin.
118 $packages_dependencies = include dirname( __FILE__ ) . '/packages-dependencies.php';
119 if ( ! isset( $packages_dependencies[ $handle ] ) ) {
120 return $file;
121 }
122
123 /*
124 * The default file will be in the plugins language directory, omitting the
125 * domain since Gutenberg assigns the script translations as the default.
126 *
127 * Example: /www/wp-content/languages/plugins/de_DE-07d88e6a803e01276b9bfcc1203e862e.json
128 *
129 * The logic of `load_script_textdomain` is such that it will assume to
130 * search in the plugins language directory, since the assigned source of
131 * the overridden Gutenberg script originates in the plugins directory.
132 *
133 * The plugin translation files each begin with the slug of the plugin, so
134 * it's a simple matter of prepending the Gutenberg plugin slug.
135 */
136 $path_parts = pathinfo( $file );
137 $plugin_translation_file = (
138 $path_parts['dirname'] .
139 '/gutenberg-' .
140 $path_parts['basename']
141 );
142
143 if ( ! is_readable( $plugin_translation_file ) ) {
144 return $file;
145 }
146
147 return $plugin_translation_file;
148 }
149 add_filter( 'load_script_translation_file', 'gutenberg_override_translation_file', 10, 2 );
150
151 /**
152 * Registers a style according to `wp_register_style`. Honors this request by
153 * deregistering any style by the same handler before registration.
154 *
155 * @since 4.1.0
156 *
157 * @param string $handle Name of the stylesheet. Should be unique.
158 * @param string $src Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory.
159 * @param array $deps Optional. An array of registered stylesheet handles this stylesheet depends on. Default empty array.
160 * @param string|bool|null $ver Optional. String specifying stylesheet version number, if it has one, which is added to the URL
161 * as a query string for cache busting purposes. If version is set to false, a version
162 * number is automatically added equal to current installed WordPress version.
163 * If set to null, no version is added.
164 * @param string $media Optional. The media for which this stylesheet has been defined.
165 * Default 'all'. Accepts media types like 'all', 'print' and 'screen', or media queries like
166 * '(orientation: portrait)' and '(max-width: 640px)'.
167 */
168 function gutenberg_override_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) {
169 wp_deregister_style( $handle );
170 wp_register_style( $handle, $src, $deps, $ver, $media );
171 }
172
173 /**
174 * Registers all the WordPress packages scripts that are in the standardized
175 * `build/` location.
176 *
177 * @since 4.5.0
178 */
179 function gutenberg_register_packages_scripts() {
180 $packages_dependencies = include dirname( __FILE__ ) . '/packages-dependencies.php';
181
182 foreach ( $packages_dependencies as $handle => $dependencies ) {
183 // Remove `wp-` prefix from the handle to get the package's name.
184 $package_name = strpos( $handle, 'wp-' ) === 0 ? substr( $handle, 3 ) : $handle;
185 $path = "build/$package_name/index.js";
186 gutenberg_override_script(
187 $handle,
188 gutenberg_url( $path ),
189 array_merge( $dependencies, array( 'wp-polyfill' ) ),
190 filemtime( gutenberg_dir_path() . $path ),
191 true
192 );
193 }
194 }
195
196 /**
197 * Registers common scripts and styles to be used as dependencies of the editor
198 * and plugins.
199 *
200 * @since 0.1.0
201 */
202 function gutenberg_register_scripts_and_styles() {
203 global $wp_scripts;
204
205 gutenberg_register_vendor_scripts();
206 gutenberg_register_packages_scripts();
207
208 // Add nonce middleware which accounts for the absence of the heartbeat
209 // listener. This relies on API Fetch implementation running middlewares in
210 // order of last added, and that the original nonce middleware would defer
211 // to an X-WP-Nonce header already being present. This inline script should
212 // be removed once the following Core ticket is resolved in assigning the
213 // nonce received from heartbeat to the created middleware.
214 //
215 // See: https://core.trac.wordpress.org/ticket/46107 .
216 // See: https://github.com/WordPress/gutenberg/pull/13451 .
217 global $wp_scripts;
218 if ( isset( $wp_scripts->registered['wp-api-fetch'] ) ) {
219 $wp_scripts->registered['wp-api-fetch']->deps[] = 'wp-hooks';
220 }
221 wp_add_inline_script(
222 'wp-api-fetch',
223 sprintf(
224 implode(
225 "\n",
226 array(
227 '( function() {',
228 ' var nonceMiddleware = wp.apiFetch.createNonceMiddleware( "%s" );',
229 ' wp.apiFetch.use( nonceMiddleware );',
230 ' wp.hooks.addAction(',
231 ' "heartbeat.tick",',
232 ' "core/api-fetch/create-nonce-middleware",',
233 ' function( response ) {',
234 ' if ( response[ "rest_nonce" ] ) {',
235 ' nonceMiddleware.nonce = response[ "rest_nonce" ];',
236 ' }',
237 ' }',
238 ' )',
239 '} )();',
240 )
241 ),
242 ( wp_installing() && ! is_multisite() ) ? '' : wp_create_nonce( 'wp_rest' )
243 ),
244 'after'
245 );
246
247 // TEMPORARY: Core does not (yet) provide persistence migration from the
248 // introduction of the block editor and still calls the data plugins.
249 // We unset the existing inline scripts first.
250 $wp_scripts->registered['wp-data']->extra['after'] = array();
251 wp_add_inline_script(
252 'wp-data',
253 implode(
254 "\n",
255 array(
256 '( function() {',
257 ' var userId = ' . get_current_user_ID() . ';',
258 ' var storageKey = "WP_DATA_USER_" + userId;',
259 ' wp.data',
260 ' .use( wp.data.plugins.persistence, { storageKey: storageKey } );',
261 ' wp.data.plugins.persistence.__unstableMigrate( { storageKey: storageKey } );',
262 '} )();',
263 )
264 )
265 );
266
267 // Editor Styles.
268 // This empty stylesheet is defined to ensure backward compatibility.
269 gutenberg_override_style( 'wp-blocks', false );
270
271 gutenberg_override_style(
272 'wp-block-editor',
273 gutenberg_url( 'build/block-editor/style.css' ),
274 array( 'wp-components', 'wp-editor-font' ),
275 filemtime( gutenberg_dir_path() . 'build/editor/style.css' )
276 );
277 wp_style_add_data( 'wp-block-editor', 'rtl', 'replace' );
278
279 gutenberg_override_style(
280 'wp-editor',
281 gutenberg_url( 'build/editor/style.css' ),
282 array( 'wp-components', 'wp-block-editor', 'wp-nux' ),
283 filemtime( gutenberg_dir_path() . 'build/editor/style.css' )
284 );
285 wp_style_add_data( 'wp-editor', 'rtl', 'replace' );
286
287 gutenberg_override_style(
288 'wp-edit-post',
289 gutenberg_url( 'build/edit-post/style.css' ),
290 array( 'wp-components', 'wp-block-editor', 'wp-editor', 'wp-edit-blocks', 'wp-block-library', 'wp-nux' ),
291 filemtime( gutenberg_dir_path() . 'build/edit-post/style.css' )
292 );
293 wp_style_add_data( 'wp-edit-post', 'rtl', 'replace' );
294
295 gutenberg_override_style(
296 'wp-components',
297 gutenberg_url( 'build/components/style.css' ),
298 array(),
299 filemtime( gutenberg_dir_path() . 'build/components/style.css' )
300 );
301 wp_style_add_data( 'wp-components', 'rtl', 'replace' );
302
303 gutenberg_override_style(
304 'wp-block-library',
305 gutenberg_url( 'build/block-library/style.css' ),
306 array(),
307 filemtime( gutenberg_dir_path() . 'build/block-library/style.css' )
308 );
309 wp_style_add_data( 'wp-block-library', 'rtl', 'replace' );
310
311 gutenberg_override_style(
312 'wp-format-library',
313 gutenberg_url( 'build/format-library/style.css' ),
314 array( 'wp-block-editor', 'wp-components' ),
315 filemtime( gutenberg_dir_path() . 'build/format-library/style.css' )
316 );
317 wp_style_add_data( 'wp-format-library', 'rtl', 'replace' );
318
319 gutenberg_override_style(
320 'wp-edit-blocks',
321 gutenberg_url( 'build/block-library/editor.css' ),
322 array(
323 'wp-components',
324 'wp-editor',
325 'wp-block-library',
326 // Always include visual styles so the editor never appears broken.
327 'wp-block-library-theme',
328 ),
329 filemtime( gutenberg_dir_path() . 'build/block-library/editor.css' )
330 );
331 wp_style_add_data( 'wp-edit-blocks', 'rtl', 'replace' );
332
333 gutenberg_override_style(
334 'wp-nux',
335 gutenberg_url( 'build/nux/style.css' ),
336 array( 'wp-components' ),
337 filemtime( gutenberg_dir_path() . 'build/nux/style.css' )
338 );
339 wp_style_add_data( 'wp-nux', 'rtl', 'replace' );
340
341 gutenberg_override_style(
342 'wp-block-library-theme',
343 gutenberg_url( 'build/block-library/theme.css' ),
344 array(),
345 filemtime( gutenberg_dir_path() . 'build/block-library/theme.css' )
346 );
347 wp_style_add_data( 'wp-block-library-theme', 'rtl', 'replace' );
348
349 gutenberg_override_style(
350 'wp-list-reusable-blocks',
351 gutenberg_url( 'build/list-reusable-blocks/style.css' ),
352 array( 'wp-components' ),
353 filemtime( gutenberg_dir_path() . 'build/list-reusable-blocks/style.css' )
354 );
355 wp_style_add_data( 'wp-list-reusable-block', 'rtl', 'replace' );
356
357 gutenberg_override_style(
358 'wp-edit-widgets',
359 gutenberg_url( 'build/edit-widgets/style.css' ),
360 array( 'wp-components', 'wp-block-editor', 'wp-edit-blocks' ),
361 filemtime( gutenberg_dir_path() . 'build/edit-widgets/style.css' )
362 );
363 wp_style_add_data( 'wp-edit-widgets', 'rtl', 'replace' );
364
365 if ( defined( 'GUTENBERG_LIVE_RELOAD' ) && GUTENBERG_LIVE_RELOAD ) {
366 $live_reload_url = ( GUTENBERG_LIVE_RELOAD === true ) ? 'http://localhost:35729/livereload.js' : GUTENBERG_LIVE_RELOAD;
367
368 wp_enqueue_script(
369 'gutenberg-live-reload',
370 $live_reload_url
371 );
372 }
373 }
374 add_action( 'wp_enqueue_scripts', 'gutenberg_register_scripts_and_styles', 5 );
375 add_action( 'admin_enqueue_scripts', 'gutenberg_register_scripts_and_styles', 5 );
376
377 /**
378 * Registers vendor JavaScript files to be used as dependencies of the editor
379 * and plugins.
380 *
381 * This function is called from a script during the plugin build process, so it
382 * should not call any WordPress PHP functions.
383 *
384 * @since 0.1.0
385 */
386 function gutenberg_register_vendor_scripts() {
387 $suffix = SCRIPT_DEBUG ? '' : '.min';
388
389 // Vendor Scripts.
390 $react_suffix = ( SCRIPT_DEBUG ? '.development' : '.production' ) . $suffix;
391
392 gutenberg_register_vendor_script(
393 'react',
394 'https://unpkg.com/react@16.8.4/umd/react' . $react_suffix . '.js',
395 array( 'wp-polyfill' )
396 );
397 gutenberg_register_vendor_script(
398 'react-dom',
399 'https://unpkg.com/react-dom@16.8.4/umd/react-dom' . $react_suffix . '.js',
400 array( 'react' )
401 );
402 }
403
404 /**
405 * Retrieves a unique and reasonably short and human-friendly filename for a
406 * vendor script based on a URL and the script handle.
407 *
408 * @param string $handle The name of the script.
409 * @param string $src Full URL of the external script.
410 *
411 * @return string Script filename suitable for local caching.
412 *
413 * @since 0.1.0
414 */
415 function gutenberg_vendor_script_filename( $handle, $src ) {
416 $filename = basename( $src );
417 $match = preg_match(
418 '/^'
419 . '(?P<ignore>.*?)'
420 . '(?P<suffix>\.min)?'
421 . '(?P<extension>\.js)'
422 . '(?P<extra>.*)'
423 . '$/',
424 $filename,
425 $filename_pieces
426 );
427
428 $prefix = $handle;
429 $suffix = $match ? $filename_pieces['suffix'] : '';
430 $hash = substr( md5( $src ), 0, 8 );
431
432 return "${prefix}${suffix}.${hash}.js";
433 }
434
435 /**
436 * Registers a vendor script from a URL, preferring a locally cached version if
437 * possible, or downloading it if the cached version is unavailable or
438 * outdated.
439 *
440 * @param string $handle Name of the script.
441 * @param string $src Full URL of the external script.
442 * @param array $deps Optional. An array of registered script handles this
443 * script depends on.
444 *
445 * @since 0.1.0
446 */
447 function gutenberg_register_vendor_script( $handle, $src, $deps = array() ) {
448 if ( defined( 'GUTENBERG_LOAD_VENDOR_SCRIPTS' ) && ! GUTENBERG_LOAD_VENDOR_SCRIPTS ) {
449 return;
450 }
451
452 $filename = gutenberg_vendor_script_filename( $handle, $src );
453
454 if ( defined( 'GUTENBERG_LIST_VENDOR_ASSETS' ) && GUTENBERG_LIST_VENDOR_ASSETS ) {
455 echo "$src|$filename\n";
456 return;
457 }
458
459 $full_path = gutenberg_dir_path() . 'vendor/' . $filename;
460
461 $needs_fetch = (
462 defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE && (
463 ! file_exists( $full_path ) ||
464 time() - filemtime( $full_path ) >= DAY_IN_SECONDS
465 )
466 );
467
468 if ( $needs_fetch ) {
469 // Determine whether we can write to this file. If not, don't waste
470 // time doing a network request.
471 // @codingStandardsIgnoreStart
472 $f = @fopen( $full_path, 'a' );
473 // @codingStandardsIgnoreEnd
474 if ( ! $f ) {
475 // Failed to open the file for writing, probably due to server
476 // permissions. Enqueue the script directly from the URL instead.
477 gutenberg_override_script( $handle, $src, $deps, null );
478 return;
479 }
480 fclose( $f );
481 $response = wp_remote_get( $src );
482 if ( wp_remote_retrieve_response_code( $response ) === 200 ) {
483 $f = fopen( $full_path, 'w' );
484 fwrite( $f, wp_remote_retrieve_body( $response ) );
485 fclose( $f );
486 } elseif ( ! filesize( $full_path ) ) {
487 // The request failed. If the file is already cached, continue to
488 // use this file. If not, then unlink the 0 byte file, and enqueue
489 // the script directly from the URL.
490 gutenberg_override_script( $handle, $src, $deps, null );
491 unlink( $full_path );
492 return;
493 }
494 }
495 gutenberg_override_script(
496 $handle,
497 gutenberg_url( 'vendor/' . $filename ),
498 $deps,
499 null
500 );
501 }
502
503 /**
504 * Extends block editor settings to include Gutenberg's `editor-styles.css` as
505 * taking precedent those styles shipped with core.
506 *
507 * @param array $settings Default editor settings.
508 *
509 * @return array Filtered editor settings.
510 */
511 function gutenberg_extend_block_editor_styles( $settings ) {
512 $editor_styles_file = gutenberg_dir_path() . 'build/editor/editor-styles.css';
513
514 /*
515 * If, for whatever reason, the built editor styles do not exist, avoid
516 * override and fall back to the default.
517 */
518 if ( ! file_exists( $editor_styles_file ) ) {
519 return $settings;
520 }
521
522 if ( empty( $settings['styles'] ) ) {
523 $settings['styles'] = array();
524 } else {
525 /*
526 * The styles setting is an array of CSS strings, so there is no direct
527 * way to find the default styles. To maximize stability, load (again)
528 * the default styles from disk and find its place in the array.
529 *
530 * See: https://github.com/WordPress/wordpress-develop/blob/5.0.3/src/wp-admin/edit-form-blocks.php#L168-L175
531 */
532
533 $default_styles = file_get_contents(
534 ABSPATH . WPINC . '/css/dist/editor/editor-styles.css'
535 );
536
537 /*
538 * Iterate backwards from the end of the array since the preferred
539 * insertion point in case not found is prepended as first entry.
540 */
541 for ( $i = count( $settings['styles'] ) - 1; $i >= 0; $i-- ) {
542 if ( isset( $settings['styles'][ $i ]['css'] ) &&
543 $default_styles === $settings['styles'][ $i ]['css'] ) {
544 break;
545 }
546 }
547 }
548
549 $editor_styles = array(
550 'css' => file_get_contents( $editor_styles_file ),
551 );
552
553 // Substitute default styles if found. Otherwise, prepend to setting array.
554 if ( isset( $i ) && $i >= 0 ) {
555 $settings['styles'][ $i ] = $editor_styles;
556 } else {
557 array_unshift( $settings['styles'], $editor_styles );
558 }
559
560 return $settings;
561 }
562 add_filter( 'block_editor_settings', 'gutenberg_extend_block_editor_styles' );
563
564 /**
565 * Extends block editor preload paths to preload additional data. Note that any
566 * additions here should be complemented with a corresponding core ticket to
567 * reconcile the change upstream for future removal from Gutenberg.
568 *
569 * @since 5.6.0
570 *
571 * @param array $preload_paths $preload_paths Array of paths to preload.
572 *
573 * @return array Filtered array of paths to preload.
574 */
575 function gutenberg_extend_block_editor_preload_paths( $preload_paths ) {
576 /*
577 * Used in considering user permissions for creating and updating blocks,
578 * as condition for displaying relevant actions in the interface.
579 *
580 * Trac ticket: https://core.trac.wordpress.org/ticket/46429
581 *
582 * This is present in WordPress 5.2 and should be removed from Gutenberg
583 * once WordPress 5.2 is the minimum supported version.
584 */
585 if ( ! in_array( array( '/wp/v2/blocks', 'OPTIONS' ), $preload_paths ) ) {
586 $preload_paths[] = array( '/wp/v2/blocks', 'OPTIONS' );
587 }
588
589 return $preload_paths;
590 }
591 add_filter( 'block_editor_preload_paths', 'gutenberg_extend_block_editor_preload_paths' );
592