Completed
Push — develop ( 17a154...2d9e91 )
by Aristeides
02:59
created

Kirki_Modules_PostMessage::script_var()   C

Complexity

Conditions 8
Paths 32

Size

Total Lines 38
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 21
nc 32
nop 1
dl 0
loc 38
rs 5.3846
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
	/**
24
	 * The script.
25
	 *
26
	 * @access protected
27
	 * @since 3.0.0
28
	 * @var string
29
	 */
30
	protected $script = '';
31
32
	/**
33
	 * Constructor.
34
	 *
35
	 * @access public
36
	 * @since 3.0.0
37
	 */
38
	public function __construct() {
39
		add_action( 'customize_preview_init', array( $this, 'postmessage' ) );
40
	}
41
42
	/**
43
	 * Enqueues the postMessage script
44
	 * and adds variables to it using the wp_localize_script function.
45
	 * The rest is handled via JS.
46
	 */
47
	public function postmessage() {
48
49
		wp_enqueue_script( 'kirki_auto_postmessage', trailingslashit( Kirki::$url ) . 'modules/postmessage/postmessage.js', array( 'jquery', 'customize-preview' ), false, true );
50
		$fields = Kirki::$fields;
51
		foreach ( $fields as $field ) {
52
			if ( isset( $field['transport'] ) && 'postMessage' === $field['transport'] && isset( $field['js_vars'] ) && ! empty( $field['js_vars'] ) && is_array( $field['js_vars'] ) && isset( $field['settings'] ) ) {
53
				$this->script .= $this->script( $field );
54
			}
55
		}
56
		$this->script = apply_filters( 'kirki/postmessage/script', $this->script );
57
		wp_add_inline_script( 'kirki_auto_postmessage', $this->script, 'after' );
58
59
	}
60
61
	/**
62
	 * Generates script for a single field.
63
	 *
64
	 * @access protected
65
	 * @since 3.0.0
66
	 * @param array $args The arguments.
67
	 */
68
	protected function script( $args ) {
69
70
		$script = 'wp.customize(\'' . $args['settings'] . '\',function(value){value.bind(function(newval){';
71
		// append unique style tag if not exist
72
		// The style ID.
73
		$style_id = 'kirki-postmessage-' . str_replace( array( '[', ']' ), '', $args['settings'] );
74
		$script .= 'if(null===document.getElementById(\'' . $style_id . '\')||\'undefined\'===typeof document.getElementById(\'' . $style_id . '\')){jQuery(\'head\').append(\'<style id="' . $style_id . '"></style>\');}';
75
76
		// Add anything we need before the main script.
77
		$script .= $this->before_script( $args );
78
79
		$field = array(
80
			'scripts' => array(),
81
		);
82
		// Loop through the js_vars and generate the script.
83
		foreach ( $args['js_vars'] as $key => $js_var ) {
84
			if ( isset( $js_var['function'] ) && 'html' === $js_var['function'] ) {
85
				$script .= $this->script_html_var( $js_var );
86
				continue;
87
			}
88
			$js_var['index_key'] = $key;
89
			$callback = $this->get_callback( $args );
90
			if ( is_callable( $callback ) ) {
91
				$field['scripts'][ $key ] = call_user_func_array( $callback, array( $js_var, $args ) );
92
				continue;
93
			}
94
			$field['scripts'][ $key ] = $this->script_var( $js_var );
95
		}
96
		$combo_extra_script = '';
97
		$combo_css_script   = '';
98
		foreach ( $field['scripts'] as $script_array ) {
99
			$combo_extra_script .= $script_array['script'];
100
			$combo_css_script   .= ( 'css' !== $combo_css_script ) ? $script_array['css'] : '';
101
		}
102
		$text = ( 'css' === $combo_css_script ) ? 'css' : '\'' . $combo_css_script . '\'';
103
		$script .= $combo_extra_script . 'jQuery(\'#' . $style_id . '\').text(' . $text . ');';
104
		$script .= '});});';
105
		return $script;
106
	}
107
108
	/**
109
	 * Generates script for a single js_var when using "html" as function.
110
	 *
111
	 * @access protected
112
	 * @since 3.0.0
113
	 * @param array $args  The arguments for this js_var.
114
	 */
115
	protected function script_html_var( $args ) {
116
117
		$script  = ( isset( $args['choice'] ) ) ? 'newval=newval[\'' . $args['choice'] . '\'];' : '';
118
		$script .= 'jQuery(\'' . $args['element'] . '\').html(newval);';
119
		if ( isset( $args['attr'] ) ) {
120
			$script = 'jQuery(\'' . $args['element'] . '\').attr(\'' . $args['attr'] . '\',newval);';
121
		}
122
		return $script;
123
	}
124
125
	/**
126
	 * Generates script for a single js_var.
127
	 *
128
	 * @access protected
129
	 * @since 3.0.0
130
	 * @param array $args  The arguments for this js_var.
131
	 */
132
	protected function script_var( $args ) {
133
		$script = '';
134
		$property_script = '';
135
136
		$value_key = 'newval' . $args['index_key'];
137
		$property_script .= $value_key . '=newval;';
138
139
		$args = $this->get_args( $args );
140
141
		// Apply callback to the value if a callback is defined.
142
		if ( ! empty( $args['js_callback'][0] ) ) {
143
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
144
		}
145
146
		// Apply the value_pattern.
147
		if ( '' !== $args['value_pattern'] ) {
148
			$script .= $this->value_pattern_replacements( $value_key, $args );
149
		}
150
151
		// Tweak to add url() for background-images.
152
		if ( 'background-image' === $args['property'] && ( ! isset( $args['value_pattern'] ) || false === strpos( $args['value_pattern'], 'gradient' ) ) ) {
153
			$script .= 'if(-1===' . $value_key . '.indexOf(\'url(\')){' . $value_key . '=\'url("\'+' . $value_key . '+\'");}';
154
		}
155
156
		// Apply prefix.
157
		$value = $value_key;
158
		if ( '' !== $args['prefix'] ) {
159
			$value = $args['prefix'] . '+' . $value_key;
160
		}
161
		$css = $args['element'] . '{' . $args['property'] . ':\'+' . $value . '+\'' . $args['units'] . $args['suffix'] . ';}';
162
		if ( isset( $args['media_query'] ) ) {
163
			$css = $args['media_query'] . '{' . $css . '}';
164
		}
165
		return array(
166
			'script' => $property_script . $script,
167
			'css'    => $css,
168
		);
169
	}
170
171
	/**
172
	 * Processes script generation for fields that save an array.
173
	 *
174
	 * @access protected
175
	 * @since 3.0.0
176
	 * @param array $args  The arguments for this js_var.
177
	 */
178
	protected function script_var_array( $args ) {
179
180
		$script = 'css=\'\';';
181
		$property_script = '';
182
183
		// Define choice.
184
		$choice  = ( isset( $args['choice'] ) && '' !== $args['choice'] ) ? $args['choice'] : '';
185
		$script .= ( '' !== $choice ) ? 'choice=\'' . $choice . '\';' : '';
186
187
		$value_key = 'newval' . $args['index_key'];
188
		$property_script .= $value_key . '=newval;';
189
190
		$args = $this->get_args( $args );
191
192
		// Apply callback to the value if a callback is defined.
193
		if ( ! empty( $args['js_callback'][0] ) ) {
194
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
195
		}
196
		$script .= '_.each(' . $value_key . ', function(subValue,subKey){';
197
198
		// Apply the value_pattern.
199
		if ( '' !== $args['value_pattern'] ) {
200
			$script .= $this->value_pattern_replacements( 'subValue', $args );
201
		}
202
203
		// Tweak to add url() for background-images.
204
		if ( '' === $choice || 'background-image' === $choice ) {
205
			$script .= 'if(\'background-image\'===\'' . $args['property'] . '\'||\'background-image\'===subKey){';
206
			$script .= 'if(-1===subValue.indexOf(\'url(\')){subValue=\'url("\'+subValue+\'")\';}';
207
			$script .= '}';
208
		}
209
210
		// Apply prefix.
211
		$value = $value_key;
212
		if ( '' !== $args['prefix'] ) {
213
			$value = '\'' . $args['prefix'] . '\'+subValue';
214
		}
215
216
		// Mostly used for padding, margin & position properties.
217
		$direction_script  = 'if(_.contains([\'top\',\'bottom\',\'left\',\'right\'],subKey)){';
218
		$direction_script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . '-\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';}';
219
		// Allows us to apply this just for a specific choice in the array of the values.
220
		if ( '' !== $choice ) {
221
			$choice_is_direction = ( false !== strpos( $choice, 'top' ) || false !== strpos( $choice, 'bottom' ) || false !== strpos( $choice, 'left' ) || false !== strpos( $choice, 'right' ) );
222
			$script .= 'choice=\'' . $choice . '\';';
223
			$script .= 'if(\'' . $choice . '\'===subKey){';
224
			$script .= ( $choice_is_direction ) ? $direction_script . 'else{' : '';
225
			$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . ':\'+subValue+\';}\';';
226
			$script .= ( $choice_is_direction ) ? '}' : '';
227
			$script .= '}';
228
		} else {
229
			$script .= $direction_script . 'else{';
230
231
			// This is where most object-based fields will go.
232
			$script .= 'css+=\'' . $args['element'] . '{\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
233
			$script .= '}';
234
		}
235
		$script .= '});';
236
237
		if ( isset( $args['media_query'] ) ) {
238
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
239
		}
240
241
		return array(
242
			'script' => $property_script . $script,
243
			'css'    => 'css',
244
		);
245
	}
246
247
	/**
248
	 * Processes script generation for typography fields.
249
	 *
250
	 * @access protected
251
	 * @since 3.0.0
252
	 * @param array $args  The arguments for this js_var.
253
	 */
254
	protected function script_var_typography( $args ) {
255
256
		$script = '';
257
		$css    = '';
258
259
		// Load the font using WenFontloader.
260
		// This is a bit ugly because wp_add_inline_script doesn't allow adding <script> directly.
261
		$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>\');';
262
263
		// Add the css.
264
		$css_build_array = array(
265
			'font-family'    => 'fontFamily',
266
			'font-size'      => 'fontSize',
267
			'line-height'    => 'lineHeight',
268
			'letter-spacing' => 'letterSpacing',
269
			'word-spacing'   => 'wordSpacing',
270
			'text-align'     => 'textAlign',
271
			'text-transform' => 'textTransform',
272
			'color'          => 'color',
273
			'font-weight'    => 'fontWeight',
274
			'font-style'     => 'fontStyle',
275
		);
276
		$choice_condition = ( isset( $args['choice'] ) && '' !== $args['choice'] && isset( $css_build_array[ $args['choice'] ] ) );
277
		$script .= ( ! $choice_condition ) ? $webfont_loader : '';
278
		foreach ( $css_build_array as $property => $var ) {
279
			if ( $choice_condition && $property !== $args['choice'] ) {
280
				continue;
281
			}
282
			$script .= ( $choice_condition && 'font-family' === $args['choice'] ) ? $webfont_loader : '';
283
			$css .= 'css+=(\'\'!==' . $var . ')?\'' . $args['element'] . '\'+\'{' . $property . ':\'+' . $var . '+\'}\':\'\';';
284
		}
285
286
		$script .= $css;
287
		if ( isset( $args['media_query'] ) ) {
288
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
289
		}
290
		return array(
291
			'script' => $script,
292
			'css'    => 'css',
293
		);
294
	}
295
296
	/**
297
	 * Adds anything we need before the main script.
298
	 *
299
	 * @access private
300
	 * @since 3.0.0
301
	 * @param array $args The field args.
302
	 * @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...
303
	 */
304
	private function before_script( $args ) {
305
306
		$script = '';
307
308
		if ( isset( $args['type'] ) ) {
309
			switch ( $args['type'] ) {
310
				case 'kirki-typography':
311
					$script .= 'fontFamily=(_.isUndefined(newval[\'font-family\']))?\'\':newval[\'font-family\'];';
312
					$script .= 'variant=(_.isUndefined(newval.variant))?\'400\':newval.variant;';
313
					$script .= 'subsets=(_.isUndefined(newval.subsets))?[]:newval.subsets;';
314
					$script .= 'subsetsString=(_.isObject(newval.subsets))?\':\'+newval.subsets.join(\',\'):\'\';';
315
					$script .= 'fontSize=(_.isUndefined(newval[\'font-size\']))?\'\':newval[\'font-size\'];';
316
					$script .= 'lineHeight=(_.isUndefined(newval[\'line-height\']))?\'\':newval[\'line-height\'];';
317
					$script .= 'letterSpacing=(_.isUndefined(newval[\'letter-spacing\']))?\'\':newval[\'letter-spacing\'];';
318
					$script .= 'wordSpacing=(_.isUndefined(newval[\'word-spacing\']))?\'\':newval[\'word-spacing\'];';
319
					$script .= 'textAlign=(_.isUndefined(newval[\'text-align\']))?\'\':newval[\'text-align\'];';
320
					$script .= 'textTransform=(_.isUndefined(newval[\'text-transform\']))?\'\':newval[\'text-transform\'];';
321
					$script .= 'color=(_.isUndefined(newval.color))?\'\':newval.color;';
322
323
					$script .= 'fw=(!_.isString(newval.variant))?\'400\':newval.variant.match(/\d/g);';
324
					$script .= 'fontWeight=(!_.isObject(fw))?400:fw.join(\'\');';
325
					$script .= 'fontStyle=(-1!==variant.indexOf(\'italic\'))?\'italic\':\'normal\';';
326
					$script .= 'css=\'\';';
327
					break;
328
			}
329
		}
330
		return $script;
331
	}
332
333
	/**
334
	 * Sanitizes the arguments and makes sure they are all there.
335
	 *
336
	 * @access private
337
	 * @since 3.0.0
338
	 * @param array $args The arguments.
339
	 * @return array
340
	 */
341
	private function get_args( $args ) {
342
343
		// Make sure everything is defined to avoid "undefined index" errors.
344
		$args = wp_parse_args( $args, array(
345
			'element'       => '',
346
			'property'      => '',
347
			'prefix'        => '',
348
			'suffix'        => '',
349
			'units'         => '',
350
			'js_callback'   => array( '', '' ),
351
			'value_pattern' => '',
352
		));
353
354
		// Element should be a string.
355
		if ( is_array( $args['element'] ) ) {
356
			$args['element'] = implode( ',', $args['element'] );
357
		}
358
359
		// Make sure arguments that are passed-on to callbacks are strings.
360
		if ( is_array( $args['js_callback'] ) && isset( $args['js_callback'][1] ) && is_array( $args['js_callback'][1] ) ) {
361
			$args['js_callback'][1] = wp_json_encode( $args['js_callback'][1] );
362
		}
363
		return $args;
364
365
	}
366
367
	/**
368
	 * Returns script for value_pattern & replacements.
369
	 *
370
	 * @access private
371
	 * @since 3.0.0
372
	 * @param string $value   The value placeholder.
373
	 * @param array  $js_vars The js_vars argument.
374
	 * @return string         The script.
375
	 */
376
	private function value_pattern_replacements( $value, $js_vars ) {
377
		$script = '';
378
		$alias  = $value;
379
		if ( isset( $js_vars['pattern_replace'] ) ) {
380
			$script .= 'settings=window.wp.customize.get();';
381
			foreach ( $js_vars['pattern_replace'] as $search => $replace ) {
382
				$replace = '\'+settings["' . $replace . '"]+\'';
383
				$value = str_replace( $search, $replace, $js_vars['value_pattern'] );
384
				$value = trim( $value, '+' );
385
			}
386
		}
387
		$value_compiled = str_replace( '$', '\'+' . $alias . '+\'', $value );
388
		$value_compiled = trim( $value_compiled, '+' );
389
		return $script . $alias . '=\'' . $value_compiled . '\';';
390
	}
391
392
	/**
393
	 * Get the callback function/method we're going to use for this field.
394
	 *
395
	 * @access private
396
	 * @since 3.0.0
397
	 * @param array $args The field args.
398
	 * @return string|array A callable function or method.
399
	 */
400
	protected function get_callback( $args ) {
401
402
		switch ( $args['type'] ) {
403
			case 'kirki-background':
404
			case 'kirki-dimensions':
405
			case 'kirki-multicolor':
406
			case 'kirki-sortable':
407
				$callback = array( $this, 'script_var_array' );
408
				break;
409
			case 'kirki-typography':
410
				$callback = array( $this, 'script_var_typography' );
411
				break;
412
			default:
413
				$callback = array( $this, 'script_var' );
414
		}
415
		return $callback;
416
	}
417
}
418