gutenberg
/
lib
/
experimental
/
interactivity-api
/
class-gutenberg-interactivity-api-full-page-navigation.php
class-gutenberg-interactivity-api-full-page-navigation.php in Gutenberg 23.7.2, at lib/experimental/interactivity-api/class-gutenberg-interactivity-api-full-page-navigation.php
| 1 | <?php |
| 2 | /** |
| 3 | * Interactivity API: Experimental full-page client-side navigation. |
| 4 | * |
| 5 | * @package Gutenberg |
| 6 | * @subpackage Interactivity API |
| 7 | */ |
| 8 | |
| 9 | if ( ! class_exists( 'Gutenberg_Interactivity_API_Full_Page_Navigation' ) ) { |
| 10 | |
| 11 | /** |
| 12 | * Class Gutenberg_Interactivity_API_Full_Page_Navigation. |
| 13 | */ |
| 14 | class Gutenberg_Interactivity_API_Full_Page_Navigation { |
| 15 | |
| 16 | private static $instance = null; |
| 17 | |
| 18 | public static function instance() { |
| 19 | if ( null === self::$instance ) { |
| 20 | self::$instance = new Gutenberg_Interactivity_API_Full_Page_Navigation(); |
| 21 | } |
| 22 | return self::$instance; |
| 23 | } |
| 24 | |
| 25 | public function __construct() { |
| 26 | add_action( 'wp_head', array( $this, 'buffer_start' ) ); |
| 27 | add_action( 'wp_footer', array( $this, 'buffer_end' ), 8 ); |
| 28 | add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_script_modules' ) ); |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Enqueues the required script modules. |
| 33 | */ |
| 34 | public function enqueue_script_modules() { |
| 35 | wp_enqueue_script_module( |
| 36 | '@wordpress/interactivity-router/full-page' |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Starts output buffering at the end of the 'wp_head' action, adding the |
| 42 | * required directives for client-side navigation to the BODY tags when the |
| 43 | * buffer is flushed. |
| 44 | */ |
| 45 | public function buffer_start() { |
| 46 | ob_start( array( $this, 'add_directives_to_body' ) ); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Flushes the output buffer at the end of the 'wp_footer' action. |
| 51 | */ |
| 52 | public function buffer_end() { |
| 53 | ob_end_flush(); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Adds client-side navigation directives to BODY tag in the passed output |
| 58 | * buffer. |
| 59 | * |
| 60 | * Note: This should probably be done per site, not by default when this option |
| 61 | * is enabled. |
| 62 | * |
| 63 | * @param string $buffer Passed output buffer. |
| 64 | * |
| 65 | * @return string The same HTML with modified BODY attributes. |
| 66 | */ |
| 67 | public function add_directives_to_body( $buffer ) { |
| 68 | $p = new WP_HTML_Tag_Processor( $buffer ); |
| 69 | if ( $p->next_tag( array( 'tag_name' => 'BODY' ) ) ) { |
| 70 | $p->set_attribute( 'data-wp-interactive', true ); |
| 71 | $p->set_attribute( 'data-wp-router-region', 'core/body' ); |
| 72 | return $p->get_updated_html(); |
| 73 | } else { |
| 74 | return $buffer; |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 |