Completed
Push — develop ( 0e7798...ecb6cb )
by Aristeides
02:24
created

Kirki_Control_Repeater::enqueue()   C

Complexity

Conditions 7
Paths 2

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 2
nop 0
dl 0
loc 25
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/**
3
 * Customizer Control: repeater.
4
 *
5
 * @package     Kirki
6
 * @subpackage  Controls
7
 * @copyright   Copyright (c) 2016, Aristeides Stathopoulos
8
 * @license     http://opensource.org/licenses/https://opensource.org/licenses/MIT
9
 * @since       2.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Repeater control
19
 */
20
class Kirki_Control_Repeater extends WP_Customize_Control {
21
22
	/**
23
	 * The control type.
24
	 *
25
	 * @access public
26
	 * @var string
27
	 */
28
	public $type = 'repeater';
29
30
	/**
31
	 * Used to automatically generate all CSS output.
32
	 *
33
	 * @access public
34
	 * @var array
35
	 */
36
	public $output = array();
37
38
	/**
39
	 * Data type
40
	 *
41
	 * @access public
42
	 * @var string
43
	 */
44
	public $option_type = 'theme_mod';
45
46
	/**
47
	 * The kirki_config we're using for this control
48
	 *
49
	 * @access public
50
	 * @var string
51
	 */
52
	public $kirki_config = 'global';
53
54
	/**
55
	 * The fields that each container row will contain.
56
	 *
57
	 * @access public
58
	 * @var array
59
	 */
60
	public $fields = array();
61
62
	/**
63
	 * Will store a filtered version of value for advenced fields (like images).
64
	 *
65
	 * @access protected
66
	 * @var array
67
	 */
68
	protected $filtered_value = array();
69
70
	/**
71
	 * The row label
72
	 *
73
	 * @access public
74
	 * @var array
75
	 */
76
	public $row_label = array();
77
78
	/**
79
	 * Constructor.
80
	 * Supplied `$args` override class property defaults.
81
	 * If `$args['settings']` is not defined, use the $id as the setting ID.
82
	 *
83
	 * @param WP_Customize_Manager $manager Customizer bootstrap instance.
84
	 * @param string               $id      Control ID.
85
	 * @param array                $args    {@see WP_Customize_Control::__construct}.
86
	 */
87
	public function __construct( $manager, $id, $args = array() ) {
88
89
		parent::__construct( $manager, $id, $args );
90
91
		// Set up defaults for row labels.
92
		$this->row_label = array(
93
			'type' => 'text',
94
			'value' => $this->l10n( 'row' ),
95
			'field' => false,
96
		);
97
98
		// Validate row-labels.
99
		$this->row_label( $args );
100
101
		if ( empty( $this->button_label ) ) {
102
			$this->button_label = $this->l10n( 'add-new' ) . ' ' . $this->row_label['value'];
103
		}
104
105
		if ( empty( $args['fields'] ) || ! is_array( $args['fields'] ) ) {
106
			$args['fields'] = array();
107
		}
108
109
		// An array to store keys of fields that need to be filtered.
110
		$media_fields_to_filter = array();
111
112
		foreach ( $args['fields'] as $key => $value ) {
113
			if ( ! isset( $value['default'] ) ) {
114
				$args['fields'][ $key ]['default'] = '';
115
			}
116
			if ( ! isset( $value['label'] ) ) {
117
				$args['fields'][ $key ]['label'] = '';
118
			}
119
			$args['fields'][ $key ]['id']      = $key;
120
121
			// We check if the filed is an uploaded media ( image , file, video, etc.. ).
122
			if ( isset( $value['type'] ) ) {
123
				switch ( $value['type'] ) {
124
					case 'image':
125
					case 'cropped_image':
126
					case 'upload':
127
						// We add it to the list of fields that need some extra filtering/processing.
128
						$media_fields_to_filter[ $key ] = true;
129
						break;
130
131
					case 'dropdown-pages':
132
						// If the field is a dropdown-pages field then add it to args.
133
						$dropdown = wp_dropdown_pages(
134
							array(
135
								'name'              => '',
136
								'echo'              => 0,
137
								'show_option_none'  => esc_attr( $this->l10n( 'select-page' ) ),
138
								'option_none_value' => '0',
139
								'selected'          => '',
140
							)
141
						);
142
						// Hackily add in the data link parameter.
143
						$dropdown = str_replace( '<select', '<select data-field="' . esc_attr( $args['fields'][ $key ]['id'] ) . '"' . $this->get_link(), $dropdown );
144
						$args['fields'][ $key ]['dropdown'] = $dropdown;
145
						break;
146
				}
147
			}
148
		} // End foreach().
149
150
		$this->fields = $args['fields'];
151
152
		// Now we are going to filter the fields.
153
		// First we create a copy of the value that would be used otherwise.
154
		$this->filtered_value = $this->value();
155
156
		if ( is_array( $this->filtered_value ) && ! empty( $this->filtered_value ) ) {
157
158
			// We iterate over the list of fields.
159
			foreach ( $this->filtered_value as &$filtered_value_field ) {
160
161
				if ( is_array( $filtered_value_field ) && ! empty( $filtered_value_field ) ) {
162
163
					// We iterate over the list of properties for this field.
164
					foreach ( $filtered_value_field as $key => &$value ) {
165
166
						// We check if this field was marked as requiring extra filtering (in this case image, cropped_images, upload).
167
						if ( array_key_exists( $key, $media_fields_to_filter ) ) {
168
169
							// What follows was made this way to preserve backward compatibility.
170
							// The repeater control use to store the URL for images instead of the attachment ID.
171
							// We check if the value look like an ID (otherwise it's probably a URL so don't filter it).
172
							if ( is_numeric( $value ) ) {
173
174
								// "sanitize" the value.
175
								$attachment_id = (int) $value;
176
177
								// Try to get the attachment_url.
178
								$url = wp_get_attachment_url( $attachment_id );
179
180
								$filename = basename( get_attached_file( $attachment_id ) );
181
182
								// If we got a URL.
183
								if ( $url ) {
184
185
									// 'id' is needed for form hidden value, URL is needed to display the image.
186
									$value = array(
187
										'id'  => $attachment_id,
188
										'url' => $url,
189
										'filename' => $filename,
190
									);
191
								}
192
							}
193
						}
194
					}
195
				}
196
			} // End foreach().
197
		} // End if().
198
	}
199
200
	/**
201
	 * Refresh the parameters passed to the JavaScript via JSON.
202
	 *
203
	 * @access public
204
	 */
205
	public function to_json() {
206
		parent::to_json();
207
208
		$this->json['default'] = ( isset( $this->default ) ) ? $this->default : $this->setting->default;
209
		$this->json['output']  = $this->output;
210
		$this->json['value']   = $this->value();
211
		$this->json['choices'] = $this->choices;
212
		$this->json['link']    = $this->get_link();
213
		$this->json['id']      = $this->id;
214
215
		if ( 'user_meta' === $this->option_type ) {
216
			$this->json['value'] = get_user_meta( get_current_user_id(), $this->id, true );
217
		}
218
219
		$this->json['inputAttrs'] = '';
220
		foreach ( $this->input_attrs as $attr => $value ) {
221
			$this->json['inputAttrs'] .= $attr . '="' . esc_attr( $value ) . '" ';
222
		}
223
224
		$fields = $this->fields;
225
226
		$this->json['fields'] = $fields;
227
		$this->json['row_label'] = $this->row_label;
228
229
		// If filtered_value has been set and is not empty we use it instead of the actual value.
230
		if ( is_array( $this->filtered_value ) && ! empty( $this->filtered_value ) ) {
231
			$this->json['value'] = $this->filtered_value;
232
		}
233
	}
234
235
	/**
236
	 * Enqueue control related scripts/styles.
237
	 *
238
	 * @access public
239
	 */
240
	public function enqueue() {
241
242
		// If we have a color picker field we need to enqueue the Wordpress Color Picker style and script.
243
		if ( is_array( $this->fields ) && ! empty( $this->fields ) ) {
244
			foreach ( $this->fields as $field ) {
245
				if ( isset( $field['type'] ) ) {
246
247
					// Some field-types require extra scripts.
248
					switch ( $field['type'] ) {
249
						case 'color':
250
							wp_enqueue_script( 'wp-color-picker' );
251
							wp_enqueue_style( 'wp-color-picker' );
252
							break;
253
						case 'select':
254
							wp_enqueue_script( 'select2', trailingslashit( Kirki::$url ) . 'controls/repeater/select2/js/select2.full.js', array( 'jquery' ), false, true );
255
							wp_enqueue_style( 'select2', trailingslashit( Kirki::$url ) . 'controls/repeater/select2/css/select2.min.css', null );
256
							break;
257
					}
258
				}
259
			}
260
		}
261
262
		wp_enqueue_script( 'kirki-repeater', trailingslashit( Kirki::$url ) . 'controls/repeater/repeater.js', array( 'jquery', 'customize-base', 'jquery-ui-core', 'jquery-ui-sortable' ), false, true );
263
		wp_enqueue_style( 'kirki-repeater-css', trailingslashit( Kirki::$url ) . 'controls/repeater/repeater.css', null );
264
	}
265
266
	/**
267
	 * Render the control's content.
268
	 * Allows the content to be overriden without having to rewrite the wrapper in $this->render().
269
	 *
270
	 * @access protected
271
	 */
272
	protected function render_content() {
273
		?>
274
		<label>
275
			<?php if ( ! empty( $this->label ) ) : ?>
276
				<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
277
			<?php endif; ?>
278
			<?php if ( ! empty( $this->description ) ) : ?>
279
				<span class="description customize-control-description"><?php echo wp_kses_post( $this->description ); ?></span>
280
			<?php endif; ?>
281
			<input type="hidden" {{{ data.inputAttrs }}} value="" <?php echo wp_kses_post( $this->get_link() ); ?> />
282
		</label>
283
284
		<ul class="repeater-fields"></ul>
285
286
		<?php if ( isset( $this->choices['limit'] ) ) : ?>
287
			<p class="limit"><?php printf( esc_html( $this->l10n( 'limit-rows' ) ), esc_html( $this->choices['limit'] ) ); ?></p>
288
		<?php endif; ?>
289
		<button class="button-secondary repeater-add"><?php echo esc_html( $this->button_label ); ?></button>
290
291
		<?php
292
293
		$this->repeater_js_template();
294
295
	}
296
297
	/**
298
	 * An Underscore (JS) template for this control's content (but not its container).
299
	 * Class variables for this control class are available in the `data` JS object.
300
	 *
301
	 * @access public
302
	 */
303
	public function repeater_js_template() {
304
		?>
305
		<script type="text/html" class="customize-control-repeater-content">
306
			<# var field; var index = data.index; #>
307
308
			<li class="repeater-row minimized" data-row="{{{ index }}}">
309
310
				<div class="repeater-row-header">
311
					<span class="repeater-row-label"></span>
312
					<i class="dashicons dashicons-arrow-down repeater-minimize"></i>
313
				</div>
314
				<div class="repeater-row-content">
315
					<# _.each( data, function( field, i ) { #>
316
317
						<div class="repeater-field repeater-field-{{{ field.type }}}">
318
319
							<# if ( 'text' === field.type || 'url' === field.type || 'link' === field.type || 'email' === field.type || 'tel' === field.type || 'date' === field.type ) { #>
320
321
								<# if ( 'link' === field.type ) { #>
322
									<# field.type = 'url' #>
323
								<# } #>
324
325
								<label>
326
									<# if ( field.label ) { #>
327
										<span class="customize-control-title">{{ field.label }}</span>
328
									<# } #>
329
									<# if ( field.description ) { #>
330
										<span class="description customize-control-description">{{ field.description }}</span>
331
									<# } #>
332
									<input type="{{field.type}}" name="" value="{{{ field.default }}}" data-field="{{{ field.id }}}">
333
								</label>
334
335
							<# } else if ( 'hidden' === field.type ) { #>
336
337
								<input type="hidden" data-field="{{{ field.id }}}" <# if ( field.default ) { #> value="{{{ field.default }}}" <# } #> />
338
339
							<# } else if ( 'checkbox' === field.type ) { #>
340
341
								<label>
342
									<input type="checkbox" value="true" data-field="{{{ field.id }}}" <# if ( field.default ) { #> checked="checked" <# } #> /> {{ field.label }}
343
									<# if ( field.description ) { #>
344
										{{ field.description }}
345
									<# } #>
346
								</label>
347
348
							<# } else if ( 'select' === field.type ) { #>
349
350
								<label>
351
									<# if ( field.label ) { #>
352
										<span class="customize-control-title">{{ field.label }}</span>
353
									<# } #>
354
									<# if ( field.description ) { #>
355
										<span class="description customize-control-description">{{ field.description }}</span>
356
									<# } #>
357
									<select data-field="{{{ field.id }}}"<# if ( 'undefined' !== field.multiple && false !== field.multiple ) { #> multiple="multiple"<# } #>>
358
										<# _.each( field.choices, function( choice, i ) { #>
359
											<option value="{{{ i }}}" <# if ( field.default == i ) { #> selected="selected" <# } #>>{{ choice }}</option>
360
										<# }); #>
361
									</select>
362
								</label>
363
364
							<# } else if ( 'dropdown-pages' === field.type ) { #>
365
366
								<label>
367
									<# if ( field.label ) { #>
368
										<span class="customize-control-title">{{{ data.label }}}</span>
369
									<# } #>
370
									<# if ( field.description ) { #>
371
										<span class="description customize-control-description">{{{ field.description }}}</span>
372
									<# } #>
373
									<div class="customize-control-content repeater-dropdown-pages">{{{ field.dropdown }}}</div>
374
								</label>
375
376
							<# } else if ( 'radio' === field.type ) { #>
377
378
								<label>
379
									<# if ( field.label ) { #>
380
										<span class="customize-control-title">{{ field.label }}</span>
381
									<# } #>
382
									<# if ( field.description ) { #>
383
										<span class="description customize-control-description">{{ field.description }}</span>
384
									<# } #>
385
386
									<# _.each( field.choices, function( choice, i ) { #>
387
										<label>
388
											<input type="radio" name="{{{ field.id }}}{{ index }}" data-field="{{{ field.id }}}" value="{{{ i }}}" <# if ( field.default == i ) { #> checked="checked" <# } #>> {{ choice }} <br/>
389
										</label>
390
									<# }); #>
391
								</label>
392
393
							<# } else if ( 'radio-image' === field.type ) { #>
394
395
								<label>
396
									<# if ( field.label ) { #>
397
										<span class="customize-control-title">{{ field.label }}</span>
398
									<# } #>
399
									<# if ( field.description ) { #>
400
										<span class="description customize-control-description">{{ field.description }}</span>
401
									<# } #>
402
403
									<# _.each( field.choices, function( choice, i ) { #>
404
										<input type="radio" id="{{{ field.id }}}_{{ index }}_{{{ i }}}" name="{{{ field.id }}}{{ index }}" data-field="{{{ field.id }}}" value="{{{ i }}}" <# if ( field.default == i ) { #> checked="checked" <# } #>>
405
											<label for="{{{ field.id }}}_{{ index }}_{{{ i }}}">
406
												<img src="{{ choice }}">
407
											</label>
408
										</input>
409
									<# }); #>
410
								</label>
411
412
							<# } else if ( 'color' === field.type ) { #>
413
414
								<# var defaultValue = '';
415
						        if ( field.default ) {
416
						            if ( '#' !== field.default.substring( 0, 1 ) ) {
417
						                defaultValue = '#' + field.default;
418
						            } else {
419
						                defaultValue = field.default;
420
						            }
421
						            defaultValue = ' data-default-color=' + defaultValue; // Quotes added automatically.
422
						        } #>
423
						        <label>
424
						            <# if ( field.label ) { #>
425
						                <span class="customize-control-title">{{{ field.label }}}</span>
426
						            <# } #>
427
						            <# if ( field.description ) { #>
428
						                <span class="description customize-control-description">{{{ field.description }}}</span>
429
						            <# } #>
430
						            <input class="color-picker-hex" type="text" maxlength="7" placeholder="<?php echo esc_attr( $this->l10n( 'hex-value' ) ); ?>"  value="{{{ field.default }}}" data-field="{{{ field.id }}}" {{ defaultValue }} />
431
432
						        </label>
433
434
							<# } else if ( 'textarea' === field.type ) { #>
435
436
								<# if ( field.label ) { #>
437
									<span class="customize-control-title">{{ field.label }}</span>
438
								<# } #>
439
								<# if ( field.description ) { #>
440
									<span class="description customize-control-description">{{ field.description }}</span>
441
								<# } #>
442
								<textarea rows="5" data-field="{{{ field.id }}}">{{ field.default }}</textarea>
443
444
							<# } else if ( field.type === 'image' || field.type === 'cropped_image' ) { #>
445
446
								<label>
447
									<# if ( field.label ) { #>
448
										<span class="customize-control-title">{{ field.label }}</span>
449
									<# } #>
450
									<# if ( field.description ) { #>
451
										<span class="description customize-control-description">{{ field.description }}</span>
452
									<# } #>
453
								</label>
454
455
								<figure class="kirki-image-attachment" data-placeholder="<?php echo esc_attr( $this->l10n( 'no-image-selected' ) ); ?>" >
456
									<# if ( field.default ) { #>
457
										<# var defaultImageURL = ( field.default.url ) ? field.default.url : field.default; #>
458
										<img src="{{{ defaultImageURL }}}">
459
									<# } else { #>
460
										<?php echo esc_attr( $this->l10n( 'no-image-selected' ) ); ?>
461
									<# } #>
462
								</figure>
463
464
								<div class="actions">
465
									<button type="button" class="button remove-button<# if ( ! field.default ) { #> hidden<# } #>"><?php echo esc_attr( $this->l10n( 'remove' ) ); ?></button>
466
									<button type="button" class="button upload-button" data-label=" <?php echo esc_attr( $this->l10n( 'add-image' ) ); ?>" data-alt-label="<?php echo esc_attr( $this->l10n( 'change-image' ) ); ?>" >
467
										<# if ( field.default ) { #>
468
											<?php echo esc_attr( $this->l10n( 'change-image' ) ); ?>
469
										<# } else { #>
470
											<?php echo esc_attr( $this->l10n( 'add-image' ) ); ?>
471
										<# } #>
472
									</button>
473
									<# if ( field.default.id ) { #>
474
										<input type="hidden" class="hidden-field" value="{{{ field.default.id }}}" data-field="{{{ field.id }}}" >
475
									<# } else { #>
476
										<input type="hidden" class="hidden-field" value="{{{ field.default }}}" data-field="{{{ field.id }}}" >
477
									<# } #>
478
								</div>
479
480
							<# } else if ( field.type === 'upload' ) { #>
481
482
								<label>
483
									<# if ( field.label ) { #>
484
										<span class="customize-control-title">{{ field.label }}</span>
485
									<# } #>
486
									<# if ( field.description ) { #>
487
										<span class="description customize-control-description">{{ field.description }}</span>
488
									<# } #>
489
								</label>
490
491
								<figure class="kirki-file-attachment" data-placeholder="<?php echo esc_attr( $this->l10n( 'no-file-selected' ) ); ?>" >
492
									<# if ( field.default ) { #>
493
										<# var defaultFilename = ( field.default.filename ) ? field.default.filename : field.default; #>
494
										<span class="file"><span class="dashicons dashicons-media-default"></span> {{ defaultFilename }}</span>
495
									<# } else { #>
496
										<?php echo esc_attr( $this->l10n( 'no-file-selected' ) ); ?>
497
									<# } #>
498
								</figure>
499
500
								<div class="actions">
501
									<button type="button" class="button remove-button<# if ( ! field.default ) { #> hidden<# } #>"></button>
502
									<button type="button" class="button upload-button" data-label="<?php echo esc_attr( $this->l10n( 'add-file' ) ); ?>" data-alt-label="<?php echo esc_attr( $this->l10n( 'change-file' ) ); ?>" >
503
										<# if ( field.default ) { #>
504
											<?php echo esc_attr( $this->l10n( 'change-file' ) ); ?>
505
										<# } else { #>
506
											<?php echo esc_attr( $this->l10n( 'add-file' ) ); ?>
507
										<# } #>
508
									</button>
509
									<# if ( field.default.id ) { #>
510
										<input type="hidden" class="hidden-field" value="{{{ field.default.id }}}" data-field="{{{ field.id }}}" >
511
									<# } else { #>
512
										<input type="hidden" class="hidden-field" value="{{{ field.default }}}" data-field="{{{ field.id }}}" >
513
									<# } #>
514
								</div>
515
516
							<# } else if ( 'custom' === field.type ) { #>
517
518
								<# if ( field.label ) { #>
519
									<span class="customize-control-title">{{ field.label }}</span>
520
								<# } #>
521
								<# if ( field.description ) { #>
522
									<span class="description customize-control-description">{{ field.description }}</span>
523
								<# } #>
524
								<div data-field="{{{ field.id }}}">{{{ field.default }}}</div>
525
526
							<# } #>
527
528
						</div>
529
					<# }); #>
530
					<button type="button" class="button-link repeater-row-remove"><?php echo esc_attr( $this->l10n( 'remove' ) ); ?></button>
531
				</div>
532
			</li>
533
		</script>
534
		<?php
535
	}
536
537
	/**
538
	 * Validate row-labels.
539
	 *
540
	 * @access protected
541
	 * @since 3.0.0
542
	 * @param array $args {@see WP_Customize_Control::__construct}.
543
	 */
544
	protected function row_label( $args ) {
545
546
		// Validating args for row labels.
547
		if ( isset( $args['row_label'] ) && is_array( $args['row_label'] ) && ! empty( $args['row_label'] ) ) {
548
549
			// Validating row label type.
550
			if ( isset( $args['row_label']['type'] ) && ( 'text' === $args['row_label']['type'] || 'field' === $args['row_label']['type'] ) ) {
551
				$this->row_label['type'] = $args['row_label']['type'];
552
			}
553
554
			// Validating row label type.
555
			if ( isset( $args['row_label']['value'] ) && ! empty( $args['row_label']['value'] ) ) {
556
				$this->row_label['value'] = esc_attr( $args['row_label']['value'] );
557
			}
558
559
			// Validating row label field.
560
			if ( isset( $args['row_label']['field'] ) && ! empty( $args['row_label']['field'] ) && isset( $args['fields'][ esc_attr( $args['row_label']['field'] ) ] ) ) {
561
				$this->row_label['field'] = esc_attr( $args['row_label']['field'] );
562
			} else {
563
				// If from field is not set correctly, making sure standard is set as the type.
564
				$this->row_label['type'] = 'text';
565
			}
566
		}
567
	}
568
569
	/**
570
	 * Returns an array of translation strings.
571
	 *
572
	 * @access protected
573
	 * @since 3.0.0
574
	 * @param string|false $id The string-ID.
575
	 * @return string
576
	 */
577
	protected function l10n( $id = false ) {
578
		$translation_strings = array(
579
			'row'               => esc_attr__( 'row', 'kirki' ),
580
			'add-new'           => esc_attr__( 'Add new', 'kirki' ),
581
			'select-page'       => esc_attr__( 'Select a Page', 'kirki' ),
582
			/* translators: %s represents the number of rows we're limiting the repeater to allow. */
583
			'limit-rows'        => esc_attr__( 'Limit: %s rows', 'kirki' ),
584
			'hex-value'         => esc_attr__( 'Hex Value', 'kirki' ),
585
			'no-image-selected' => esc_attr__( 'No Image Selected', 'kirki' ),
586
			'remove'            => esc_attr__( 'Remove', 'kirki' ),
587
			'add-image'         => esc_attr__( 'Add Image', 'kirki' ),
588
			'change-image'      => esc_attr__( 'Change Image', 'kirki' ),
589
			'no-file-selected'  => esc_attr__( 'No File Selected', 'kirki' ),
590
			'add-file'          => esc_attr__( 'Add File', 'kirki' ),
591
			'change-file'       => esc_attr__( 'Change File', 'kirki' ),
592
		);
593
		$translation_strings = apply_filters( 'kirki/' . $this->kirki_config . '/l10n', $translation_strings );
594
		if ( false === $id ) {
595
			return $translation_strings;
596
		}
597
		return $translation_strings[ $id ];
598
	}
599
}
600