-
Notifications
You must be signed in to change notification settings - Fork 4k
/
class-wp-interactivity-initial-state.php
82 lines (75 loc) · 1.65 KB
/
class-wp-interactivity-initial-state.php
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
<?php
/**
* WP_Interactivity_Initial_State class
*
* @package Gutenberg
* @subpackage Interactivity API
*/
if ( class_exists( 'WP_Interactivity_Initial_State' ) ) {
return;
}
/**
* Manages the initial state of the Interactivity API store in the server and
* its serialization so it can be restored in the browser upon hydration.
*
* @package Gutenberg
* @subpackage Interactivity API
*/
class WP_Interactivity_Initial_State {
/**
* Map of initial state by namespace.
*
* @var array
*/
private static $initial_state = array();
/**
* Get state from a given namespace.
*
* @param string $store_ns Namespace.
*
* @return array The requested state.
*/
public static function get_state( $store_ns ) {
return self::$initial_state[ $store_ns ] ?? array();
}
/**
* Merge data into the state with the given namespace.
*
* @param string $store_ns Namespace.
* @param array $data State to merge.
*
* @return void
*/
public static function merge_state( $store_ns, $data ) {
self::$initial_state[ $store_ns ] = array_replace_recursive(
self::get_state( $store_ns ),
$data
);
}
/**
* Get store data.
*
* @return array
*/
public static function get_data() {
return self::$initial_state;
}
/**
* Reset the initial state.
*/
public static function reset() {
self::$initial_state = array();
}
/**
* Render the initial state.
*/
public static function render() {
if ( empty( self::$initial_state ) ) {
return;
}
echo sprintf(
'<script id="wp-interactivity-initial-state" type="application/json">%s</script>',
wp_json_encode( self::$initial_state, JSON_HEX_TAG | JSON_HEX_AMP )
);
}
}