Completed
Push — develop ( 2d809e...4b580b )
by Aristeides
03:12
created

Kirki_Modules_PostMessage::script_html_var()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * Automatic postMessage scripts calculation for Kirki controls.
4
 *
5
 * @package     Kirki
6
 * @category    Modules
7
 * @author      Aristeides Stathopoulos
8
 * @copyright   Copyright (c) 2017, Aristeides Stathopoulos
9
 * @license     http://opensource.org/licenses/https://opensource.org/licenses/MIT
10
 * @since       3.0.0
11
 */
12
13
// Exit if accessed directly.
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * Adds styles to the customizer.
20
 */
21
class Kirki_Modules_PostMessage {
22
	/**
23
	 * The object instance.
24
	 *
25
	 * @static
26
	 * @access private
27
	 * @since 3.0.0
28
	 * @var object
29
	 */
30
	private static $instance;
31
32
	/**
33
	 * The script.
34
	 *
35
	 * @access protected
36
	 * @since 3.0.0
37
	 * @var string
38
	 */
39
	protected $script = '';
40
41
	/**
42
	 * Constructor.
43
	 *
44
	 * @access protected
45
	 * @since 3.0.0
46
	 */
47
	protected function __construct() {
48
		add_action( 'customize_preview_init', array( $this, 'postmessage' ) );
49
	}
50
51
	/**
52
	 * Gets an instance of this object.
53
	 * Prevents duplicate instances which avoid artefacts and improves performance.
54
	 *
55
	 * @static
56
	 * @access public
57
	 * @since 3.0.0
58
	 * @return object
59
	 */
60
	public static function get_instance() {
61
		if ( ! self::$instance ) {
62
			self::$instance = new self();
63
		}
64
		return self::$instance;
65
	}
66
67
	/**
68
	 * Enqueues the postMessage script
69
	 * and adds variables to it using the wp_localize_script function.
70
	 * The rest is handled via JS.
71
	 */
72
	public function postmessage() {
73
74
		wp_enqueue_script( 'kirki_auto_postmessage', trailingslashit( Kirki::$url ) . 'modules/postmessage/postmessage.js', array( 'jquery', 'customize-preview' ), false, true );
75
		$fields = Kirki::$fields;
76
		foreach ( $fields as $field ) {
77
			if ( isset( $field['transport'] ) && 'postMessage' === $field['transport'] && isset( $field['js_vars'] ) && ! empty( $field['js_vars'] ) && is_array( $field['js_vars'] ) && isset( $field['settings'] ) ) {
78
				$this->script .= $this->script( $field );
79
			}
80
		}
81
		$this->script = apply_filters( 'kirki/postmessage/script', $this->script );
82
		wp_add_inline_script( 'kirki_auto_postmessage', $this->script, 'after' );
83
84
	}
85
86
	/**
87
	 * Generates script for a single field.
88
	 *
89
	 * @access protected
90
	 * @since 3.0.0
91
	 * @param array $args The arguments.
92
	 */
93
	protected function script( $args ) {
94
95
		$script = 'wp.customize(\'' . $args['settings'] . '\',function(value){value.bind(function(newval){';
96
		// append unique style tag if not exist
97
		// The style ID.
98
		$style_id = 'kirki-postmessage-' . str_replace( array( '[', ']' ), '', $args['settings'] );
99
		$script .= 'if(null===document.getElementById(\'' . $style_id . '\')||\'undefined\'===typeof document.getElementById(\'' . $style_id . '\')){jQuery(\'head\').append(\'<style id="' . $style_id . '"></style>\');}';
100
101
		// Add anything we need before the main script.
102
		$script .= $this->before_script( $args );
103
104
		$field = array(
105
			'scripts' => array(),
106
		);
107
		// Loop through the js_vars and generate the script.
108
		foreach ( $args['js_vars'] as $key => $js_var ) {
109
			if ( isset( $js_var['function'] ) && 'html' === $js_var['function'] ) {
110
				$script .= $this->script_html_var( $js_var );
111
				continue;
112
			}
113
			$js_var['index_key'] = $key;
114
			$callback = $this->get_callback( $args );
115
			if ( is_callable( $callback ) ) {
116
				$field['scripts'][ $key ] = call_user_func_array( $callback, array( $js_var, $args ) );
117
				continue;
118
			}
119
			$field['scripts'][ $key ] = $this->script_var( $js_var );
120
		}
121
		$combo_extra_script = '';
122
		$combo_css_script   = '';
123
		foreach ( $field['scripts'] as $script_array ) {
124
			$combo_extra_script .= $script_array['script'];
125
			$combo_css_script   .= ( 'css' !== $combo_css_script ) ? $script_array['css'] : '';
126
		}
127
		$text = ( 'css' === $combo_css_script ) ? 'css' : '\'' . $combo_css_script . '\'';
128
		$script .= $combo_extra_script . 'jQuery(\'#' . $style_id . '\').text(' . $text . ');';
129
		$script .= 'jQuery(\'#' . $style_id . '\').appendTo(\'head\');';
130
		$script .= '});});';
131
		return $script;
132
	}
133
134
	/**
135
	 * Generates script for a single js_var when using "html" as function.
136
	 *
137
	 * @access protected
138
	 * @since 3.0.0
139
	 * @param array $args  The arguments for this js_var.
140
	 */
141
	protected function script_html_var( $args ) {
142
143
		$script  = ( isset( $args['choice'] ) ) ? 'newval=newval[\'' . $args['choice'] . '\'];' : '';
144
		$script .= 'jQuery(\'' . $args['element'] . '\').html(newval);';
145
		if ( isset( $args['attr'] ) ) {
146
			$script = 'jQuery(\'' . $args['element'] . '\').attr(\'' . $args['attr'] . '\',newval);';
147
		}
148
		return $script;
149
	}
150
151
	/**
152
	 * Generates script for a single js_var.
153
	 *
154
	 * @access protected
155
	 * @since 3.0.0
156
	 * @param array $args  The arguments for this js_var.
157
	 */
158
	protected function script_var( $args ) {
159
		$script = '';
160
		$property_script = '';
161
162
		$value_key = 'newval' . $args['index_key'];
163
		$property_script .= $value_key . '=newval;';
164
165
		$args = $this->get_args( $args );
166
167
		// Apply callback to the value if a callback is defined.
168
		if ( ! empty( $args['js_callback'][0] ) ) {
169
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
170
		}
171
172
		// Apply the value_pattern.
173
		if ( '' !== $args['value_pattern'] ) {
174
			$script .= $this->value_pattern_replacements( $value_key, $args );
175
		}
176
177
		// Tweak to add url() for background-images.
178
		if ( 'background-image' === $args['property'] && ( ! isset( $args['value_pattern'] ) || false === strpos( $args['value_pattern'], 'gradient' ) ) ) {
179
			$script .= 'if(-1===' . $value_key . '.indexOf(\'url(\')){' . $value_key . '=\'url("\'+' . $value_key . '+\'");}';
180
		}
181
182
		// Apply prefix.
183
		$value = $value_key;
184
		if ( '' !== $args['prefix'] ) {
185
			$value = $args['prefix'] . '+' . $value_key;
186
		}
187
		$css = $args['element'] . '{' . $args['property'] . ':\'+' . $value . '+\'' . $args['units'] . $args['suffix'] . ';}';
188
		if ( isset( $args['media_query'] ) ) {
189
			$css = $args['media_query'] . '{' . $css . '}';
190
		}
191
		return array(
192
			'script' => $property_script . $script,
193
			'css'    => $css,
194
		);
195
	}
196
197
	/**
198
	 * Processes script generation for fields that save an array.
199
	 *
200
	 * @access protected
201
	 * @since 3.0.0
202
	 * @param array $args  The arguments for this js_var.
203
	 */
204
	protected function script_var_array( $args ) {
205
206
		$script = 'css=\'\';';
207
		$property_script = '';
208
209
		// Define choice.
210
		$choice  = ( isset( $args['choice'] ) && '' !== $args['choice'] ) ? $args['choice'] : '';
211
		$script .= ( '' !== $choice ) ? 'choice=\'' . $choice . '\';' : '';
212
213
		$value_key = 'newval' . $args['index_key'];
214
		$property_script .= $value_key . '=newval;';
215
216
		$args = $this->get_args( $args );
217
218
		// Apply callback to the value if a callback is defined.
219
		if ( ! empty( $args['js_callback'][0] ) ) {
220
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
221
		}
222
		$script .= '_.each(' . $value_key . ', function(subValue,subKey){';
223
224
		// Apply the value_pattern.
225
		if ( '' !== $args['value_pattern'] ) {
226
			$script .= $this->value_pattern_replacements( 'subValue', $args );
227
		}
228
229
		// Tweak to add url() for background-images.
230
		if ( '' === $choice || 'background-image' === $choice ) {
231
			$script .= 'if(\'background-image\'===\'' . $args['property'] . '\'||\'background-image\'===subKey){';
232
			$script .= 'if(-1===subValue.indexOf(\'url(\')){subValue=\'url("\'+subValue+\'")\';}';
233
			$script .= '}';
234
		}
235
236
		// Apply prefix.
237
		$value = $value_key;
238
		if ( '' !== $args['prefix'] ) {
239
			$value = '\'' . $args['prefix'] . '\'+subValue';
240
		}
241
242
		// Mostly used for padding, margin & position properties.
243
		$direction_script  = 'if(_.contains([\'top\',\'bottom\',\'left\',\'right\'],subKey)){';
244
		$direction_script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . '-\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';}';
245
		// Allows us to apply this just for a specific choice in the array of the values.
246
		if ( '' !== $choice ) {
247
			$choice_is_direction = ( false !== strpos( $choice, 'top' ) || false !== strpos( $choice, 'bottom' ) || false !== strpos( $choice, 'left' ) || false !== strpos( $choice, 'right' ) );
248
			$script .= 'choice=\'' . $choice . '\';';
249
			$script .= 'if(\'' . $choice . '\'===subKey){';
250
			$script .= ( $choice_is_direction ) ? $direction_script . 'else{' : '';
251
			$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . ':\'+subValue+\';}\';';
252
			$script .= ( $choice_is_direction ) ? '}' : '';
253
			$script .= '}';
254
		} else {
255
			$script .= $direction_script . 'else{';
256
257
			// This is where most object-based fields will go.
258
			$script .= 'css+=\'' . $args['element'] . '{\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
259
			$script .= '}';
260
		}
261
		$script .= '});';
262
263
		if ( isset( $args['media_query'] ) ) {
264
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
265
		}
266
267
		return array(
268
			'script' => $property_script . $script,
269
			'css'    => 'css',
270
		);
271
	}
272
273
	/**
274
	 * Processes script generation for typography fields.
275
	 *
276
	 * @access protected
277
	 * @since 3.0.0
278
	 * @param array $args  The arguments for this js_var.
279
	 */
280
	protected function script_var_typography( $args ) {
281
282
		$script = '';
283
		$css    = '';
284
285
		// Load the font using WenFontloader.
286
		// This is a bit ugly because wp_add_inline_script doesn't allow adding <script> directly.
287
		$webfont_loader = 'sc=\'a\';jQuery(\'head\').append(sc.replace(\'a\',\'<\')+\'script>if(!_.isUndefined(WebFont)){WebFont.load({google:{families:["\'+fontFamily.replace( /\"/g, \'&quot;\' )+\':\'+variant+subsetsString+\'"]}});}\'+sc.replace(\'a\',\'<\')+\'/script>\');';
288
289
		// Add the css.
290
		$css_build_array = array(
291
			'font-family'    => 'fontFamily',
292
			'font-size'      => 'fontSize',
293
			'line-height'    => 'lineHeight',
294
			'letter-spacing' => 'letterSpacing',
295
			'word-spacing'   => 'wordSpacing',
296
			'text-align'     => 'textAlign',
297
			'text-transform' => 'textTransform',
298
			'color'          => 'color',
299
			'font-weight'    => 'fontWeight',
300
			'font-style'     => 'fontStyle',
301
		);
302
		$choice_condition = ( isset( $args['choice'] ) && '' !== $args['choice'] && isset( $css_build_array[ $args['choice'] ] ) );
303
		$script .= ( ! $choice_condition ) ? $webfont_loader : '';
304
		foreach ( $css_build_array as $property => $var ) {
305
			if ( $choice_condition && $property !== $args['choice'] ) {
306
				continue;
307
			}
308
			$script .= ( $choice_condition && 'font-family' === $args['choice'] ) ? $webfont_loader : '';
309
310
			if ( ! isset( $args['choice'] ) || 'font-family' === $args['choice'] ) {
311
				$css .= 'fontFamilyCSS=fontFamily;if(0<fontFamily.indexOf(\' \')&&-1===fontFamily.indexOf(\'"\')){fontFamilyCSS=\'"\'+fontFamily+\'"\';}';
312
				$var = 'fontFamilyCSS';
313
			}
314
			$css .= 'css+=(\'\'!==' . $var . ')?\'' . $args['element'] . '\'+\'{' . $property . ':\'+' . $var . '+\';}\':\'\';';
315
		}
316
317
		$script .= $css;
318
		if ( isset( $args['media_query'] ) ) {
319
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
320
		}
321
		return array(
322
			'script' => $script,
323
			'css'    => 'css',
324
		);
325
	}
326
327
	/**
328
	 * Adds anything we need before the main script.
329
	 *
330
	 * @access private
331
	 * @since 3.0.0
332
	 * @param array $args The field args.
333
	 * @return string;
0 ignored issues
show
Documentation introduced by
The doc-type string; could not be parsed: Expected "|" or "end of type", but got ";" at position 6. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
334
	 */
335
	private function before_script( $args ) {
336
337
		$script = '';
338
339
		if ( isset( $args['type'] ) ) {
340
			switch ( $args['type'] ) {
341
				case 'kirki-typography':
342
					$script .= 'fontFamily=(_.isUndefined(newval[\'font-family\']))?\'\':newval[\'font-family\'];';
343
					$script .= 'variant=(_.isUndefined(newval.variant))?\'400\':newval.variant;';
344
					$script .= 'subsets=(_.isUndefined(newval.subsets))?[]:newval.subsets;';
345
					$script .= 'subsetsString=(_.isObject(newval.subsets))?\':\'+newval.subsets.join(\',\'):\'\';';
346
					$script .= 'fontSize=(_.isUndefined(newval[\'font-size\']))?\'\':newval[\'font-size\'];';
347
					$script .= 'lineHeight=(_.isUndefined(newval[\'line-height\']))?\'\':newval[\'line-height\'];';
348
					$script .= 'letterSpacing=(_.isUndefined(newval[\'letter-spacing\']))?\'\':newval[\'letter-spacing\'];';
349
					$script .= 'wordSpacing=(_.isUndefined(newval[\'word-spacing\']))?\'\':newval[\'word-spacing\'];';
350
					$script .= 'textAlign=(_.isUndefined(newval[\'text-align\']))?\'\':newval[\'text-align\'];';
351
					$script .= 'textTransform=(_.isUndefined(newval[\'text-transform\']))?\'\':newval[\'text-transform\'];';
352
					$script .= 'color=(_.isUndefined(newval.color))?\'\':newval.color;';
353
354
					$script .= 'fw=(!_.isString(newval.variant))?\'400\':newval.variant.match(/\d/g);';
355
					$script .= 'fontWeight=(!_.isObject(fw))?400:fw.join(\'\');';
356
					$script .= 'fontStyle=(-1!==variant.indexOf(\'italic\'))?\'italic\':\'normal\';';
357
					$script .= 'css=\'\';';
358
					break;
359
			}
360
		}
361
		return $script;
362
	}
363
364
	/**
365
	 * Sanitizes the arguments and makes sure they are all there.
366
	 *
367
	 * @access private
368
	 * @since 3.0.0
369
	 * @param array $args The arguments.
370
	 * @return array
371
	 */
372
	private function get_args( $args ) {
373
374
		// Make sure everything is defined to avoid "undefined index" errors.
375
		$args = wp_parse_args( $args, array(
376
			'element'       => '',
377
			'property'      => '',
378
			'prefix'        => '',
379
			'suffix'        => '',
380
			'units'         => '',
381
			'js_callback'   => array( '', '' ),
382
			'value_pattern' => '',
383
		));
384
385
		// Element should be a string.
386
		if ( is_array( $args['element'] ) ) {
387
			$args['element'] = implode( ',', $args['element'] );
388
		}
389
390
		// Make sure arguments that are passed-on to callbacks are strings.
391
		if ( is_array( $args['js_callback'] ) && isset( $args['js_callback'][1] ) && is_array( $args['js_callback'][1] ) ) {
392
			$args['js_callback'][1] = wp_json_encode( $args['js_callback'][1] );
393
		}
394
		return $args;
395
396
	}
397
398
	/**
399
	 * Returns script for value_pattern & replacements.
400
	 *
401
	 * @access private
402
	 * @since 3.0.0
403
	 * @param string $value   The value placeholder.
404
	 * @param array  $js_vars The js_vars argument.
405
	 * @return string         The script.
406
	 */
407
	private function value_pattern_replacements( $value, $js_vars ) {
408
		$script = '';
409
		$alias  = $value;
410
		if ( isset( $js_vars['pattern_replace'] ) ) {
411
			$script .= 'settings=window.wp.customize.get();';
412
			foreach ( $js_vars['pattern_replace'] as $search => $replace ) {
413
				$replace = '\'+settings["' . $replace . '"]+\'';
414
				$value = str_replace( $search, $replace, $js_vars['value_pattern'] );
415
				$value = trim( $value, '+' );
416
			}
417
		}
418
		$value_compiled = str_replace( '$', '\'+' . $alias . '+\'', $value );
419
		$value_compiled = trim( $value_compiled, '+' );
420
		return $script . $alias . '=\'' . $value_compiled . '\';';
421
	}
422
423
	/**
424
	 * Get the callback function/method we're going to use for this field.
425
	 *
426
	 * @access private
427
	 * @since 3.0.0
428
	 * @param array $args The field args.
429
	 * @return string|array A callable function or method.
430
	 */
431
	protected function get_callback( $args ) {
432
433
		switch ( $args['type'] ) {
434
			case 'kirki-background':
435
			case 'kirki-dimensions':
436
			case 'kirki-multicolor':
437
			case 'kirki-sortable':
438
				$callback = array( $this, 'script_var_array' );
439
				break;
440
			case 'kirki-typography':
441
				$callback = array( $this, 'script_var_typography' );
442
				break;
443
			default:
444
				$callback = array( $this, 'script_var' );
445
		}
446
		return $callback;
447
	}
448
}
449