PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/js/wp-api.js

https://bitbucket.org/stephenharris/stephenharris
JavaScript | 1395 lines | 752 code | 244 blank | 399 comment | 161 complexity | 3b8c124f3009a102041cb7cc70474ed8 MD5 | raw file
  1. (function( window, undefined ) {
  2. 'use strict';
  3. /**
  4. * Initialise the WP_API.
  5. */
  6. function WP_API() {
  7. this.models = {};
  8. this.collections = {};
  9. this.views = {};
  10. }
  11. window.wp = window.wp || {};
  12. wp.api = wp.api || new WP_API();
  13. wp.api.versionString = wp.api.versionString || 'wp/v2/';
  14. // Alias _includes to _.contains, ensuring it is available if lodash is used.
  15. if ( ! _.isFunction( _.includes ) && _.isFunction( _.contains ) ) {
  16. _.includes = _.contains;
  17. }
  18. })( window );
  19. (function( window, undefined ) {
  20. 'use strict';
  21. var pad, r;
  22. window.wp = window.wp || {};
  23. wp.api = wp.api || {};
  24. wp.api.utils = wp.api.utils || {};
  25. /**
  26. * ECMAScript 5 shim, adapted from MDN.
  27. * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
  28. */
  29. if ( ! Date.prototype.toISOString ) {
  30. pad = function( number ) {
  31. r = String( number );
  32. if ( 1 === r.length ) {
  33. r = '0' + r;
  34. }
  35. return r;
  36. };
  37. Date.prototype.toISOString = function() {
  38. return this.getUTCFullYear() +
  39. '-' + pad( this.getUTCMonth() + 1 ) +
  40. '-' + pad( this.getUTCDate() ) +
  41. 'T' + pad( this.getUTCHours() ) +
  42. ':' + pad( this.getUTCMinutes() ) +
  43. ':' + pad( this.getUTCSeconds() ) +
  44. '.' + String( ( this.getUTCMilliseconds() / 1000 ).toFixed( 3 ) ).slice( 2, 5 ) +
  45. 'Z';
  46. };
  47. }
  48. /**
  49. * Parse date into ISO8601 format.
  50. *
  51. * @param {Date} date.
  52. */
  53. wp.api.utils.parseISO8601 = function( date ) {
  54. var timestamp, struct, i, k,
  55. minutesOffset = 0,
  56. numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
  57. // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
  58. // before falling back to any implementation-specific date parsing, so that’s what we do, even if native
  59. // implementations could be faster.
  60. // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
  61. if ( ( struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec( date ) ) ) {
  62. // Avoid NaN timestamps caused by “undefined” values being passed to Date.UTC.
  63. for ( i = 0; ( k = numericKeys[i] ); ++i ) {
  64. struct[k] = +struct[k] || 0;
  65. }
  66. // Allow undefined days and months.
  67. struct[2] = ( +struct[2] || 1 ) - 1;
  68. struct[3] = +struct[3] || 1;
  69. if ( 'Z' !== struct[8] && undefined !== struct[9] ) {
  70. minutesOffset = struct[10] * 60 + struct[11];
  71. if ( '+' === struct[9] ) {
  72. minutesOffset = 0 - minutesOffset;
  73. }
  74. }
  75. timestamp = Date.UTC( struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7] );
  76. } else {
  77. timestamp = Date.parse ? Date.parse( date ) : NaN;
  78. }
  79. return timestamp;
  80. };
  81. /**
  82. * Helper function for getting the root URL.
  83. * @return {[type]} [description]
  84. */
  85. wp.api.utils.getRootUrl = function() {
  86. return window.location.origin ?
  87. window.location.origin + '/' :
  88. window.location.protocol + '/' + window.location.host + '/';
  89. };
  90. /**
  91. * Helper for capitalizing strings.
  92. */
  93. wp.api.utils.capitalize = function( str ) {
  94. if ( _.isUndefined( str ) ) {
  95. return str;
  96. }
  97. return str.charAt( 0 ).toUpperCase() + str.slice( 1 );
  98. };
  99. /**
  100. * Helper function that capitalizes the first word and camel cases any words starting
  101. * after dashes, removing the dashes.
  102. */
  103. wp.api.utils.capitalizeAndCamelCaseDashes = function( str ) {
  104. if ( _.isUndefined( str ) ) {
  105. return str;
  106. }
  107. str = wp.api.utils.capitalize( str );
  108. return wp.api.utils.camelCaseDashes( str );
  109. };
  110. /**
  111. * Helper function to camel case the letter after dashes, removing the dashes.
  112. */
  113. wp.api.utils.camelCaseDashes = function( str ) {
  114. return str.replace( /-([a-z])/g, function( g ) {
  115. return g[ 1 ].toUpperCase();
  116. } );
  117. };
  118. /**
  119. * Extract a route part based on negative index.
  120. *
  121. * @param {string} route The endpoint route.
  122. * @param {int} part The number of parts from the end of the route to retrieve. Default 1.
  123. * Example route `/a/b/c`: part 1 is `c`, part 2 is `b`, part 3 is `a`.
  124. * @param {string} [versionString] Version string, defaults to `wp.api.versionString`.
  125. * @param {boolean} [reverse] Whether to reverse the order when extracting the route part. Optional, default false.
  126. */
  127. wp.api.utils.extractRoutePart = function( route, part, versionString, reverse ) {
  128. var routeParts;
  129. part = part || 1;
  130. versionString = versionString || wp.api.versionString;
  131. // Remove versions string from route to avoid returning it.
  132. if ( 0 === route.indexOf( '/' + versionString ) ) {
  133. route = route.substr( versionString.length + 1 );
  134. }
  135. routeParts = route.split( '/' );
  136. if ( reverse ) {
  137. routeParts = routeParts.reverse();
  138. }
  139. if ( _.isUndefined( routeParts[ --part ] ) ) {
  140. return '';
  141. }
  142. return routeParts[ part ];
  143. };
  144. /**
  145. * Extract a parent name from a passed route.
  146. *
  147. * @param {string} route The route to extract a name from.
  148. */
  149. wp.api.utils.extractParentName = function( route ) {
  150. var name,
  151. lastSlash = route.lastIndexOf( '_id>[\\d]+)/' );
  152. if ( lastSlash < 0 ) {
  153. return '';
  154. }
  155. name = route.substr( 0, lastSlash - 1 );
  156. name = name.split( '/' );
  157. name.pop();
  158. name = name.pop();
  159. return name;
  160. };
  161. /**
  162. * Add args and options to a model prototype from a route's endpoints.
  163. *
  164. * @param {array} routeEndpoints Array of route endpoints.
  165. * @param {Object} modelInstance An instance of the model (or collection)
  166. * to add the args to.
  167. */
  168. wp.api.utils.decorateFromRoute = function( routeEndpoints, modelInstance ) {
  169. /**
  170. * Build the args based on route endpoint data.
  171. */
  172. _.each( routeEndpoints, function( routeEndpoint ) {
  173. // Add post and edit endpoints as model args.
  174. if ( _.includes( routeEndpoint.methods, 'POST' ) || _.includes( routeEndpoint.methods, 'PUT' ) ) {
  175. // Add any non empty args, merging them into the args object.
  176. if ( ! _.isEmpty( routeEndpoint.args ) ) {
  177. // Set as default if no args yet.
  178. if ( _.isEmpty( modelInstance.prototype.args ) ) {
  179. modelInstance.prototype.args = routeEndpoint.args;
  180. } else {
  181. // We already have args, merge these new args in.
  182. modelInstance.prototype.args = _.extend( modelInstance.prototype.args, routeEndpoint.args );
  183. }
  184. }
  185. } else {
  186. // Add GET method as model options.
  187. if ( _.includes( routeEndpoint.methods, 'GET' ) ) {
  188. // Add any non empty args, merging them into the defaults object.
  189. if ( ! _.isEmpty( routeEndpoint.args ) ) {
  190. // Set as default if no defaults yet.
  191. if ( _.isEmpty( modelInstance.prototype.options ) ) {
  192. modelInstance.prototype.options = routeEndpoint.args;
  193. } else {
  194. // We already have options, merge these new args in.
  195. modelInstance.prototype.options = _.extend( modelInstance.prototype.options, routeEndpoint.args );
  196. }
  197. }
  198. }
  199. }
  200. } );
  201. };
  202. /**
  203. * Add mixins and helpers to models depending on their defaults.
  204. *
  205. * @param {Backbone Model} model The model to attach helpers and mixins to.
  206. * @param {string} modelClassName The classname of the constructed model.
  207. * @param {Object} loadingObjects An object containing the models and collections we are building.
  208. */
  209. wp.api.utils.addMixinsAndHelpers = function( model, modelClassName, loadingObjects ) {
  210. var hasDate = false,
  211. /**
  212. * Array of parseable dates.
  213. *
  214. * @type {string[]}.
  215. */
  216. parseableDates = [ 'date', 'modified', 'date_gmt', 'modified_gmt' ],
  217. /**
  218. * Mixin for all content that is time stamped.
  219. *
  220. * This mixin converts between mysql timestamps and JavaScript Dates when syncing a model
  221. * to or from the server. For example, a date stored as `2015-12-27T21:22:24` on the server
  222. * gets expanded to `Sun Dec 27 2015 14:22:24 GMT-0700 (MST)` when the model is fetched.
  223. *
  224. * @type {{toJSON: toJSON, parse: parse}}.
  225. */
  226. TimeStampedMixin = {
  227. /**
  228. * Prepare a JavaScript Date for transmitting to the server.
  229. *
  230. * This helper function accepts a field and Date object. It converts the passed Date
  231. * to an ISO string and sets that on the model field.
  232. *
  233. * @param {Date} date A JavaScript date object. WordPress expects dates in UTC.
  234. * @param {string} field The date field to set. One of 'date', 'date_gmt', 'date_modified'
  235. * or 'date_modified_gmt'. Optional, defaults to 'date'.
  236. */
  237. setDate: function( date, field ) {
  238. var theField = field || 'date';
  239. // Don't alter non parsable date fields.
  240. if ( _.indexOf( parseableDates, theField ) < 0 ) {
  241. return false;
  242. }
  243. this.set( theField, date.toISOString() );
  244. },
  245. /**
  246. * Get a JavaScript Date from the passed field.
  247. *
  248. * WordPress returns 'date' and 'date_modified' in the timezone of the server as well as
  249. * UTC dates as 'date_gmt' and 'date_modified_gmt'. Draft posts do not include UTC dates.
  250. *
  251. * @param {string} field The date field to set. One of 'date', 'date_gmt', 'date_modified'
  252. * or 'date_modified_gmt'. Optional, defaults to 'date'.
  253. */
  254. getDate: function( field ) {
  255. var theField = field || 'date',
  256. theISODate = this.get( theField );
  257. // Only get date fields and non null values.
  258. if ( _.indexOf( parseableDates, theField ) < 0 || _.isNull( theISODate ) ) {
  259. return false;
  260. }
  261. return new Date( wp.api.utils.parseISO8601( theISODate ) );
  262. }
  263. },
  264. /**
  265. * Build a helper function to retrieve related model.
  266. *
  267. * @param {string} parentModel The parent model.
  268. * @param {int} modelId The model ID if the object to request
  269. * @param {string} modelName The model name to use when constructing the model.
  270. * @param {string} embedSourcePoint Where to check the embedds object for _embed data.
  271. * @param {string} embedCheckField Which model field to check to see if the model has data.
  272. *
  273. * @return {Deferred.promise} A promise which resolves to the constructed model.
  274. */
  275. buildModelGetter = function( parentModel, modelId, modelName, embedSourcePoint, embedCheckField ) {
  276. var getModel, embeddeds, attributes, deferred;
  277. deferred = jQuery.Deferred();
  278. embeddeds = parentModel.get( '_embedded' ) || {};
  279. // Verify that we have a valid object id.
  280. if ( ! _.isNumber( modelId ) || 0 === modelId ) {
  281. deferred.reject();
  282. return deferred;
  283. }
  284. // If we have embedded object data, use that when constructing the getModel.
  285. if ( embeddeds[ embedSourcePoint ] ) {
  286. attributes = _.findWhere( embeddeds[ embedSourcePoint ], { id: modelId } );
  287. }
  288. // Otherwise use the modelId.
  289. if ( ! attributes ) {
  290. attributes = { id: modelId };
  291. }
  292. // Create the new getModel model.
  293. getModel = new wp.api.models[ modelName ]( attributes );
  294. if ( ! getModel.get( embedCheckField ) ) {
  295. getModel.fetch( {
  296. success: function( getModel ) {
  297. deferred.resolve( getModel );
  298. },
  299. error: function( getModel, response ) {
  300. deferred.reject( response );
  301. }
  302. } );
  303. } else {
  304. // Resolve with the embedded model.
  305. deferred.resolve( getModel );
  306. }
  307. // Return a promise.
  308. return deferred.promise();
  309. },
  310. /**
  311. * Build a helper to retrieve a collection.
  312. *
  313. * @param {string} parentModel The parent model.
  314. * @param {string} collectionName The name to use when constructing the collection.
  315. * @param {string} embedSourcePoint Where to check the embedds object for _embed data.
  316. * @param {string} embedIndex An addiitonal optional index for the _embed data.
  317. *
  318. * @return {Deferred.promise} A promise which resolves to the constructed collection.
  319. */
  320. buildCollectionGetter = function( parentModel, collectionName, embedSourcePoint, embedIndex ) {
  321. /**
  322. * Returns a promise that resolves to the requested collection
  323. *
  324. * Uses the embedded data if available, otherwises fetches the
  325. * data from the server.
  326. *
  327. * @return {Deferred.promise} promise Resolves to a wp.api.collections[ collectionName ]
  328. * collection.
  329. */
  330. var postId, embeddeds, getObjects,
  331. classProperties = '',
  332. properties = '',
  333. deferred = jQuery.Deferred();
  334. postId = parentModel.get( 'id' );
  335. embeddeds = parentModel.get( '_embedded' ) || {};
  336. // Verify that we have a valid post id.
  337. if ( ! _.isNumber( postId ) || 0 === postId ) {
  338. deferred.reject();
  339. return deferred;
  340. }
  341. // If we have embedded getObjects data, use that when constructing the getObjects.
  342. if ( ! _.isUndefined( embedSourcePoint ) && ! _.isUndefined( embeddeds[ embedSourcePoint ] ) ) {
  343. // Some embeds also include an index offset, check for that.
  344. if ( _.isUndefined( embedIndex ) ) {
  345. // Use the embed source point directly.
  346. properties = embeddeds[ embedSourcePoint ];
  347. } else {
  348. // Add the index to the embed source point.
  349. properties = embeddeds[ embedSourcePoint ][ embedIndex ];
  350. }
  351. } else {
  352. // Otherwise use the postId.
  353. classProperties = { parent: postId };
  354. }
  355. // Create the new getObjects collection.
  356. getObjects = new wp.api.collections[ collectionName ]( properties, classProperties );
  357. // If we didn’t have embedded getObjects, fetch the getObjects data.
  358. if ( _.isUndefined( getObjects.models[0] ) ) {
  359. getObjects.fetch( {
  360. success: function( getObjects ) {
  361. // Add a helper 'parent_post' attribute onto the model.
  362. setHelperParentPost( getObjects, postId );
  363. deferred.resolve( getObjects );
  364. },
  365. error: function( getModel, response ) {
  366. deferred.reject( response );
  367. }
  368. } );
  369. } else {
  370. // Add a helper 'parent_post' attribute onto the model.
  371. setHelperParentPost( getObjects, postId );
  372. deferred.resolve( getObjects );
  373. }
  374. // Return a promise.
  375. return deferred.promise();
  376. },
  377. /**
  378. * Set the model post parent.
  379. */
  380. setHelperParentPost = function( collection, postId ) {
  381. // Attach post_parent id to the collection.
  382. _.each( collection.models, function( model ) {
  383. model.set( 'parent_post', postId );
  384. } );
  385. },
  386. /**
  387. * Add a helper function to handle post Meta.
  388. */
  389. MetaMixin = {
  390. getMeta: function() {
  391. return buildCollectionGetter( this, 'PostMeta', 'https://api.w.org/meta' );
  392. }
  393. },
  394. /**
  395. * Add a helper function to handle post Revisions.
  396. */
  397. RevisionsMixin = {
  398. getRevisions: function() {
  399. return buildCollectionGetter( this, 'PostRevisions' );
  400. }
  401. },
  402. /**
  403. * Add a helper function to handle post Tags.
  404. */
  405. TagsMixin = {
  406. /**
  407. * Get the tags for a post.
  408. *
  409. * @return {Deferred.promise} promise Resolves to an array of tags.
  410. */
  411. getTags: function() {
  412. var tagIds = this.get( 'tags' ),
  413. tags = new wp.api.collections.Tags();
  414. // Resolve with an empty array if no tags.
  415. if ( _.isEmpty( tagIds ) ) {
  416. return jQuery.Deferred().resolve( [] );
  417. }
  418. return tags.fetch( { data: { include: tagIds } } );
  419. },
  420. /**
  421. * Set the tags for a post.
  422. *
  423. * Accepts an array of tag slugs, or a Tags collection.
  424. *
  425. * @param {array|Backbone.Collection} tags The tags to set on the post.
  426. *
  427. */
  428. setTags: function( tags ) {
  429. var allTags, newTag,
  430. self = this,
  431. newTags = [];
  432. if ( _.isString( tags ) ) {
  433. return false;
  434. }
  435. // If this is an array of slugs, build a collection.
  436. if ( _.isArray( tags ) ) {
  437. // Get all the tags.
  438. allTags = new wp.api.collections.Tags();
  439. allTags.fetch( {
  440. data: { per_page: 100 },
  441. success: function( alltags ) {
  442. // Find the passed tags and set them up.
  443. _.each( tags, function( tag ) {
  444. newTag = new wp.api.models.Tag( alltags.findWhere( { slug: tag } ) );
  445. // Tie the new tag to the post.
  446. newTag.set( 'parent_post', self.get( 'id' ) );
  447. // Add the new tag to the collection.
  448. newTags.push( newTag );
  449. } );
  450. tags = new wp.api.collections.Tags( newTags );
  451. self.setTagsWithCollection( tags );
  452. }
  453. } );
  454. } else {
  455. this.setTagsWithCollection( tags );
  456. }
  457. },
  458. /**
  459. * Set the tags for a post.
  460. *
  461. * Accepts a Tags collection.
  462. *
  463. * @param {array|Backbone.Collection} tags The tags to set on the post.
  464. *
  465. */
  466. setTagsWithCollection: function( tags ) {
  467. // Pluck out the category ids.
  468. this.set( 'tags', tags.pluck( 'id' ) );
  469. return this.save();
  470. }
  471. },
  472. /**
  473. * Add a helper function to handle post Categories.
  474. */
  475. CategoriesMixin = {
  476. /**
  477. * Get a the categories for a post.
  478. *
  479. * @return {Deferred.promise} promise Resolves to an array of categories.
  480. */
  481. getCategories: function() {
  482. var categoryIds = this.get( 'categories' ),
  483. categories = new wp.api.collections.Categories();
  484. // Resolve with an empty array if no categories.
  485. if ( _.isEmpty( categoryIds ) ) {
  486. return jQuery.Deferred().resolve( [] );
  487. }
  488. return categories.fetch( { data: { include: categoryIds } } );
  489. },
  490. /**
  491. * Set the categories for a post.
  492. *
  493. * Accepts an array of category slugs, or a Categories collection.
  494. *
  495. * @param {array|Backbone.Collection} categories The categories to set on the post.
  496. *
  497. */
  498. setCategories: function( categories ) {
  499. var allCategories, newCategory,
  500. self = this,
  501. newCategories = [];
  502. if ( _.isString( categories ) ) {
  503. return false;
  504. }
  505. // If this is an array of slugs, build a collection.
  506. if ( _.isArray( categories ) ) {
  507. // Get all the categories.
  508. allCategories = new wp.api.collections.Categories();
  509. allCategories.fetch( {
  510. data: { per_page: 100 },
  511. success: function( allcats ) {
  512. // Find the passed categories and set them up.
  513. _.each( categories, function( category ) {
  514. newCategory = new wp.api.models.Category( allcats.findWhere( { slug: category } ) );
  515. // Tie the new category to the post.
  516. newCategory.set( 'parent_post', self.get( 'id' ) );
  517. // Add the new category to the collection.
  518. newCategories.push( newCategory );
  519. } );
  520. categories = new wp.api.collections.Categories( newCategories );
  521. self.setCategoriesWithCollection( categories );
  522. }
  523. } );
  524. } else {
  525. this.setCategoriesWithCollection( categories );
  526. }
  527. },
  528. /**
  529. * Set the categories for a post.
  530. *
  531. * Accepts Categories collection.
  532. *
  533. * @param {array|Backbone.Collection} categories The categories to set on the post.
  534. *
  535. */
  536. setCategoriesWithCollection: function( categories ) {
  537. // Pluck out the category ids.
  538. this.set( 'categories', categories.pluck( 'id' ) );
  539. return this.save();
  540. }
  541. },
  542. /**
  543. * Add a helper function to retrieve the author user model.
  544. */
  545. AuthorMixin = {
  546. getAuthorUser: function() {
  547. return buildModelGetter( this, this.get( 'author' ), 'User', 'author', 'name' );
  548. }
  549. },
  550. /**
  551. * Add a helper function to retrieve the featured media.
  552. */
  553. FeaturedMediaMixin = {
  554. getFeaturedMedia: function() {
  555. return buildModelGetter( this, this.get( 'featured_media' ), 'Media', 'wp:featuredmedia', 'source_url' );
  556. }
  557. };
  558. // Exit if we don't have valid model defaults.
  559. if ( _.isUndefined( model.prototype.args ) ) {
  560. return model;
  561. }
  562. // Go thru the parsable date fields, if our model contains any of them it gets the TimeStampedMixin.
  563. _.each( parseableDates, function( theDateKey ) {
  564. if ( ! _.isUndefined( model.prototype.args[ theDateKey ] ) ) {
  565. hasDate = true;
  566. }
  567. } );
  568. // Add the TimeStampedMixin for models that contain a date field.
  569. if ( hasDate ) {
  570. model = model.extend( TimeStampedMixin );
  571. }
  572. // Add the AuthorMixin for models that contain an author.
  573. if ( ! _.isUndefined( model.prototype.args.author ) ) {
  574. model = model.extend( AuthorMixin );
  575. }
  576. // Add the FeaturedMediaMixin for models that contain a featured_media.
  577. if ( ! _.isUndefined( model.prototype.args.featured_media ) ) {
  578. model = model.extend( FeaturedMediaMixin );
  579. }
  580. // Add the CategoriesMixin for models that support categories collections.
  581. if ( ! _.isUndefined( model.prototype.args.categories ) ) {
  582. model = model.extend( CategoriesMixin );
  583. }
  584. // Add the MetaMixin for models that support meta collections.
  585. if ( ! _.isUndefined( loadingObjects.collections[ modelClassName + 'Meta' ] ) ) {
  586. model = model.extend( MetaMixin );
  587. }
  588. // Add the TagsMixin for models that support tags collections.
  589. if ( ! _.isUndefined( model.prototype.args.tags ) ) {
  590. model = model.extend( TagsMixin );
  591. }
  592. // Add the RevisionsMixin for models that support revisions collections.
  593. if ( ! _.isUndefined( loadingObjects.collections[ modelClassName + 'Revisions' ] ) ) {
  594. model = model.extend( RevisionsMixin );
  595. }
  596. return model;
  597. };
  598. })( window );
  599. /* global wpApiSettings:false */
  600. // Suppress warning about parse function's unused "options" argument:
  601. /* jshint unused:false */
  602. (function() {
  603. 'use strict';
  604. var wpApiSettings = window.wpApiSettings || {};
  605. /**
  606. * Backbone base model for all models.
  607. */
  608. wp.api.WPApiBaseModel = Backbone.Model.extend(
  609. /** @lends WPApiBaseModel.prototype */
  610. {
  611. /**
  612. * Set nonce header before every Backbone sync.
  613. *
  614. * @param {string} method.
  615. * @param {Backbone.Model} model.
  616. * @param {{beforeSend}, *} options.
  617. * @returns {*}.
  618. */
  619. sync: function( method, model, options ) {
  620. var beforeSend;
  621. options = options || {};
  622. // Remove date_gmt if null.
  623. if ( _.isNull( model.get( 'date_gmt' ) ) ) {
  624. model.unset( 'date_gmt' );
  625. }
  626. // Remove slug if empty.
  627. if ( _.isEmpty( model.get( 'slug' ) ) ) {
  628. model.unset( 'slug' );
  629. }
  630. if ( ! _.isUndefined( wpApiSettings.nonce ) && ! _.isNull( wpApiSettings.nonce ) ) {
  631. beforeSend = options.beforeSend;
  632. // @todo enable option for jsonp endpoints
  633. // options.dataType = 'jsonp';
  634. options.beforeSend = function( xhr ) {
  635. xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
  636. if ( beforeSend ) {
  637. return beforeSend.apply( this, arguments );
  638. }
  639. };
  640. }
  641. // Add '?force=true' to use delete method when required.
  642. if ( this.requireForceForDelete && 'delete' === method ) {
  643. model.url = model.url() + '?force=true';
  644. }
  645. return Backbone.sync( method, model, options );
  646. },
  647. /**
  648. * Save is only allowed when the PUT OR POST methods are available for the endpoint.
  649. */
  650. save: function( attrs, options ) {
  651. // Do we have the put method, then execute the save.
  652. if ( _.includes( this.methods, 'PUT' ) || _.includes( this.methods, 'POST' ) ) {
  653. // Proxy the call to the original save function.
  654. return Backbone.Model.prototype.save.call( this, attrs, options );
  655. } else {
  656. // Otherwise bail, disallowing action.
  657. return false;
  658. }
  659. },
  660. /**
  661. * Delete is only allowed when the DELETE method is available for the endpoint.
  662. */
  663. destroy: function( options ) {
  664. // Do we have the DELETE method, then execute the destroy.
  665. if ( _.includes( this.methods, 'DELETE' ) ) {
  666. // Proxy the call to the original save function.
  667. return Backbone.Model.prototype.destroy.call( this, options );
  668. } else {
  669. // Otherwise bail, disallowing action.
  670. return false;
  671. }
  672. }
  673. }
  674. );
  675. /**
  676. * API Schema model. Contains meta information about the API.
  677. */
  678. wp.api.models.Schema = wp.api.WPApiBaseModel.extend(
  679. /** @lends Schema.prototype */
  680. {
  681. defaults: {
  682. _links: {},
  683. namespace: null,
  684. routes: {}
  685. },
  686. initialize: function( attributes, options ) {
  687. var model = this;
  688. options = options || {};
  689. wp.api.WPApiBaseModel.prototype.initialize.call( model, attributes, options );
  690. model.apiRoot = options.apiRoot || wpApiSettings.root;
  691. model.versionString = options.versionString || wpApiSettings.versionString;
  692. },
  693. url: function() {
  694. return this.apiRoot + this.versionString;
  695. }
  696. }
  697. );
  698. })();
  699. ( function() {
  700. 'use strict';
  701. var wpApiSettings = window.wpApiSettings || {};
  702. /**
  703. * Contains basic collection functionality such as pagination.
  704. */
  705. wp.api.WPApiBaseCollection = Backbone.Collection.extend(
  706. /** @lends BaseCollection.prototype */
  707. {
  708. /**
  709. * Setup default state.
  710. */
  711. initialize: function( models, options ) {
  712. this.state = {
  713. data: {},
  714. currentPage: null,
  715. totalPages: null,
  716. totalObjects: null
  717. };
  718. if ( _.isUndefined( options ) ) {
  719. this.parent = '';
  720. } else {
  721. this.parent = options.parent;
  722. }
  723. },
  724. /**
  725. * Extend Backbone.Collection.sync to add nince and pagination support.
  726. *
  727. * Set nonce header before every Backbone sync.
  728. *
  729. * @param {string} method.
  730. * @param {Backbone.Model} model.
  731. * @param {{success}, *} options.
  732. * @returns {*}.
  733. */
  734. sync: function( method, model, options ) {
  735. var beforeSend, success,
  736. self = this;
  737. options = options || {};
  738. beforeSend = options.beforeSend;
  739. // If we have a localized nonce, pass that along with each sync.
  740. if ( 'undefined' !== typeof wpApiSettings.nonce ) {
  741. options.beforeSend = function( xhr ) {
  742. xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
  743. if ( beforeSend ) {
  744. return beforeSend.apply( self, arguments );
  745. }
  746. };
  747. }
  748. // When reading, add pagination data.
  749. if ( 'read' === method ) {
  750. if ( options.data ) {
  751. self.state.data = _.clone( options.data );
  752. delete self.state.data.page;
  753. } else {
  754. self.state.data = options.data = {};
  755. }
  756. if ( 'undefined' === typeof options.data.page ) {
  757. self.state.currentPage = null;
  758. self.state.totalPages = null;
  759. self.state.totalObjects = null;
  760. } else {
  761. self.state.currentPage = options.data.page - 1;
  762. }
  763. success = options.success;
  764. options.success = function( data, textStatus, request ) {
  765. if ( ! _.isUndefined( request ) ) {
  766. self.state.totalPages = parseInt( request.getResponseHeader( 'x-wp-totalpages' ), 10 );
  767. self.state.totalObjects = parseInt( request.getResponseHeader( 'x-wp-total' ), 10 );
  768. }
  769. if ( null === self.state.currentPage ) {
  770. self.state.currentPage = 1;
  771. } else {
  772. self.state.currentPage++;
  773. }
  774. if ( success ) {
  775. return success.apply( this, arguments );
  776. }
  777. };
  778. }
  779. // Continue by calling Bacckbone's sync.
  780. return Backbone.sync( method, model, options );
  781. },
  782. /**
  783. * Fetches the next page of objects if a new page exists.
  784. *
  785. * @param {data: {page}} options.
  786. * @returns {*}.
  787. */
  788. more: function( options ) {
  789. options = options || {};
  790. options.data = options.data || {};
  791. _.extend( options.data, this.state.data );
  792. if ( 'undefined' === typeof options.data.page ) {
  793. if ( ! this.hasMore() ) {
  794. return false;
  795. }
  796. if ( null === this.state.currentPage || this.state.currentPage <= 1 ) {
  797. options.data.page = 2;
  798. } else {
  799. options.data.page = this.state.currentPage + 1;
  800. }
  801. }
  802. return this.fetch( options );
  803. },
  804. /**
  805. * Returns true if there are more pages of objects available.
  806. *
  807. * @returns null|boolean.
  808. */
  809. hasMore: function() {
  810. if ( null === this.state.totalPages ||
  811. null === this.state.totalObjects ||
  812. null === this.state.currentPage ) {
  813. return null;
  814. } else {
  815. return ( this.state.currentPage < this.state.totalPages );
  816. }
  817. }
  818. }
  819. );
  820. } )();
  821. ( function() {
  822. 'use strict';
  823. var Endpoint, initializedDeferreds = {},
  824. wpApiSettings = window.wpApiSettings || {};
  825. window.wp = window.wp || {};
  826. wp.api = wp.api || {};
  827. // If wpApiSettings is unavailable, try the default.
  828. if ( _.isEmpty( wpApiSettings ) ) {
  829. wpApiSettings.root = window.location.origin + '/wp-json/';
  830. }
  831. Endpoint = Backbone.Model.extend( {
  832. defaults: {
  833. apiRoot: wpApiSettings.root,
  834. versionString: wp.api.versionString,
  835. schema: null,
  836. models: {},
  837. collections: {}
  838. },
  839. /**
  840. * Initialize the Endpoint model.
  841. */
  842. initialize: function() {
  843. var model = this, deferred;
  844. Backbone.Model.prototype.initialize.apply( model, arguments );
  845. deferred = jQuery.Deferred();
  846. model.schemaConstructed = deferred.promise();
  847. model.schemaModel = new wp.api.models.Schema( null, {
  848. apiRoot: model.get( 'apiRoot' ),
  849. versionString: model.get( 'versionString' )
  850. } );
  851. // When the model loads, resolve the promise.
  852. model.schemaModel.once( 'change', function() {
  853. model.constructFromSchema();
  854. deferred.resolve( model );
  855. } );
  856. if ( model.get( 'schema' ) ) {
  857. // Use schema supplied as model attribute.
  858. model.schemaModel.set( model.schemaModel.parse( model.get( 'schema' ) ) );
  859. } else if (
  860. ! _.isUndefined( sessionStorage ) &&
  861. ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) &&
  862. sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) )
  863. ) {
  864. // Used a cached copy of the schema model if available.
  865. model.schemaModel.set( model.schemaModel.parse( JSON.parse( sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) ) ) ) );
  866. } else {
  867. model.schemaModel.fetch( {
  868. /**
  869. * When the server returns the schema model data, store the data in a sessionCache so we don't
  870. * have to retrieve it again for this session. Then, construct the models and collections based
  871. * on the schema model data.
  872. */
  873. success: function( newSchemaModel ) {
  874. // Store a copy of the schema model in the session cache if available.
  875. if ( ! _.isUndefined( sessionStorage ) && ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) ) {
  876. try {
  877. sessionStorage.setItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ), JSON.stringify( newSchemaModel ) );
  878. } catch ( error ) {
  879. // Fail silently, fixes errors in safari private mode.
  880. }
  881. }
  882. },
  883. // Log the error condition.
  884. error: function( err ) {
  885. window.console.log( err );
  886. }
  887. } );
  888. }
  889. },
  890. constructFromSchema: function() {
  891. var routeModel = this, modelRoutes, collectionRoutes, schemaRoot, loadingObjects,
  892. /**
  893. * Set up the model and collection name mapping options. As the schema is built, the
  894. * model and collection names will be adjusted if they are found in the mapping object.
  895. *
  896. * Localizing a variable wpApiSettings.mapping will over-ride the default mapping options.
  897. *
  898. */
  899. mapping = wpApiSettings.mapping || {
  900. models: {
  901. 'Categories': 'Category',
  902. 'Comments': 'Comment',
  903. 'Pages': 'Page',
  904. 'PagesMeta': 'PageMeta',
  905. 'PagesRevisions': 'PageRevision',
  906. 'Posts': 'Post',
  907. 'PostsCategories': 'PostCategory',
  908. 'PostsRevisions': 'PostRevision',
  909. 'PostsTags': 'PostTag',
  910. 'Schema': 'Schema',
  911. 'Statuses': 'Status',
  912. 'Tags': 'Tag',
  913. 'Taxonomies': 'Taxonomy',
  914. 'Types': 'Type',
  915. 'Users': 'User'
  916. },
  917. collections: {
  918. 'PagesMeta': 'PageMeta',
  919. 'PagesRevisions': 'PageRevisions',
  920. 'PostsCategories': 'PostCategories',
  921. 'PostsMeta': 'PostMeta',
  922. 'PostsRevisions': 'PostRevisions',
  923. 'PostsTags': 'PostTags'
  924. }
  925. };
  926. /**
  927. * Iterate thru the routes, picking up models and collections to build. Builds two arrays,
  928. * one for models and one for collections.
  929. */
  930. modelRoutes = [];
  931. collectionRoutes = [];
  932. schemaRoot = routeModel.get( 'apiRoot' ).replace( wp.api.utils.getRootUrl(), '' );
  933. loadingObjects = {};
  934. /**
  935. * Tracking objects for models and collections.
  936. */
  937. loadingObjects.models = routeModel.get( 'models' );
  938. loadingObjects.collections = routeModel.get( 'collections' );
  939. _.each( routeModel.schemaModel.get( 'routes' ), function( route, index ) {
  940. // Skip the schema root if included in the schema.
  941. if ( index !== routeModel.get( ' versionString' ) &&
  942. index !== schemaRoot &&
  943. index !== ( '/' + routeModel.get( 'versionString' ).slice( 0, -1 ) )
  944. ) {
  945. // Single items end with a regex (or the special case 'me').
  946. if ( /(?:.*[+)]|\/me)$/.test( index ) ) {
  947. modelRoutes.push( { index: index, route: route } );
  948. } else {
  949. // Collections end in a name.
  950. collectionRoutes.push( { index: index, route: route } );
  951. }
  952. }
  953. } );
  954. /**
  955. * Construct the models.
  956. *
  957. * Base the class name on the route endpoint.
  958. */
  959. _.each( modelRoutes, function( modelRoute ) {
  960. // Extract the name and any parent from the route.
  961. var modelClassName,
  962. routeName = wp.api.utils.extractRoutePart( modelRoute.index, 2, routeModel.get( 'versionString' ), true ),
  963. parentName = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), false ),
  964. routeEnd = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), true );
  965. // Clear the parent part of the rouite if its actually the version string.
  966. if ( parentName === routeModel.get( 'versionString' ) ) {
  967. parentName = '';
  968. }
  969. // Handle the special case of the 'me' route.
  970. if ( 'me' === routeEnd ) {
  971. routeName = 'me';
  972. }
  973. // If the model has a parent in its route, add that to its class name.
  974. if ( '' !== parentName && parentName !== routeName ) {
  975. modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  976. modelClassName = mapping.models[ modelClassName ] || modelClassName;
  977. loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
  978. // Return a constructed url based on the parent and id.
  979. url: function() {
  980. var url =
  981. routeModel.get( 'apiRoot' ) +
  982. routeModel.get( 'versionString' ) +
  983. parentName + '/' +
  984. ( ( _.isUndefined( this.get( 'parent' ) ) || 0 === this.get( 'parent' ) ) ?
  985. ( _.isUndefined( this.get( 'parent_post' ) ) ? '' : this.get( 'parent_post' ) + '/' ) :
  986. this.get( 'parent' ) + '/' ) +
  987. routeName;
  988. if ( ! _.isUndefined( this.get( 'id' ) ) ) {
  989. url += '/' + this.get( 'id' );
  990. }
  991. return url;
  992. },
  993. // Include a reference to the original route object.
  994. route: modelRoute,
  995. // Include a reference to the original class name.
  996. name: modelClassName,
  997. // Include the array of route methods for easy reference.
  998. methods: modelRoute.route.methods,
  999. initialize: function( attributes, options ) {
  1000. wp.api.WPApiBaseModel.prototype.initialize.call( this, attributes, options );
  1001. /**
  1002. * Posts and pages support trashing, other types don't support a trash
  1003. * and require that you pass ?force=true to actually delete them.
  1004. *
  1005. * @todo we should be getting trashability from the Schema, not hard coding types here.
  1006. */
  1007. if (
  1008. 'Posts' !== this.name &&
  1009. 'Pages' !== this.name &&
  1010. _.includes( this.methods, 'DELETE' )
  1011. ) {
  1012. this.requireForceForDelete = true;
  1013. }
  1014. }
  1015. } );
  1016. } else {
  1017. // This is a model without a parent in its route
  1018. modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1019. modelClassName = mapping.models[ modelClassName ] || modelClassName;
  1020. loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
  1021. // Function that returns a constructed url based on the id.
  1022. url: function() {
  1023. var url = routeModel.get( 'apiRoot' ) +
  1024. routeModel.get( 'versionString' ) +
  1025. ( ( 'me' === routeName ) ? 'users/me' : routeName );
  1026. if ( ! _.isUndefined( this.get( 'id' ) ) ) {
  1027. url += '/' + this.get( 'id' );
  1028. }
  1029. return url;
  1030. },
  1031. // Include a reference to the original route object.
  1032. route: modelRoute,
  1033. // Include a reference to the original class name.
  1034. name: modelClassName,
  1035. // Include the array of route methods for easy reference.
  1036. methods: modelRoute.route.methods
  1037. } );
  1038. }
  1039. // Add defaults to the new model, pulled form the endpoint.
  1040. wp.api.utils.decorateFromRoute(
  1041. modelRoute.route.endpoints,
  1042. loadingObjects.models[ modelClassName ],
  1043. routeModel.get( 'versionString' )
  1044. );
  1045. } );
  1046. /**
  1047. * Construct the collections.
  1048. *
  1049. * Base the class name on the route endpoint.
  1050. */
  1051. _.each( collectionRoutes, function( collectionRoute ) {
  1052. // Extract the name and any parent from the route.
  1053. var collectionClassName, modelClassName,
  1054. routeName = collectionRoute.index.slice( collectionRoute.index.lastIndexOf( '/' ) + 1 ),
  1055. parentName = wp.api.utils.extractRoutePart( collectionRoute.index, 1, routeModel.get( 'versionString' ), false );
  1056. // If the collection has a parent in its route, add that to its class name.
  1057. if ( '' !== parentName && parentName !== routeName && routeModel.get( 'versionString' ) !== parentName ) {
  1058. collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1059. modelClassName = mapping.models[ collectionClassName ] || collectionClassName;
  1060. collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
  1061. loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
  1062. // Function that returns a constructed url passed on the parent.
  1063. url: function() {
  1064. return routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) +
  1065. parentName + '/' + this.parent + '/' +
  1066. routeName;
  1067. },
  1068. // Specify the model that this collection contains.
  1069. model: function( attrs, options ) {
  1070. return new loadingObjects.models[ modelClassName ]( attrs, options );
  1071. },
  1072. // Include a reference to the original class name.
  1073. name: collectionClassName,
  1074. // Include a reference to the original route object.
  1075. route: collectionRoute,
  1076. // Include the array of route methods for easy reference.
  1077. methods: collectionRoute.route.methods
  1078. } );
  1079. } else {
  1080. // This is a collection without a parent in its route.
  1081. collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1082. modelClassName = mapping.models[ collectionClassName ] || collectionClassName;
  1083. collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
  1084. loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
  1085. // For the url of a root level collection, use a string.
  1086. url: routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) + routeName,
  1087. // Specify the model that this collection contains.
  1088. model: function( attrs, options ) {
  1089. return new loadingObjects.models[ modelClassName ]( attrs, options );
  1090. },
  1091. // Include a reference to the original class name.
  1092. name: collectionClassName,
  1093. // Include a reference to the original route object.
  1094. route: collectionRoute,
  1095. // Include the array of route methods for easy reference.
  1096. methods: collectionRoute.route.methods
  1097. } );
  1098. }
  1099. // Add defaults to the new model, pulled form the endpoint.
  1100. wp.api.utils.decorateFromRoute( collectionRoute.route.endpoints, loadingObjects.collections[ collectionClassName ] );
  1101. } );
  1102. // Add mixins and helpers for each of the models.
  1103. _.each( loadingObjects.models, function( model, index ) {
  1104. loadingObjects.models[ index ] = wp.api.utils.addMixinsAndHelpers( model, index, loadingObjects );
  1105. } );
  1106. }
  1107. } );
  1108. wp.api.endpoints = new Backbone.Collection( {
  1109. model: Endpoint
  1110. } );
  1111. /**
  1112. * Initialize the wp-api, optionally passing the API root.
  1113. *
  1114. * @param {object} [args]
  1115. * @param {string} [args.apiRoot] The api root. Optional, defaults to wpApiSettings.root.
  1116. * @param {string} [args.versionString] The version string. Optional, defaults to wpApiSettings.root.
  1117. * @param {object} [args.schema] The schema. Optional, will be fetched from API if not provided.
  1118. */
  1119. wp.api.init = function( args ) {
  1120. var endpoint, attributes = {}, deferred, promise;
  1121. args = args || {};
  1122. attributes.apiRoot = args.apiRoot || wpApiSettings.root;
  1123. attributes.versionString = args.versionString || wpApiSettings.versionString;
  1124. attributes.schema = args.schema || null;
  1125. if ( ! attributes.schema && attributes.apiRoot === wpApiSettings.root && attributes.versionString === wpApiSettings.versionString ) {
  1126. attributes.schema = wpApiSettings.schema;
  1127. }
  1128. if ( ! initializedDeferreds[ attributes.apiRoot + attributes.versionString ] ) {
  1129. endpoint = wp.api.endpoints.findWhere( { apiRoot: attributes.apiRoot, versionString: attributes.versionString } );
  1130. if ( ! endpoint ) {
  1131. endpoint = new Endpoint( attributes );
  1132. wp.api.endpoints.add( endpoint );
  1133. }
  1134. deferred = jQuery.Deferred();
  1135. promise = deferred.promise();
  1136. endpoint.schemaConstructed.done( function( endpoint ) {
  1137. // Map the default endpoints, extending any already present items (including Schema model).
  1138. wp.api.models = _.extend( endpoint.get( 'models' ), wp.api.models );
  1139. wp.api.collections = _.extend( endpoint.get( 'collections' ), wp.api.collections );
  1140. deferred.resolveWith( wp.api, [ endpoint ] );
  1141. } );
  1142. initializedDeferreds[ attributes.apiRoot + attributes.versionString ] = promise;
  1143. }
  1144. return initializedDeferreds[ attributes.apiRoot + attributes.versionString ];
  1145. };
  1146. /**
  1147. * Construct the default endpoints and add to an endpoints collection.
  1148. */
  1149. // The wp.api.init function returns a promise that will resolve with the endpoint once it is ready.
  1150. wp.api.loadPromise = wp.api.init();
  1151. } )();