Make WordPress Core


Ignore:
Timestamp:
06/26/2024 01:19:47 PM (4 months ago)
Author:
Bernhard Reiter
Message:

Script Modules: Add new API to embed server data in HTML.

Add a new filter script_module_data_{$module_id} to associate data
with a Script Module. For example:

add_filter(
        'script_module_data_MyScriptModuleID',
        function ( array $data ): array {
                $data['script-needs-this-data'] = 'ok';
                return $data;
        }
);

If the Script Module is included in the page, enqueued or as a
dependency, the associated data will be JSON-encoded and embedded in the
HTML in a <script type="application/json"> tag with an ID of the form
wp-script-module-data-{$module_id} allowing the Script Module to
access the data on the client.

See the original proposal: https://make.wordpress.org/core/2024/05/06/proposal-server-to-client-data-sharing-for-script-modules/

Developed in https://github.com/WordPress/wordpress-develop/pull/6682.

Props jonsurrell, cbravobernal, westonruter, gziolo, bernhard-reiter, youknowriad, sergiomdgomes, czapla.
Fixes #61510. See #60647.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-script-modules.php

    r58126 r58579  
    183183        add_action( 'admin_print_footer_scripts', array( $this, 'print_enqueued_script_modules' ) );
    184184        add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_preloads' ) );
     185
     186        add_action( 'wp_footer', array( $this, 'print_script_module_data' ) );
     187        add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_data' ) );
    185188    }
    186189
     
    364367        return $src;
    365368    }
     369
     370    /**
     371     * Print data associated with Script Modules.
     372     *
     373     * The data will be embedded in the page HTML and can be read by Script Modules on page load.
     374     *
     375     * @since 6.7.0
     376     *
     377     * Data can be associated with a Script Module via the
     378     * {@see "script_module_data_{$module_id}"} filter.
     379     *
     380     * The data for a Script Module will be serialized as JSON in a script tag with an ID of the
     381     * form `wp-script-module-data-{$module_id}`.
     382     */
     383    public function print_script_module_data(): void {
     384        $modules = array();
     385        foreach ( array_keys( $this->get_marked_for_enqueue() ) as $id ) {
     386            $modules[ $id ] = true;
     387        }
     388        foreach ( array_keys( $this->get_import_map()['imports'] ) as $id ) {
     389            $modules[ $id ] = true;
     390        }
     391
     392        foreach ( array_keys( $modules ) as $module_id ) {
     393            /**
     394             * Filters data associated with a given Script Module.
     395             *
     396             * Script Modules may require data that is required for initialization or is essential
     397             * to have immediately available on page load. These are suitable use cases for
     398             * this data.
     399             *
     400             * The dynamic portion of the hook name, `$module_id`, refers to the Script Module ID
     401             * that the data is associated with.
     402             *
     403             * This is best suited to pass essential data that must be available to the module for
     404             * initialization or immediately on page load. It does not replace the REST API or
     405             * fetching data from the client.
     406             *
     407             * @example
     408             *   add_filter(
     409             *     'script_module_data_MyScriptModuleID',
     410             *     function ( array $data ): array {
     411             *       $data['script-needs-this-data'] = 'ok';
     412             *       return $data;
     413             *     }
     414             *   );
     415             *
     416             * If the filter returns no data (an empty array), nothing will be embedded in the page.
     417             *
     418             * The data for a given Script Module, if provided, will be JSON serialized in a script
     419             * tag with an ID of the form `wp-script-module-data-{$module_id}`.
     420             *
     421             * The data can be read on the client with a pattern like this:
     422             *
     423             * @example
     424             *   const dataContainer = document.getElementById( 'wp-script-module-data-MyScriptModuleID' );
     425             *   let data = {};
     426             *   if ( dataContainer ) {
     427             *     try {
     428             *       data = JSON.parse( dataContainer.textContent );
     429             *     } catch {}
     430             *   }
     431             *   initMyScriptModuleWithData( data );
     432             *
     433             * @since 6.7.0
     434             *
     435             * @param array $data The data associated with the Script Module.
     436             */
     437            $data = apply_filters( "script_module_data_{$module_id}", array() );
     438
     439            if ( is_array( $data ) && array() !== $data ) {
     440                /*
     441                 * This data will be printed as JSON inside a script tag like this:
     442                 *   <script type="application/json"></script>
     443                 *
     444                 * A script tag must be closed by a sequence beginning with `</`. It's impossible to
     445                 * close a script tag without using `<`. We ensure that `<` is escaped and `/` can
     446                 * remain unescaped, so `</script>` will be printed as `\u003C/script\u00E3`.
     447                 *
     448                 *   - JSON_HEX_TAG: All < and > are converted to \u003C and \u003E.
     449                 *   - JSON_UNESCAPED_SLASHES: Don't escape /.
     450                 *
     451                 * If the page will use UTF-8 encoding, it's safe to print unescaped unicode:
     452                 *
     453                 *   - JSON_UNESCAPED_UNICODE: Encode multibyte Unicode characters literally (instead of as `\uXXXX`).
     454                 *   - JSON_UNESCAPED_LINE_TERMINATORS: The line terminators are kept unescaped when
     455                 *     JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was
     456                 *     before PHP 7.1 without this constant. Available as of PHP 7.1.0.
     457                 *
     458                 * The JSON specification requires encoding in UTF-8, so if the generated HTML page
     459                 * is not encoded in UTF-8 then it's not safe to include those literals. They must
     460                 * be escaped to avoid encoding issues.
     461                 *
     462                 * @see https://www.rfc-editor.org/rfc/rfc8259.html for details on encoding requirements.
     463                 * @see https://www.php.net/manual/en/json.constants.php for details on these constants.
     464                 * @see https://html.spec.whatwg.org/#script-data-state for details on script tag parsing.
     465                 */
     466                $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS;
     467                if ( ! is_utf8_charset() ) {
     468                    $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES;
     469                }
     470
     471                wp_print_inline_script_tag(
     472                    wp_json_encode(
     473                        $data,
     474                        $json_encode_flags
     475                    ),
     476                    array(
     477                        'type' => 'application/json',
     478                        'id'   => "wp-script-module-data-{$module_id}",
     479                    )
     480                );
     481            }
     482        }
     483    }
    366484}
Note: See TracChangeset for help on using the changeset viewer.