-
Notifications
You must be signed in to change notification settings - Fork 0
/
mai-columns.php
474 lines (408 loc) · 10.7 KB
/
mai-columns.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
<?php
/**
* Plugin Name: Mai Columns
* Description: Create simple and complex repeatable column arrangements quickly.
* Requires at least: 6.1
* Requires PHP: 7.0
* Version: 0.1.0
* Author: Bizbudding
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: mai-columns
*/
// Prevent direct file access.
defined( 'ABSPATH' ) || die;
$block = new Mai_Columns_Block;
class Mai_Columns_Block {
/**
* Construct the class.
*/
function __construct() {
$this->hooks();
}
/**
* Add hooks.
*
* @since 0.1.0
*
* @return void
*/
function hooks() {
add_action( 'init', [ $this, 'block_init' ] );
}
/**
* Registers the block using the metadata loaded from the `block.json` file.
* Behind the scenes, it registers also all assets so they can be enqueued
* through the block editor in the corresponding context.
*
* @since 0.1.0
*
* @return void
*/
function block_init() {
register_block_type( __DIR__ . '/build/columns',
[
'render_callback' => [ $this, 'get_columns' ],
]
);
register_block_type( __DIR__ . '/build/column',
[
'render_callback' => [ $this, 'get_column' ],
]
);
}
/**
* Get columns.
*
* @since 0.1.0
*
* @param array $attributes The block attributes.
* @param string $content The block inner content.
* @param WP_Block $block The block object.
*
* @return string
*/
function get_columns( $attributes, $content, $block ) {
// Bail if in the editor.
if ( is_admin() ) {
return;
}
// Bail if no content.
if ( ! $content ) {
return sprintf( '<div class="mai-columns">%s</div>', $content );
}
// Get arrangements.
$arrangements = [
'lg' => $attributes['sizesLg'],
'md' => $attributes['sizesMd'],
'sm' => $attributes['sizesSm'],
];
// Set fallbacks.
foreach ( $arrangements as $key => $value ) {
if ( ! $value ) {
$keys = array_keys( $arrangements );
$shift = array_shift( $keys );
$arrangements[ $key ] = $arrangements[ $shift ];
}
}
// Get column nodes.
$dom = $this->get_dom_document( $content );
$xpath = new DOMXPath( $dom );
$columns = $xpath->query( '/div[contains(concat(" ", normalize-space(@class), " "), " mai-column ")]' );
// Bail if no columns.
if ( ! $columns->length ) {
return sprintf( '<div class="mai-columns">%s</div>', $content );
}
// Start counter.
$i = 0;
// Loop through columns, adding styles.
foreach ( $columns as $column ) {
$columns = [];
$flexes = [];
$styles = (string) $column->getAttribute( 'style' );
$styles = explode( ';', $styles );
$styles = array_map( 'trim', $styles );
$styles = array_filter( $styles );
// Loop through arrangements, setting custom properties by breakpoint.
foreach ( $arrangements as $key => $values ) {
$size = $values ? $this->get_index_value_from_array( $i, $values ) : '';
$columns[] = sprintf( '--size-%s:%s', $key, $this->get_fraction( $size ) ?: 1 );
$flexes[] = sprintf( '--flex-%s:%s', $key, $this->get_flex( $size ) );
}
// Merge styles.
$styles = array_merge( $styles, $columns, $flexes );
// Handle styles attribute.
if ( $styles ) {
$column->setAttribute( 'style', implode( ';', $styles ) );
} else {
$column->removeAttribute( 'style' );
}
// Increment counter.
$i++;
}
// Save content.
$content = $dom->saveHTML();
// Build default atts.
$style = [];
$atts = [
'class' => 'mai-columns',
];
// Add align-items.
if ( isset( $attributes['alignItems'] ) ) {
$style[] = isset( $attributes['alignItems'] ) ? sprintf( '--align-items:%s;', $this->get_flex_css_value( $attributes['alignItems'] ) ) : 'initial';
}
// Add justify-content.
if ( isset( $attributes['justifyContent'] ) ) {
$style[] = isset( $attributes['justifyContent'] ) ? sprintf( '--justify-content:%s;', $this->get_flex_css_value( $attributes['justifyContent'] ) ) : 'initial';
}
// Add block gaps.
if ( isset( $attributes['style']['spacing']['blockGap'] ) ) {
$gap = $this->get_block_gap( $attributes['style']['spacing']['blockGap'] );
if ( $gap ) {
foreach ( $gap as $position => $value ) {
$style[] = sprintf( '--%s-gap:%s;', $position, $value );
}
}
}
// Add inline styles.
if ( $style ) {
$atts['style'] = implode( '', $style );
}
// Get attributes with custom class first, and replace `wp-block-` with an emtpy string.
$attr = get_block_wrapper_attributes( $atts );
$attr = str_replace( ' wp-block-mai-columns', '', $attr );
return sprintf( '<div %s>%s</div>', trim( $attr ), $content );
}
/**
* Get row items.
*
* @since 0.1.0
*
* @param array $attributes The block attributes.
* @param string $content The block inner content.
* @param WP_Block $block The block object.
*
* @return string
*/
function get_column( $attributes, $content, $block ) {
// Bail if in the editor.
if ( is_admin() ) {
return;
}
// Build default atts.
$style = [];
$atts = [
'class' => 'mai-column',
];
// Justify content is align items value since flex-direction is column.
if ( isset( $attributes['alignItems'] ) ) {
$style[] = isset( $attributes['alignItems'] ) ? sprintf( '--justify-content:%s;', $this->get_flex_css_value( $attributes['alignItems'] ) ) : 'initial';
}
// Add inline styles.
if ( $style ) {
$atts['style'] = implode( '', $style );
}
// Get attributes with custom class first, and replace `wp-block-` with an emtpy string.
$attr = get_block_wrapper_attributes( $atts );
$attr = str_replace( ' wp-block-mai-column', '', $attr );
return sprintf( '<div %s>%s</div>', trim( $attr ), $content );
}
/**
* Get the flex CSS value.
*
* @since 0.1.0
*
* @return string
*/
function get_flex_css_value( $value ) {
switch ( $value ) {
case 'top':
case 'left':
return 'flex-start';
case 'middle':
case 'center':
return 'center';
case 'bottom':
case 'right':
return 'flex-end';
case 'space-between':
return 'space-between';
default:
return 'initial';
}
}
/**
* Converts blockGap values to CSS value.
*
* @since 0.1.0
*
* @param string|array $gap The blockGap value.
*
* @return string
*/
function get_block_gap( $gap ) {
$return = [
'row' => 'initial',
'column' => 'initial',
];
if ( is_array( $gap ) ) {
foreach ( $gap as $position => $value ) {
switch ( $position ) {
case 'top':
case 'bottom':
$return['row'] = $this->get_block_gap_value( $value );
break;
case 'left':
case 'right':
$return['column'] = $this->get_block_gap_value( $value );
break;
}
}
} else {
$value = $this->get_block_gap_value( $gap );
if ( $value ) {
$return['row'] = $value;
$return['column'] = $value;
}
}
return $return;
}
/**
* Gets the CSS value from the blockGap value.
*
* @since 0.1.0
*
* @param string $gap The blockGap value.
*
* @return string
*/
function get_block_gap_value( $gap ) {
$array = explode( '|', $gap );
$last = array_pop( $array );
return count( $array ) > 1 ? sprintf( 'var(--wp--preset--spacing--%s)', $last ) : $last;
}
/**
* Gets flex value from column size.
*
* @since 0.1.0
*
* @param string $size The size value from settings.
*
* @return string
*/
function get_flex( $size ) {
if ( ! $size ) {
return '1';
}
switch ( $size ) {
// No longer using 'auto', as this is the "empty" default, same as '1'.
// case 'auto':
// return '0 1 0%';
case 'fit':
return '0 1 auto';
case 'fill':
return '1 0 0';
}
return '0 1 var(--flex-basis)';
}
/**
* Gets the correct column value from the repeated arrangement array.
* Alternate, but slower, versions below.
*
* // Slower.
* $array = array_merge(...array_fill( 0, $index, $array ));
* return $array[ $index ] ?? $default;
*
* // Slowest.
* $array = [];
* for ( $i = 0; $i < ( $index + 1) / count( $pattern ); $i++ ) {
* $array = array_merge( $array, $pattern );
* }
* return $array[ $index ] ?? $default;
*
* @since 0.1.0
*
* @param int $index The current item index to get the value for.
* @param array $array The array to get index value from.
* @param mixed $default The default value if there is no index.
*
* @return mixed
*/
function get_index_value_from_array( $index, $array, $default = null ) {
// If index is already available, return it.
if ( isset( $array[ $index ] ) ) {
return $array[ $index ];
}
// If only 1 item in array, return the first.
if ( 1 === count( $array ) ) {
return reset( $array );
}
return $array[ $index % count( $array ) ] ?? $default;
}
/**
* Gets the fraction value from a given value.
*
* @param string $value
*
* @return string
*/
function get_fraction( $value ) {
if ( ! $value ) {
return false;
}
if ( in_array( $value, [ 'auto', 'fit', 'fill' ] ) ) {
return false;
}
if ( $this->is_fraction( $value ) ) {
return $value;
}
// If not a fraction, it's a percentage. Convert to fraction and reduce.
$percentage = floatval( str_replace( '%', '', $value ) );
$decimalValue = $percentage / 100;
$numerator = intval( round( $decimalValue * 100 ) );
$denominator = 100;
$gcd = $this->get_gcd( $numerator, $denominator );
return sprintf( '%s/%s', $numerator / $gcd, $denominator / $gcd);
}
/**
* Gets the greatest common denominator.
*
* @since 0.1.0
*
* @param int $a
* @param int $b
*
* @return int
*/
function get_gcd( $a, $b ) {
if ( 0 === $b ) {
return $a;
}
return $this->get_gcd( $b, $a % $b );
}
/**
* Checks if a value is a fraction.
*
* @since 0.1.0
*
* @param string $value
*
* @return bool
*/
function is_fraction( $value ) {
return preg_match( '/^\\d+\\/\\d+$/', $value );
}
/**
* Gets DOMDocument object.
*
* @since 0.1.0
*
* @param string $html Any given HTML string.
*
* @return DOMDocument
*/
function get_dom_document( $html ) {
// Create the new document.
$dom = new DOMDocument();
// Modify state.
$libxml_previous_state = libxml_use_internal_errors( true );
// Encode.
$html = mb_convert_encoding( $html, 'HTML-ENTITIES', 'UTF-8' );
// Load the content in the document HTML.
$dom->loadHTML( "<div>$html</div>" );
// Handle wraps.
$container = $dom->getElementsByTagName('div')->item(0);
$container = $container->parentNode->removeChild( $container );
while ( $dom->firstChild ) {
$dom->removeChild( $dom->firstChild );
}
while ( $container->firstChild ) {
$dom->appendChild( $container->firstChild );
}
// Handle errors.
libxml_clear_errors();
// Restore.
libxml_use_internal_errors( $libxml_previous_state );
return $dom;
}
}