summaryrefslogtreecommitdiffstats
path: root/wp-includes/js/wp-util.js
blob: c603bc69f4a21219fd3ae2b7cbb8e6b40a215029 (plain)
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
/**
 * @output wp-includes/js/wp-util.js
 */

/* global _wpUtilSettings */

/** @namespace wp */
window.wp = window.wp || {};

(function ($) {
	// Check for the utility settings.
	var settings = typeof _wpUtilSettings === 'undefined' ? {} : _wpUtilSettings;

	/**
	 * wp.template( id )
	 *
	 * Fetch a JavaScript template for an id, and return a templating function for it.
	 *
	 * @param {string} id A string that corresponds to a DOM element with an id prefixed with "tmpl-".
	 *                    For example, "attachment" maps to "tmpl-attachment".
	 * @return {function} A function that lazily-compiles the template requested.
	 */
	wp.template = _.memoize(function ( id ) {
		var compiled,
			/*
			 * Underscore's default ERB-style templates are incompatible with PHP
			 * when asp_tags is enabled, so WordPress uses Mustache-inspired templating syntax.
			 *
			 * @see trac ticket #22344.
			 */
			options = {
				evaluate:    /<#([\s\S]+?)#>/g,
				interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
				escape:      /\{\{([^\}]+?)\}\}(?!\})/g,
				variable:    'data'
			};

		return function ( data ) {
			if ( ! document.getElementById( 'tmpl-' + id ) ) {
				throw new Error( 'Template not found: ' + '#tmpl-' + id );
			}
			compiled = compiled || _.template( $( '#tmpl-' + id ).html(),  options );
			return compiled( data );
		};
	});

	/*
	 * wp.ajax
	 * ------
	 *
	 * Tools for sending ajax requests with JSON responses and built in error handling.
	 * Mirrors and wraps jQuery's ajax APIs.
	 */
	wp.ajax = {
		settings: settings.ajax || {},

		/**
		 * wp.ajax.post( [action], [data] )
		 *
		 * Sends a POST request to WordPress.
		 *
		 * @param {(string|Object)} action The slug of the action to fire in WordPress or options passed
		 *                                 to jQuery.ajax.
		 * @param {Object=}         data   Optional. The data to populate $_POST with.
		 * @return {$.promise} A jQuery promise that represents the request,
		 *                     decorated with an abort() method.
		 */
		post: function( action, data ) {
			return wp.ajax.send({
				data: _.isObject( action ) ? action : _.extend( data || {}, { action: action })
			});
		},

		/**
		 * wp.ajax.send( [action], [options] )
		 *
		 * Sends a POST request to WordPress.
		 *
		 * @param {(string|Object)} action  The slug of the action to fire in WordPress or options passed
		 *                                  to jQuery.ajax.
		 * @param {Object=}         options Optional. The options passed to jQuery.ajax.
		 * @return {$.promise} A jQuery promise that represents the request,
		 *                     decorated with an abort() method.
		 */
		send: function( action, options ) {
			var promise, deferred;
			if ( _.isObject( action ) ) {
				options = action;
			} else {
				options = options || {};
				options.data = _.extend( options.data || {}, { action: action });
			}

			options = _.defaults( options || {}, {
				type:    'POST',
				url:     wp.ajax.settings.url,
				context: this
			});

			deferred = $.Deferred( function( deferred ) {
				// Transfer success/error callbacks.
				if ( options.success ) {
					deferred.done( options.success );
				}

				if ( options.error ) {
					deferred.fail( options.error );
				}

				delete options.success;
				delete options.error;

				// Use with PHP's wp_send_json_success() and wp_send_json_error().
				deferred.jqXHR = $.ajax( options ).done( function( response ) {
					// Treat a response of 1 as successful for backward compatibility with existing handlers.
					if ( response === '1' || response === 1 ) {
						response = { success: true };
					}

					if ( _.isObject( response ) && ! _.isUndefined( response.success ) ) {

						// When handling a media attachments request, get the total attachments from response headers.
						var context = this;
						deferred.done( function() {
							if (
								action &&
								action.data &&
								'query-attachments' === action.data.action &&
								deferred.jqXHR.hasOwnProperty( 'getResponseHeader' ) &&
								deferred.jqXHR.getResponseHeader( 'X-WP-Total' )
							) {
								context.totalAttachments = parseInt( deferred.jqXHR.getResponseHeader( 'X-WP-Total' ), 10 );
							} else {
								context.totalAttachments = 0;
							}
						} );
						deferred[ response.success ? 'resolveWith' : 'rejectWith' ]( this, [response.data] );
					} else {
						deferred.rejectWith( this, [response] );
					}
				}).fail( function() {
					deferred.rejectWith( this, arguments );
				});
			});

			promise = deferred.promise();
			promise.abort = function() {
				deferred.jqXHR.abort();
				return this;
			};

			return promise;
		}
	};

}(jQuery));