You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

850 lines
22 KiB

  1. window.wp = window.wp || {};
  2. (function( exports, $ ){
  3. var api = {}, ctor, inherits,
  4. slice = Array.prototype.slice;
  5. // Shared empty constructor function to aid in prototype-chain creation.
  6. ctor = function() {};
  7. /**
  8. * Helper function to correctly set up the prototype chain, for subclasses.
  9. * Similar to `goog.inherits`, but uses a hash of prototype properties and
  10. * class properties to be extended.
  11. *
  12. * @param object parent Parent class constructor to inherit from.
  13. * @param object protoProps Properties to apply to the prototype for use as class instance properties.
  14. * @param object staticProps Properties to apply directly to the class constructor.
  15. * @return child The subclassed constructor.
  16. */
  17. inherits = function( parent, protoProps, staticProps ) {
  18. var child;
  19. // The constructor function for the new subclass is either defined by you
  20. // (the "constructor" property in your `extend` definition), or defaulted
  21. // by us to simply call `super()`.
  22. if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) {
  23. child = protoProps.constructor;
  24. } else {
  25. child = function() {
  26. // Storing the result `super()` before returning the value
  27. // prevents a bug in Opera where, if the constructor returns
  28. // a function, Opera will reject the return value in favor of
  29. // the original object. This causes all sorts of trouble.
  30. var result = parent.apply( this, arguments );
  31. return result;
  32. };
  33. }
  34. // Inherit class (static) properties from parent.
  35. $.extend( child, parent );
  36. // Set the prototype chain to inherit from `parent`, without calling
  37. // `parent`'s constructor function.
  38. ctor.prototype = parent.prototype;
  39. child.prototype = new ctor();
  40. // Add prototype properties (instance properties) to the subclass,
  41. // if supplied.
  42. if ( protoProps )
  43. $.extend( child.prototype, protoProps );
  44. // Add static properties to the constructor function, if supplied.
  45. if ( staticProps )
  46. $.extend( child, staticProps );
  47. // Correctly set child's `prototype.constructor`.
  48. child.prototype.constructor = child;
  49. // Set a convenience property in case the parent's prototype is needed later.
  50. child.__super__ = parent.prototype;
  51. return child;
  52. };
  53. /**
  54. * Base class for object inheritance.
  55. */
  56. api.Class = function( applicator, argsArray, options ) {
  57. var magic, args = arguments;
  58. if ( applicator && argsArray && api.Class.applicator === applicator ) {
  59. args = argsArray;
  60. $.extend( this, options || {} );
  61. }
  62. magic = this;
  63. /*
  64. * If the class has a method called "instance",
  65. * the return value from the class' constructor will be a function that
  66. * calls the "instance" method.
  67. *
  68. * It is also an object that has properties and methods inside it.
  69. */
  70. if ( this.instance ) {
  71. magic = function() {
  72. return magic.instance.apply( magic, arguments );
  73. };
  74. $.extend( magic, this );
  75. }
  76. magic.initialize.apply( magic, args );
  77. return magic;
  78. };
  79. /**
  80. * Creates a subclass of the class.
  81. *
  82. * @param object protoProps Properties to apply to the prototype.
  83. * @param object staticProps Properties to apply directly to the class.
  84. * @return child The subclass.
  85. */
  86. api.Class.extend = function( protoProps, classProps ) {
  87. var child = inherits( this, protoProps, classProps );
  88. child.extend = this.extend;
  89. return child;
  90. };
  91. api.Class.applicator = {};
  92. /**
  93. * Initialize a class instance.
  94. *
  95. * Override this function in a subclass as needed.
  96. */
  97. api.Class.prototype.initialize = function() {};
  98. /*
  99. * Checks whether a given instance extended a constructor.
  100. *
  101. * The magic surrounding the instance parameter causes the instanceof
  102. * keyword to return inaccurate results; it defaults to the function's
  103. * prototype instead of the constructor chain. Hence this function.
  104. */
  105. api.Class.prototype.extended = function( constructor ) {
  106. var proto = this;
  107. while ( typeof proto.constructor !== 'undefined' ) {
  108. if ( proto.constructor === constructor )
  109. return true;
  110. if ( typeof proto.constructor.__super__ === 'undefined' )
  111. return false;
  112. proto = proto.constructor.__super__;
  113. }
  114. return false;
  115. };
  116. /**
  117. * An events manager object, offering the ability to bind to and trigger events.
  118. *
  119. * Used as a mixin.
  120. */
  121. api.Events = {
  122. trigger: function( id ) {
  123. if ( this.topics && this.topics[ id ] )
  124. this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
  125. return this;
  126. },
  127. bind: function( id ) {
  128. this.topics = this.topics || {};
  129. this.topics[ id ] = this.topics[ id ] || $.Callbacks();
  130. this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
  131. return this;
  132. },
  133. unbind: function( id ) {
  134. if ( this.topics && this.topics[ id ] )
  135. this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
  136. return this;
  137. }
  138. };
  139. /**
  140. * Observable values that support two-way binding.
  141. *
  142. * @constructor
  143. */
  144. api.Value = api.Class.extend({
  145. /**
  146. * @param {mixed} initial The initial value.
  147. * @param {object} options
  148. */
  149. initialize: function( initial, options ) {
  150. this._value = initial; // @todo: potentially change this to a this.set() call.
  151. this.callbacks = $.Callbacks();
  152. this._dirty = false;
  153. $.extend( this, options || {} );
  154. this.set = $.proxy( this.set, this );
  155. },
  156. /*
  157. * Magic. Returns a function that will become the instance.
  158. * Set to null to prevent the instance from extending a function.
  159. */
  160. instance: function() {
  161. return arguments.length ? this.set.apply( this, arguments ) : this.get();
  162. },
  163. /**
  164. * Get the value.
  165. *
  166. * @return {mixed}
  167. */
  168. get: function() {
  169. return this._value;
  170. },
  171. /**
  172. * Set the value and trigger all bound callbacks.
  173. *
  174. * @param {object} to New value.
  175. */
  176. set: function( to ) {
  177. var from = this._value;
  178. to = this._setter.apply( this, arguments );
  179. to = this.validate( to );
  180. // Bail if the sanitized value is null or unchanged.
  181. if ( null === to || _.isEqual( from, to ) ) {
  182. return this;
  183. }
  184. this._value = to;
  185. this._dirty = true;
  186. this.callbacks.fireWith( this, [ to, from ] );
  187. return this;
  188. },
  189. _setter: function( to ) {
  190. return to;
  191. },
  192. setter: function( callback ) {
  193. var from = this.get();
  194. this._setter = callback;
  195. // Temporarily clear value so setter can decide if it's valid.
  196. this._value = null;
  197. this.set( from );
  198. return this;
  199. },
  200. resetSetter: function() {
  201. this._setter = this.constructor.prototype._setter;
  202. this.set( this.get() );
  203. return this;
  204. },
  205. validate: function( value ) {
  206. return value;
  207. },
  208. /**
  209. * Bind a function to be invoked whenever the value changes.
  210. *
  211. * @param {...Function} A function, or multiple functions, to add to the callback stack.
  212. */
  213. bind: function() {
  214. this.callbacks.add.apply( this.callbacks, arguments );
  215. return this;
  216. },
  217. /**
  218. * Unbind a previously bound function.
  219. *
  220. * @param {...Function} A function, or multiple functions, to remove from the callback stack.
  221. */
  222. unbind: function() {
  223. this.callbacks.remove.apply( this.callbacks, arguments );
  224. return this;
  225. },
  226. link: function() { // values*
  227. var set = this.set;
  228. $.each( arguments, function() {
  229. this.bind( set );
  230. });
  231. return this;
  232. },
  233. unlink: function() { // values*
  234. var set = this.set;
  235. $.each( arguments, function() {
  236. this.unbind( set );
  237. });
  238. return this;
  239. },
  240. sync: function() { // values*
  241. var that = this;
  242. $.each( arguments, function() {
  243. that.link( this );
  244. this.link( that );
  245. });
  246. return this;
  247. },
  248. unsync: function() { // values*
  249. var that = this;
  250. $.each( arguments, function() {
  251. that.unlink( this );
  252. this.unlink( that );
  253. });
  254. return this;
  255. }
  256. });
  257. /**
  258. * A collection of observable values.
  259. *
  260. * @constructor
  261. * @augments wp.customize.Class
  262. * @mixes wp.customize.Events
  263. */
  264. api.Values = api.Class.extend({
  265. /**
  266. * The default constructor for items of the collection.
  267. *
  268. * @type {object}
  269. */
  270. defaultConstructor: api.Value,
  271. initialize: function( options ) {
  272. $.extend( this, options || {} );
  273. this._value = {};
  274. this._deferreds = {};
  275. },
  276. /**
  277. * Get the instance of an item from the collection if only ID is specified.
  278. *
  279. * If more than one argument is supplied, all are expected to be IDs and
  280. * the last to be a function callback that will be invoked when the requested
  281. * items are available.
  282. *
  283. * @see {api.Values.when}
  284. *
  285. * @param {string} id ID of the item.
  286. * @param {...} Zero or more IDs of items to wait for and a callback
  287. * function to invoke when they're available. Optional.
  288. * @return {mixed} The item instance if only one ID was supplied.
  289. * A Deferred Promise object if a callback function is supplied.
  290. */
  291. instance: function( id ) {
  292. if ( arguments.length === 1 )
  293. return this.value( id );
  294. return this.when.apply( this, arguments );
  295. },
  296. /**
  297. * Get the instance of an item.
  298. *
  299. * @param {string} id The ID of the item.
  300. * @return {[type]} [description]
  301. */
  302. value: function( id ) {
  303. return this._value[ id ];
  304. },
  305. /**
  306. * Whether the collection has an item with the given ID.
  307. *
  308. * @param {string} id The ID of the item to look for.
  309. * @return {Boolean}
  310. */
  311. has: function( id ) {
  312. return typeof this._value[ id ] !== 'undefined';
  313. },
  314. /**
  315. * Add an item to the collection.
  316. *
  317. * @param {string} id The ID of the item.
  318. * @param {mixed} value The item instance.
  319. * @return {mixed} The new item's instance.
  320. */
  321. add: function( id, value ) {
  322. if ( this.has( id ) )
  323. return this.value( id );
  324. this._value[ id ] = value;
  325. value.parent = this;
  326. // Propagate a 'change' event on an item up to the collection.
  327. if ( value.extended( api.Value ) )
  328. value.bind( this._change );
  329. this.trigger( 'add', value );
  330. // If a deferred object exists for this item,
  331. // resolve it.
  332. if ( this._deferreds[ id ] )
  333. this._deferreds[ id ].resolve();
  334. return this._value[ id ];
  335. },
  336. /**
  337. * Create a new item of the collection using the collection's default constructor
  338. * and store it in the collection.
  339. *
  340. * @param {string} id The ID of the item.
  341. * @param {mixed} value Any extra arguments are passed into the item's initialize method.
  342. * @return {mixed} The new item's instance.
  343. */
  344. create: function( id ) {
  345. return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
  346. },
  347. /**
  348. * Iterate over all items in the collection invoking the provided callback.
  349. *
  350. * @param {Function} callback Function to invoke.
  351. * @param {object} context Object context to invoke the function with. Optional.
  352. */
  353. each: function( callback, context ) {
  354. context = typeof context === 'undefined' ? this : context;
  355. $.each( this._value, function( key, obj ) {
  356. callback.call( context, obj, key );
  357. });
  358. },
  359. /**
  360. * Remove an item from the collection.
  361. *
  362. * @param {string} id The ID of the item to remove.
  363. */
  364. remove: function( id ) {
  365. var value;
  366. if ( this.has( id ) ) {
  367. value = this.value( id );
  368. this.trigger( 'remove', value );
  369. if ( value.extended( api.Value ) )
  370. value.unbind( this._change );
  371. delete value.parent;
  372. }
  373. delete this._value[ id ];
  374. delete this._deferreds[ id ];
  375. },
  376. /**
  377. * Runs a callback once all requested values exist.
  378. *
  379. * when( ids*, [callback] );
  380. *
  381. * For example:
  382. * when( id1, id2, id3, function( value1, value2, value3 ) {} );
  383. *
  384. * @returns $.Deferred.promise();
  385. */
  386. when: function() {
  387. var self = this,
  388. ids = slice.call( arguments ),
  389. dfd = $.Deferred();
  390. // If the last argument is a callback, bind it to .done()
  391. if ( $.isFunction( ids[ ids.length - 1 ] ) )
  392. dfd.done( ids.pop() );
  393. /*
  394. * Create a stack of deferred objects for each item that is not
  395. * yet available, and invoke the supplied callback when they are.
  396. */
  397. $.when.apply( $, $.map( ids, function( id ) {
  398. if ( self.has( id ) )
  399. return;
  400. /*
  401. * The requested item is not available yet, create a deferred
  402. * object to resolve when it becomes available.
  403. */
  404. return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
  405. })).done( function() {
  406. var values = $.map( ids, function( id ) {
  407. return self( id );
  408. });
  409. // If a value is missing, we've used at least one expired deferred.
  410. // Call Values.when again to generate a new deferred.
  411. if ( values.length !== ids.length ) {
  412. // ids.push( callback );
  413. self.when.apply( self, ids ).done( function() {
  414. dfd.resolveWith( self, values );
  415. });
  416. return;
  417. }
  418. dfd.resolveWith( self, values );
  419. });
  420. return dfd.promise();
  421. },
  422. /**
  423. * A helper function to propagate a 'change' event from an item
  424. * to the collection itself.
  425. */
  426. _change: function() {
  427. this.parent.trigger( 'change', this );
  428. }
  429. });
  430. // Create a global events bus on the Customizer.
  431. $.extend( api.Values.prototype, api.Events );
  432. /**
  433. * Cast a string to a jQuery collection if it isn't already.
  434. *
  435. * @param {string|jQuery collection} element
  436. */
  437. api.ensure = function( element ) {
  438. return typeof element == 'string' ? $( element ) : element;
  439. };
  440. /**
  441. * An observable value that syncs with an element.
  442. *
  443. * Handles inputs, selects, and textareas by default.
  444. *
  445. * @constructor
  446. * @augments wp.customize.Value
  447. * @augments wp.customize.Class
  448. */
  449. api.Element = api.Value.extend({
  450. initialize: function( element, options ) {
  451. var self = this,
  452. synchronizer = api.Element.synchronizer.html,
  453. type, update, refresh;
  454. this.element = api.ensure( element );
  455. this.events = '';
  456. if ( this.element.is('input, select, textarea') ) {
  457. this.events += 'change';
  458. synchronizer = api.Element.synchronizer.val;
  459. if ( this.element.is('input') ) {
  460. type = this.element.prop('type');
  461. if ( api.Element.synchronizer[ type ] ) {
  462. synchronizer = api.Element.synchronizer[ type ];
  463. }
  464. if ( 'text' === type || 'password' === type ) {
  465. this.events += ' keyup';
  466. } else if ( 'range' === type ) {
  467. this.events += ' input propertychange';
  468. }
  469. } else if ( this.element.is('textarea') ) {
  470. this.events += ' keyup';
  471. }
  472. }
  473. api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
  474. this._value = this.get();
  475. update = this.update;
  476. refresh = this.refresh;
  477. this.update = function( to ) {
  478. if ( to !== refresh.call( self ) )
  479. update.apply( this, arguments );
  480. };
  481. this.refresh = function() {
  482. self.set( refresh.call( self ) );
  483. };
  484. this.bind( this.update );
  485. this.element.bind( this.events, this.refresh );
  486. },
  487. find: function( selector ) {
  488. return $( selector, this.element );
  489. },
  490. refresh: function() {},
  491. update: function() {}
  492. });
  493. api.Element.synchronizer = {};
  494. $.each( [ 'html', 'val' ], function( index, method ) {
  495. api.Element.synchronizer[ method ] = {
  496. update: function( to ) {
  497. this.element[ method ]( to );
  498. },
  499. refresh: function() {
  500. return this.element[ method ]();
  501. }
  502. };
  503. });
  504. api.Element.synchronizer.checkbox = {
  505. update: function( to ) {
  506. this.element.prop( 'checked', to );
  507. },
  508. refresh: function() {
  509. return this.element.prop( 'checked' );
  510. }
  511. };
  512. api.Element.synchronizer.radio = {
  513. update: function( to ) {
  514. this.element.filter( function() {
  515. return this.value === to;
  516. }).prop( 'checked', true );
  517. },
  518. refresh: function() {
  519. return this.element.filter( ':checked' ).val();
  520. }
  521. };
  522. $.support.postMessage = !! window.postMessage;
  523. /**
  524. * A communicator for sending data from one window to another over postMessage.
  525. *
  526. * @constructor
  527. * @augments wp.customize.Class
  528. * @mixes wp.customize.Events
  529. */
  530. api.Messenger = api.Class.extend({
  531. /**
  532. * Create a new Value.
  533. *
  534. * @param {string} key Unique identifier.
  535. * @param {mixed} initial Initial value.
  536. * @param {mixed} options Options hash. Optional.
  537. * @return {Value} Class instance of the Value.
  538. */
  539. add: function( key, initial, options ) {
  540. return this[ key ] = new api.Value( initial, options );
  541. },
  542. /**
  543. * Initialize Messenger.
  544. *
  545. * @param {object} params - Parameters to configure the messenger.
  546. * {string} params.url - The URL to communicate with.
  547. * {window} params.targetWindow - The window instance to communicate with. Default window.parent.
  548. * {string} params.channel - If provided, will send the channel with each message and only accept messages a matching channel.
  549. * @param {object} options - Extend any instance parameter or method with this object.
  550. */
  551. initialize: function( params, options ) {
  552. // Target the parent frame by default, but only if a parent frame exists.
  553. var defaultTarget = window.parent === window ? null : window.parent;
  554. $.extend( this, options || {} );
  555. this.add( 'channel', params.channel );
  556. this.add( 'url', params.url || '' );
  557. this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
  558. var urlParser = document.createElement( 'a' );
  559. urlParser.href = to;
  560. // Port stripping needed by IE since it adds to host but not to event.origin.
  561. return urlParser.protocol + '//' + urlParser.host.replace( /:80$/, '' );
  562. });
  563. // first add with no value
  564. this.add( 'targetWindow', null );
  565. // This avoids SecurityErrors when setting a window object in x-origin iframe'd scenarios.
  566. this.targetWindow.set = function( to ) {
  567. var from = this._value;
  568. to = this._setter.apply( this, arguments );
  569. to = this.validate( to );
  570. if ( null === to || from === to ) {
  571. return this;
  572. }
  573. this._value = to;
  574. this._dirty = true;
  575. this.callbacks.fireWith( this, [ to, from ] );
  576. return this;
  577. };
  578. // now set it
  579. this.targetWindow( params.targetWindow || defaultTarget );
  580. // Since we want jQuery to treat the receive function as unique
  581. // to this instance, we give the function a new guid.
  582. //
  583. // This will prevent every Messenger's receive function from being
  584. // unbound when calling $.off( 'message', this.receive );
  585. this.receive = $.proxy( this.receive, this );
  586. this.receive.guid = $.guid++;
  587. $( window ).on( 'message', this.receive );
  588. },
  589. destroy: function() {
  590. $( window ).off( 'message', this.receive );
  591. },
  592. /**
  593. * Receive data from the other window.
  594. *
  595. * @param {jQuery.Event} event Event with embedded data.
  596. */
  597. receive: function( event ) {
  598. var message;
  599. event = event.originalEvent;
  600. if ( ! this.targetWindow || ! this.targetWindow() ) {
  601. return;
  602. }
  603. // Check to make sure the origin is valid.
  604. if ( this.origin() && event.origin !== this.origin() )
  605. return;
  606. // Ensure we have a string that's JSON.parse-able
  607. if ( typeof event.data !== 'string' || event.data[0] !== '{' ) {
  608. return;
  609. }
  610. message = JSON.parse( event.data );
  611. // Check required message properties.
  612. if ( ! message || ! message.id || typeof message.data === 'undefined' )
  613. return;
  614. // Check if channel names match.
  615. if ( ( message.channel || this.channel() ) && this.channel() !== message.channel )
  616. return;
  617. this.trigger( message.id, message.data );
  618. },
  619. /**
  620. * Send data to the other window.
  621. *
  622. * @param {string} id The event name.
  623. * @param {object} data Data.
  624. */
  625. send: function( id, data ) {
  626. var message;
  627. data = typeof data === 'undefined' ? null : data;
  628. if ( ! this.url() || ! this.targetWindow() )
  629. return;
  630. message = { id: id, data: data };
  631. if ( this.channel() )
  632. message.channel = this.channel();
  633. this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
  634. }
  635. });
  636. // Add the Events mixin to api.Messenger.
  637. $.extend( api.Messenger.prototype, api.Events );
  638. /**
  639. * Notification.
  640. *
  641. * @class
  642. * @augments wp.customize.Class
  643. * @since 4.6.0
  644. *
  645. * @param {string} code - The error code.
  646. * @param {object} params - Params.
  647. * @param {string} params.message=null - The error message.
  648. * @param {string} [params.type=error] - The notification type.
  649. * @param {boolean} [params.fromServer=false] - Whether the notification was server-sent.
  650. * @param {string} [params.setting=null] - The setting ID that the notification is related to.
  651. * @param {*} [params.data=null] - Any additional data.
  652. */
  653. api.Notification = api.Class.extend({
  654. initialize: function( code, params ) {
  655. var _params;
  656. this.code = code;
  657. _params = _.extend(
  658. {
  659. message: null,
  660. type: 'error',
  661. fromServer: false,
  662. data: null,
  663. setting: null
  664. },
  665. params
  666. );
  667. delete _params.code;
  668. _.extend( this, _params );
  669. }
  670. });
  671. // The main API object is also a collection of all customizer settings.
  672. api = $.extend( new api.Values(), api );
  673. /**
  674. * Get all customize settings.
  675. *
  676. * @return {object}
  677. */
  678. api.get = function() {
  679. var result = {};
  680. this.each( function( obj, key ) {
  681. result[ key ] = obj.get();
  682. });
  683. return result;
  684. };
  685. /**
  686. * Utility function namespace
  687. */
  688. api.utils = {};
  689. /**
  690. * Parse query string.
  691. *
  692. * @since 4.7.0
  693. * @access public
  694. *
  695. * @param {string} queryString Query string.
  696. * @returns {object} Parsed query string.
  697. */
  698. api.utils.parseQueryString = function parseQueryString( queryString ) {
  699. var queryParams = {};
  700. _.each( queryString.split( '&' ), function( pair ) {
  701. var parts, key, value;
  702. parts = pair.split( '=', 2 );
  703. if ( ! parts[0] ) {
  704. return;
  705. }
  706. key = decodeURIComponent( parts[0].replace( /\+/g, ' ' ) );
  707. key = key.replace( / /g, '_' ); // What PHP does.
  708. if ( _.isUndefined( parts[1] ) ) {
  709. value = null;
  710. } else {
  711. value = decodeURIComponent( parts[1].replace( /\+/g, ' ' ) );
  712. }
  713. queryParams[ key ] = value;
  714. } );
  715. return queryParams;
  716. };
  717. // Expose the API publicly on window.wp.customize
  718. exports.customize = api;
  719. })( wp, jQuery );