-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathattributes-for-blocks.php
313 lines (253 loc) · 7.43 KB
/
attributes-for-blocks.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<?php
/**
* Plugin Name: Attributes for Blocks
* Plugin URI: https://wordpress.org/plugins/attributes-for-blocks
* Description: Allows to add HTML attributes to Gutenberg blocks.
* Version: 1.0.10
* Author: websevendev
* Author URI: https://github.com/websevendev
*/
namespace wsd\afb;
use WP_HTML_Tag_Processor;
defined('ABSPATH') || exit;
function_exists('get_plugin_data') || require_once ABSPATH . 'wp-admin/includes/plugin.php';
$afb_plugin = get_plugin_data(__FILE__, false, false);
define('WSD_AFB_VER', $afb_plugin['Version']);
define('WSD_AFB_FILE', __FILE__);
define('WSD_AFB_DIR', dirname(__FILE__));
/**
* Blocks known to not work properly with Attributes for Blocks.
*
* @return array
*/
function get_unsupported_blocks() {
return apply_filters('afb_unsupported_blocks', [
'core/freeform',
'core/html',
'core/shortcode',
'core/legacy-widget',
]);
}
/**
* Enqueue editor assets.
*/
function editor_assets() {
$asset = include WSD_AFB_DIR . '/build/index.asset.php';
wp_enqueue_style(
'attributes-for-blocks',
plugins_url('build/style-index.css', WSD_AFB_FILE),
[],
$asset['version'],
'all'
);
wp_enqueue_script(
'attributes-for-blocks',
plugins_url('build/index.js', WSD_AFB_FILE),
$asset['dependencies'],
$asset['version'],
false
);
wp_localize_script(
'attributes-for-blocks',
'afbData',
['unsupportedBlocks' => get_unsupported_blocks()]
);
if(function_exists('wp_set_script_translations')) {
wp_set_script_translations('attributes-for-blocks', 'attributes-for-blocks');
}
}
add_action('enqueue_block_editor_assets', __NAMESPACE__ . '\\editor_assets', 5);
/**
* Should additional attributes from this plugin be applied to a block.
*
* @param mixed $attributes Block attributes.
* @return boolean
*/
function has_attributes($attributes) {
return is_array($attributes)
&& isset($attributes['attributesForBlocks'])
&& is_array($attributes['attributesForBlocks'])
&& count($attributes['attributesForBlocks']) > 0;
}
/**
* Handle merging custom attribute with existing attribute.
*
* @param string $attribute Attribute name.
* @param string $current Current attribute value.
* @param string $add Value to merge with.
* @return string
*/
function merge_attributes($attribute, $current, $add) {
/** Clean attribute. */
switch($attribute) {
case 'style':
/** Ensure style applied via JS matches input style. */
$add = str_replace(': ', ':', $add);
$add = str_replace('; ', ';', $add);
$add = rtrim($add, ';');
$current = rtrim($current, ';');
/** Fix `WP_HTML_Tag_Processor` stripping leading `-`, causing a mismatch. */
$current = str_replace('-afb-placeholder', 'afb-placeholder', $current);
$current = str_replace('afb-placeholder', '-afb-placeholder', $current);
break;
}
$current = trim(
/** Remove the existing attribute value when it already exists (added via JS while the block also has PHP `render_callback`). */
str_replace($add, '', $current)
);
$add = trim($add);
/** Nothing to merge. */
if(empty($current)) {
return $add;
}
/** Determine the separator based on attribute type. */
$separator = ' ';
switch($attribute) {
case 'style':
if(substr($current, -1) !== ';' && substr($add, 0, 1) !== ';') {
$separator = ';';
}
break;
}
$separator = apply_filters('afb_attribute_separator', $separator, $attribute);
return implode($separator, [$current, $add]);
}
/**
* @param array $args AFB settings.
* @param WP_HTML_Tag_Processor $tags
* @return array Attribute name and value pairs.
*/
function get_attributes($args, $tags) {
$attributes = [];
foreach($args as $key => $value) {
/** Override attribute. */
if(strpos($key, '@') === 0) {
$attributes[substr($key, 1)] = $value;
continue;
}
/** Merge attribute. */
$attributes[$key] = merge_attributes(
$key,
$tags->get_attribute($key) ?? '',
$value
);
}
return apply_filters('afb_get_attributes', $attributes, $args, $tags);
}
/**
* Add attributes to block root element.
*
* @param array $args AFB settings.
* @param string $html Block HTML.
* @return string Block HTML with additional attributes.
*/
function add_attributes($args, $html) {
$tags = new WP_HTML_Tag_Processor($html);
if($tags->next_tag()) {
/** Add attributes. */
foreach(get_attributes($args, $tags) as $key => $value) {
$tags->set_attribute($key, $value);
}
return $tags->get_updated_html();
}
return $html;
}
/**
* When registering a block, add AFB argument and wrap `render_callback`.
*
* @param array $args
* @param string $name
* @return array
*/
function block_args($args, $name) {
static $not_supported;
if(!is_array($not_supported)) {
$not_supported = get_unsupported_blocks();
}
if(in_array($name, $not_supported, true)) {
return $args;
}
if(!isset($args['attributes']) || !is_array($args['attributes'])) {
$args['attributes'] = [];
}
/** Register AFB attributes, this is necessary for `/wp-json/wp/v2/block-renderer` REST endpoint to not throw `rest_additional_properties_forbidden`. */
$args['attributes']['attributesForBlocks'] = [
'type' => 'object',
'default' => [],
];
return $args;
}
add_filter('register_block_type_args', __NAMESPACE__ . '\\block_args', 10, 2);
/**
* Add attributes to blocks' root HTML element when applicable.
*
* @param string $block_content Rendered block.
* @param string $block Parsed array representation of block.
* @return string
*/
function render_block($block_content, $block) {
static $not_supported;
if(!is_array($not_supported)) {
$not_supported = get_unsupported_blocks();
}
if(in_array($block['blockName'], $not_supported, true)) {
return $block_content;
}
if(!has_attributes($block['attrs'] ?? [])) {
return $block_content;
}
return add_attributes($block['attrs']['attributesForBlocks'], $block_content);
}
add_filter('render_block', __NAMESPACE__ . '\\render_block', 10, 2);
/**
* Strips `attributesForBlocks` block attribute when the current user doesn't have `unfiltered_html` capabilities.
*
* @param string $content Content to filter through KSES.
*/
function sanitize_attributes($content) {
if(strpos($content, '<!-- wp:') === false) { // !has_blocks()
return $content;
}
if(strpos($content, 'attributesForBlocks') === false) {
return $content;
}
if(!defined('SECURE_AUTH_COOKIE')) {
if(!function_exists('wp_cookie_constants')) {
require ABSPATH . WPINC . '/default-constants.php';
}
wp_cookie_constants();
}
if(!function_exists('wp_get_current_user')) {
require ABSPATH . WPINC . '/pluggable.php';
}
if(current_user_can('unfiltered_html')) {
return $content;
}
$matches = null;
if(preg_match_all('/\\\?"attributesForBlocks\\\?"\s*:\s*{[^}]*}/', $content, $matches)) {
foreach($matches[0] as $atts) {
$empty_atts = '"attributesForBlocks":{}';
$was_slashed = wp_unslash($atts) !== $atts;
if($was_slashed) {
$empty_atts = wp_slash($empty_atts);
}
$content = str_replace($atts, $empty_atts, $content);
}
}
return $content;
}
add_filter('pre_kses', __NAMESPACE__ . '\\sanitize_attributes');
/**
* Add GitHub link on the plugins page.
*
* @param array $plugin_meta
* @param string $plugin_file
* @return array
*/
function github_link($plugin_meta, $plugin_file) {
if($plugin_file === plugin_basename(WSD_AFB_FILE)) {
$plugin_meta[] = '<a href="https://github.com/websevendev/attributes-for-blocks" target="_blank" rel="noopener noreferrer">GitHub</a>';
}
return $plugin_meta;
}
add_filter('plugin_row_meta', __NAMESPACE__ . '\\github_link', 10, 2);