media-editor.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. /**
  2. * @output wp-includes/js/media-editor.js
  3. */
  4. /* global getUserSetting, tinymce, QTags */
  5. // WordPress, TinyMCE, and Media
  6. // -----------------------------
  7. (function($, _){
  8. /**
  9. * Stores the editors' `wp.media.controller.Frame` instances.
  10. *
  11. * @static
  12. */
  13. var workflows = {};
  14. /**
  15. * A helper mixin function to avoid truthy and falsey values being
  16. * passed as an input that expects booleans. If key is undefined in the map,
  17. * but has a default value, set it.
  18. *
  19. * @param {object} attrs Map of props from a shortcode or settings.
  20. * @param {string} key The key within the passed map to check for a value.
  21. * @returns {mixed|undefined} The original or coerced value of key within attrs
  22. */
  23. wp.media.coerce = function ( attrs, key ) {
  24. if ( _.isUndefined( attrs[ key ] ) && ! _.isUndefined( this.defaults[ key ] ) ) {
  25. attrs[ key ] = this.defaults[ key ];
  26. } else if ( 'true' === attrs[ key ] ) {
  27. attrs[ key ] = true;
  28. } else if ( 'false' === attrs[ key ] ) {
  29. attrs[ key ] = false;
  30. }
  31. return attrs[ key ];
  32. };
  33. /** @namespace wp.media.string */
  34. wp.media.string = {
  35. /**
  36. * Joins the `props` and `attachment` objects,
  37. * outputting the proper object format based on the
  38. * attachment's type.
  39. *
  40. * @param {Object} [props={}] Attachment details (align, link, size, etc).
  41. * @param {Object} attachment The attachment object, media version of Post.
  42. * @returns {Object} Joined props
  43. */
  44. props: function( props, attachment ) {
  45. var link, linkUrl, size, sizes,
  46. defaultProps = wp.media.view.settings.defaultProps;
  47. props = props ? _.clone( props ) : {};
  48. if ( attachment && attachment.type ) {
  49. props.type = attachment.type;
  50. }
  51. if ( 'image' === props.type ) {
  52. props = _.defaults( props || {}, {
  53. align: defaultProps.align || getUserSetting( 'align', 'none' ),
  54. size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ),
  55. url: '',
  56. classes: []
  57. });
  58. }
  59. // All attachment-specific settings follow.
  60. if ( ! attachment ) {
  61. return props;
  62. }
  63. props.title = props.title || attachment.title;
  64. link = props.link || defaultProps.link || getUserSetting( 'urlbutton', 'file' );
  65. if ( 'file' === link || 'embed' === link ) {
  66. linkUrl = attachment.url;
  67. } else if ( 'post' === link ) {
  68. linkUrl = attachment.link;
  69. } else if ( 'custom' === link ) {
  70. linkUrl = props.linkUrl;
  71. }
  72. props.linkUrl = linkUrl || '';
  73. // Format properties for images.
  74. if ( 'image' === attachment.type ) {
  75. props.classes.push( 'wp-image-' + attachment.id );
  76. sizes = attachment.sizes;
  77. size = sizes && sizes[ props.size ] ? sizes[ props.size ] : attachment;
  78. _.extend( props, _.pick( attachment, 'align', 'caption', 'alt' ), {
  79. width: size.width,
  80. height: size.height,
  81. src: size.url,
  82. captionId: 'attachment_' + attachment.id
  83. });
  84. } else if ( 'video' === attachment.type || 'audio' === attachment.type ) {
  85. _.extend( props, _.pick( attachment, 'title', 'type', 'icon', 'mime' ) );
  86. // Format properties for non-images.
  87. } else {
  88. props.title = props.title || attachment.filename;
  89. props.rel = props.rel || 'attachment wp-att-' + attachment.id;
  90. }
  91. return props;
  92. },
  93. /**
  94. * Create link markup that is suitable for passing to the editor
  95. *
  96. * @param {Object} props Attachment details (align, link, size, etc).
  97. * @param {Object} attachment The attachment object, media version of Post.
  98. * @returns {string} The link markup
  99. */
  100. link: function( props, attachment ) {
  101. var options;
  102. props = wp.media.string.props( props, attachment );
  103. options = {
  104. tag: 'a',
  105. content: props.title,
  106. attrs: {
  107. href: props.linkUrl
  108. }
  109. };
  110. if ( props.rel ) {
  111. options.attrs.rel = props.rel;
  112. }
  113. return wp.html.string( options );
  114. },
  115. /**
  116. * Create an Audio shortcode string that is suitable for passing to the editor
  117. *
  118. * @param {Object} props Attachment details (align, link, size, etc).
  119. * @param {Object} attachment The attachment object, media version of Post.
  120. * @returns {string} The audio shortcode
  121. */
  122. audio: function( props, attachment ) {
  123. return wp.media.string._audioVideo( 'audio', props, attachment );
  124. },
  125. /**
  126. * Create a Video shortcode string that is suitable for passing to the editor
  127. *
  128. * @param {Object} props Attachment details (align, link, size, etc).
  129. * @param {Object} attachment The attachment object, media version of Post.
  130. * @returns {string} The video shortcode
  131. */
  132. video: function( props, attachment ) {
  133. return wp.media.string._audioVideo( 'video', props, attachment );
  134. },
  135. /**
  136. * Helper function to create a media shortcode string
  137. *
  138. * @access private
  139. *
  140. * @param {string} type The shortcode tag name: 'audio' or 'video'.
  141. * @param {Object} props Attachment details (align, link, size, etc).
  142. * @param {Object} attachment The attachment object, media version of Post.
  143. * @returns {string} The media shortcode
  144. */
  145. _audioVideo: function( type, props, attachment ) {
  146. var shortcode, html, extension;
  147. props = wp.media.string.props( props, attachment );
  148. if ( props.link !== 'embed' )
  149. return wp.media.string.link( props );
  150. shortcode = {};
  151. if ( 'video' === type ) {
  152. if ( attachment.image && -1 === attachment.image.src.indexOf( attachment.icon ) ) {
  153. shortcode.poster = attachment.image.src;
  154. }
  155. if ( attachment.width ) {
  156. shortcode.width = attachment.width;
  157. }
  158. if ( attachment.height ) {
  159. shortcode.height = attachment.height;
  160. }
  161. }
  162. extension = attachment.filename.split('.').pop();
  163. if ( _.contains( wp.media.view.settings.embedExts, extension ) ) {
  164. shortcode[extension] = attachment.url;
  165. } else {
  166. // Render unsupported audio and video files as links.
  167. return wp.media.string.link( props );
  168. }
  169. html = wp.shortcode.string({
  170. tag: type,
  171. attrs: shortcode
  172. });
  173. return html;
  174. },
  175. /**
  176. * Create image markup, optionally with a link and/or wrapped in a caption shortcode,
  177. * that is suitable for passing to the editor
  178. *
  179. * @param {Object} props Attachment details (align, link, size, etc).
  180. * @param {Object} attachment The attachment object, media version of Post.
  181. * @returns {string}
  182. */
  183. image: function( props, attachment ) {
  184. var img = {},
  185. options, classes, shortcode, html;
  186. props.type = 'image';
  187. props = wp.media.string.props( props, attachment );
  188. classes = props.classes || [];
  189. img.src = ! _.isUndefined( attachment ) ? attachment.url : props.url;
  190. _.extend( img, _.pick( props, 'width', 'height', 'alt' ) );
  191. // Only assign the align class to the image if we're not printing
  192. // a caption, since the alignment is sent to the shortcode.
  193. if ( props.align && ! props.caption ) {
  194. classes.push( 'align' + props.align );
  195. }
  196. if ( props.size ) {
  197. classes.push( 'size-' + props.size );
  198. }
  199. img['class'] = _.compact( classes ).join(' ');
  200. // Generate `img` tag options.
  201. options = {
  202. tag: 'img',
  203. attrs: img,
  204. single: true
  205. };
  206. // Generate the `a` element options, if they exist.
  207. if ( props.linkUrl ) {
  208. options = {
  209. tag: 'a',
  210. attrs: {
  211. href: props.linkUrl
  212. },
  213. content: options
  214. };
  215. }
  216. html = wp.html.string( options );
  217. // Generate the caption shortcode.
  218. if ( props.caption ) {
  219. shortcode = {};
  220. if ( img.width ) {
  221. shortcode.width = img.width;
  222. }
  223. if ( props.captionId ) {
  224. shortcode.id = props.captionId;
  225. }
  226. if ( props.align ) {
  227. shortcode.align = 'align' + props.align;
  228. }
  229. html = wp.shortcode.string({
  230. tag: 'caption',
  231. attrs: shortcode,
  232. content: html + ' ' + props.caption
  233. });
  234. }
  235. return html;
  236. }
  237. };
  238. wp.media.embed = {
  239. coerce : wp.media.coerce,
  240. defaults : {
  241. url : '',
  242. width: '',
  243. height: ''
  244. },
  245. edit : function( data, isURL ) {
  246. var frame, props = {}, shortcode;
  247. if ( isURL ) {
  248. props.url = data.replace(/<[^>]+>/g, '');
  249. } else {
  250. shortcode = wp.shortcode.next( 'embed', data ).shortcode;
  251. props = _.defaults( shortcode.attrs.named, this.defaults );
  252. if ( shortcode.content ) {
  253. props.url = shortcode.content;
  254. }
  255. }
  256. frame = wp.media({
  257. frame: 'post',
  258. state: 'embed',
  259. metadata: props
  260. });
  261. return frame;
  262. },
  263. shortcode : function( model ) {
  264. var self = this, content;
  265. _.each( this.defaults, function( value, key ) {
  266. model[ key ] = self.coerce( model, key );
  267. if ( value === model[ key ] ) {
  268. delete model[ key ];
  269. }
  270. });
  271. content = model.url;
  272. delete model.url;
  273. return new wp.shortcode({
  274. tag: 'embed',
  275. attrs: model,
  276. content: content
  277. });
  278. }
  279. };
  280. /**
  281. * @class wp.media.collection
  282. *
  283. * @param {Object} attributes
  284. */
  285. wp.media.collection = function(attributes) {
  286. var collections = {};
  287. return _.extend(/** @lends wp.media.collection.prototype */{
  288. coerce : wp.media.coerce,
  289. /**
  290. * Retrieve attachments based on the properties of the passed shortcode
  291. *
  292. * @param {wp.shortcode} shortcode An instance of wp.shortcode().
  293. * @returns {wp.media.model.Attachments} A Backbone.Collection containing
  294. * the media items belonging to a collection.
  295. * The query[ this.tag ] property is a Backbone.Model
  296. * containing the 'props' for the collection.
  297. */
  298. attachments: function( shortcode ) {
  299. var shortcodeString = shortcode.string(),
  300. result = collections[ shortcodeString ],
  301. attrs, args, query, others, self = this;
  302. delete collections[ shortcodeString ];
  303. if ( result ) {
  304. return result;
  305. }
  306. // Fill the default shortcode attributes.
  307. attrs = _.defaults( shortcode.attrs.named, this.defaults );
  308. args = _.pick( attrs, 'orderby', 'order' );
  309. args.type = this.type;
  310. args.perPage = -1;
  311. // Mark the `orderby` override attribute.
  312. if ( undefined !== attrs.orderby ) {
  313. attrs._orderByField = attrs.orderby;
  314. }
  315. if ( 'rand' === attrs.orderby ) {
  316. attrs._orderbyRandom = true;
  317. }
  318. // Map the `orderby` attribute to the corresponding model property.
  319. if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) ) {
  320. args.orderby = 'menuOrder';
  321. }
  322. // Map the `ids` param to the correct query args.
  323. if ( attrs.ids ) {
  324. args.post__in = attrs.ids.split(',');
  325. args.orderby = 'post__in';
  326. } else if ( attrs.include ) {
  327. args.post__in = attrs.include.split(',');
  328. }
  329. if ( attrs.exclude ) {
  330. args.post__not_in = attrs.exclude.split(',');
  331. }
  332. if ( ! args.post__in ) {
  333. args.uploadedTo = attrs.id;
  334. }
  335. // Collect the attributes that were not included in `args`.
  336. others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
  337. _.each( this.defaults, function( value, key ) {
  338. others[ key ] = self.coerce( others, key );
  339. });
  340. query = wp.media.query( args );
  341. query[ this.tag ] = new Backbone.Model( others );
  342. return query;
  343. },
  344. /**
  345. * Triggered when clicking 'Insert {label}' or 'Update {label}'
  346. *
  347. * @param {wp.media.model.Attachments} attachments A Backbone.Collection containing
  348. * the media items belonging to a collection.
  349. * The query[ this.tag ] property is a Backbone.Model
  350. * containing the 'props' for the collection.
  351. * @returns {wp.shortcode}
  352. */
  353. shortcode: function( attachments ) {
  354. var props = attachments.props.toJSON(),
  355. attrs = _.pick( props, 'orderby', 'order' ),
  356. shortcode, clone;
  357. if ( attachments.type ) {
  358. attrs.type = attachments.type;
  359. delete attachments.type;
  360. }
  361. if ( attachments[this.tag] ) {
  362. _.extend( attrs, attachments[this.tag].toJSON() );
  363. }
  364. // Convert all gallery shortcodes to use the `ids` property.
  365. // Ignore `post__in` and `post__not_in`; the attachments in
  366. // the collection will already reflect those properties.
  367. attrs.ids = attachments.pluck('id');
  368. // Copy the `uploadedTo` post ID.
  369. if ( props.uploadedTo ) {
  370. attrs.id = props.uploadedTo;
  371. }
  372. // Check if the gallery is randomly ordered.
  373. delete attrs.orderby;
  374. if ( attrs._orderbyRandom ) {
  375. attrs.orderby = 'rand';
  376. } else if ( attrs._orderByField && attrs._orderByField != 'rand' ) {
  377. attrs.orderby = attrs._orderByField;
  378. }
  379. delete attrs._orderbyRandom;
  380. delete attrs._orderByField;
  381. // If the `ids` attribute is set and `orderby` attribute
  382. // is the default value, clear it for cleaner output.
  383. if ( attrs.ids && 'post__in' === attrs.orderby ) {
  384. delete attrs.orderby;
  385. }
  386. attrs = this.setDefaults( attrs );
  387. shortcode = new wp.shortcode({
  388. tag: this.tag,
  389. attrs: attrs,
  390. type: 'single'
  391. });
  392. // Use a cloned version of the gallery.
  393. clone = new wp.media.model.Attachments( attachments.models, {
  394. props: props
  395. });
  396. clone[ this.tag ] = attachments[ this.tag ];
  397. collections[ shortcode.string() ] = clone;
  398. return shortcode;
  399. },
  400. /**
  401. * Triggered when double-clicking a collection shortcode placeholder
  402. * in the editor
  403. *
  404. * @param {string} content Content that is searched for possible
  405. * shortcode markup matching the passed tag name,
  406. *
  407. * @this wp.media.{prop}
  408. *
  409. * @returns {wp.media.view.MediaFrame.Select} A media workflow.
  410. */
  411. edit: function( content ) {
  412. var shortcode = wp.shortcode.next( this.tag, content ),
  413. defaultPostId = this.defaults.id,
  414. attachments, selection, state;
  415. // Bail if we didn't match the shortcode or all of the content.
  416. if ( ! shortcode || shortcode.content !== content ) {
  417. return;
  418. }
  419. // Ignore the rest of the match object.
  420. shortcode = shortcode.shortcode;
  421. if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) ) {
  422. shortcode.set( 'id', defaultPostId );
  423. }
  424. attachments = this.attachments( shortcode );
  425. selection = new wp.media.model.Selection( attachments.models, {
  426. props: attachments.props.toJSON(),
  427. multiple: true
  428. });
  429. selection[ this.tag ] = attachments[ this.tag ];
  430. // Fetch the query's attachments, and then break ties from the
  431. // query to allow for sorting.
  432. selection.more().done( function() {
  433. // Break ties with the query.
  434. selection.props.set({ query: false });
  435. selection.unmirror();
  436. selection.props.unset('orderby');
  437. });
  438. // Destroy the previous gallery frame.
  439. if ( this.frame ) {
  440. this.frame.dispose();
  441. }
  442. if ( shortcode.attrs.named.type && 'video' === shortcode.attrs.named.type ) {
  443. state = 'video-' + this.tag + '-edit';
  444. } else {
  445. state = this.tag + '-edit';
  446. }
  447. // Store the current frame.
  448. this.frame = wp.media({
  449. frame: 'post',
  450. state: state,
  451. title: this.editTitle,
  452. editing: true,
  453. multiple: true,
  454. selection: selection
  455. }).open();
  456. return this.frame;
  457. },
  458. setDefaults: function( attrs ) {
  459. var self = this;
  460. // Remove default attributes from the shortcode.
  461. _.each( this.defaults, function( value, key ) {
  462. attrs[ key ] = self.coerce( attrs, key );
  463. if ( value === attrs[ key ] ) {
  464. delete attrs[ key ];
  465. }
  466. });
  467. return attrs;
  468. }
  469. }, attributes );
  470. };
  471. wp.media._galleryDefaults = {
  472. itemtag: 'dl',
  473. icontag: 'dt',
  474. captiontag: 'dd',
  475. columns: '3',
  476. link: 'post',
  477. size: 'thumbnail',
  478. order: 'ASC',
  479. id: wp.media.view.settings.post && wp.media.view.settings.post.id,
  480. orderby : 'menu_order ID'
  481. };
  482. if ( wp.media.view.settings.galleryDefaults ) {
  483. wp.media.galleryDefaults = _.extend( {}, wp.media._galleryDefaults, wp.media.view.settings.galleryDefaults );
  484. } else {
  485. wp.media.galleryDefaults = wp.media._galleryDefaults;
  486. }
  487. wp.media.gallery = new wp.media.collection({
  488. tag: 'gallery',
  489. type : 'image',
  490. editTitle : wp.media.view.l10n.editGalleryTitle,
  491. defaults : wp.media.galleryDefaults,
  492. setDefaults: function( attrs ) {
  493. var self = this, changed = ! _.isEqual( wp.media.galleryDefaults, wp.media._galleryDefaults );
  494. _.each( this.defaults, function( value, key ) {
  495. attrs[ key ] = self.coerce( attrs, key );
  496. if ( value === attrs[ key ] && ( ! changed || value === wp.media._galleryDefaults[ key ] ) ) {
  497. delete attrs[ key ];
  498. }
  499. } );
  500. return attrs;
  501. }
  502. });
  503. /**
  504. * @namespace wp.media.featuredImage
  505. * @memberOf wp.media
  506. */
  507. wp.media.featuredImage = {
  508. /**
  509. * Get the featured image post ID
  510. *
  511. * @returns {wp.media.view.settings.post.featuredImageId|number}
  512. */
  513. get: function() {
  514. return wp.media.view.settings.post.featuredImageId;
  515. },
  516. /**
  517. * Sets the featured image ID property and sets the HTML in the post meta box to the new featured image.
  518. *
  519. * @param {number} id The post ID of the featured image, or -1 to unset it.
  520. */
  521. set: function( id ) {
  522. var settings = wp.media.view.settings;
  523. settings.post.featuredImageId = id;
  524. wp.media.post( 'get-post-thumbnail-html', {
  525. post_id: settings.post.id,
  526. thumbnail_id: settings.post.featuredImageId,
  527. _wpnonce: settings.post.nonce
  528. }).done( function( html ) {
  529. if ( html == '0' ) {
  530. window.alert( window.setPostThumbnailL10n.error );
  531. return;
  532. }
  533. $( '.inside', '#postimagediv' ).html( html );
  534. });
  535. },
  536. /**
  537. * Remove the featured image id, save the post thumbnail data and
  538. * set the HTML in the post meta box to no featured image.
  539. */
  540. remove: function() {
  541. wp.media.featuredImage.set( -1 );
  542. },
  543. /**
  544. * The Featured Image workflow
  545. *
  546. * @this wp.media.featuredImage
  547. *
  548. * @returns {wp.media.view.MediaFrame.Select} A media workflow.
  549. */
  550. frame: function() {
  551. if ( this._frame ) {
  552. wp.media.frame = this._frame;
  553. return this._frame;
  554. }
  555. this._frame = wp.media({
  556. state: 'featured-image',
  557. states: [ new wp.media.controller.FeaturedImage() , new wp.media.controller.EditImage() ]
  558. });
  559. this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
  560. /**
  561. * @this wp.media.view.MediaFrame.Select
  562. */
  563. this.createSelectToolbar( toolbar, {
  564. text: wp.media.view.l10n.setFeaturedImage
  565. });
  566. }, this._frame );
  567. this._frame.on( 'content:render:edit-image', function() {
  568. var selection = this.state('featured-image').get('selection'),
  569. view = new wp.media.view.EditImage( { model: selection.single(), controller: this } ).render();
  570. this.content.set( view );
  571. // after bringing in the frame, load the actual editor via an ajax call
  572. view.loadEditor();
  573. }, this._frame );
  574. this._frame.state('featured-image').on( 'select', this.select );
  575. return this._frame;
  576. },
  577. /**
  578. * 'select' callback for Featured Image workflow, triggered when
  579. * the 'Set Featured Image' button is clicked in the media modal.
  580. *
  581. * @this wp.media.controller.FeaturedImage
  582. */
  583. select: function() {
  584. var selection = this.get('selection').single();
  585. if ( ! wp.media.view.settings.post.featuredImageId ) {
  586. return;
  587. }
  588. wp.media.featuredImage.set( selection ? selection.id : -1 );
  589. },
  590. /**
  591. * Open the content media manager to the 'featured image' tab when
  592. * the post thumbnail is clicked.
  593. *
  594. * Update the featured image id when the 'remove' link is clicked.
  595. */
  596. init: function() {
  597. $('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) {
  598. event.preventDefault();
  599. // Stop propagation to prevent thickbox from activating.
  600. event.stopPropagation();
  601. wp.media.featuredImage.frame().open();
  602. }).on( 'click', '#remove-post-thumbnail', function() {
  603. wp.media.featuredImage.remove();
  604. return false;
  605. });
  606. }
  607. };
  608. $( wp.media.featuredImage.init );
  609. /** @namespace wp.media.editor */
  610. wp.media.editor = {
  611. /**
  612. * Send content to the editor
  613. *
  614. * @param {string} html Content to send to the editor
  615. */
  616. insert: function( html ) {
  617. var editor, wpActiveEditor,
  618. hasTinymce = ! _.isUndefined( window.tinymce ),
  619. hasQuicktags = ! _.isUndefined( window.QTags );
  620. if ( this.activeEditor ) {
  621. wpActiveEditor = window.wpActiveEditor = this.activeEditor;
  622. } else {
  623. wpActiveEditor = window.wpActiveEditor;
  624. }
  625. // Delegate to the global `send_to_editor` if it exists.
  626. // This attempts to play nice with any themes/plugins that have
  627. // overridden the insert functionality.
  628. if ( window.send_to_editor ) {
  629. return window.send_to_editor.apply( this, arguments );
  630. }
  631. if ( ! wpActiveEditor ) {
  632. if ( hasTinymce && tinymce.activeEditor ) {
  633. editor = tinymce.activeEditor;
  634. wpActiveEditor = window.wpActiveEditor = editor.id;
  635. } else if ( ! hasQuicktags ) {
  636. return false;
  637. }
  638. } else if ( hasTinymce ) {
  639. editor = tinymce.get( wpActiveEditor );
  640. }
  641. if ( editor && ! editor.isHidden() ) {
  642. editor.execCommand( 'mceInsertContent', false, html );
  643. } else if ( hasQuicktags ) {
  644. QTags.insertContent( html );
  645. } else {
  646. document.getElementById( wpActiveEditor ).value += html;
  647. }
  648. // If the old thickbox remove function exists, call it in case
  649. // a theme/plugin overloaded it.
  650. if ( window.tb_remove ) {
  651. try { window.tb_remove(); } catch( e ) {}
  652. }
  653. },
  654. /**
  655. * Setup 'workflow' and add to the 'workflows' cache. 'open' can
  656. * subsequently be called upon it.
  657. *
  658. * @param {string} id A slug used to identify the workflow.
  659. * @param {Object} [options={}]
  660. *
  661. * @this wp.media.editor
  662. *
  663. * @returns {wp.media.view.MediaFrame.Select} A media workflow.
  664. */
  665. add: function( id, options ) {
  666. var workflow = this.get( id );
  667. // only add once: if exists return existing
  668. if ( workflow ) {
  669. return workflow;
  670. }
  671. workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
  672. frame: 'post',
  673. state: 'insert',
  674. title: wp.media.view.l10n.addMedia,
  675. multiple: true
  676. } ) );
  677. workflow.on( 'insert', function( selection ) {
  678. var state = workflow.state();
  679. selection = selection || state.get('selection');
  680. if ( ! selection )
  681. return;
  682. $.when.apply( $, selection.map( function( attachment ) {
  683. var display = state.display( attachment ).toJSON();
  684. /**
  685. * @this wp.media.editor
  686. */
  687. return this.send.attachment( display, attachment.toJSON() );
  688. }, this ) ).done( function() {
  689. wp.media.editor.insert( _.toArray( arguments ).join('\n\n') );
  690. });
  691. }, this );
  692. workflow.state('gallery-edit').on( 'update', function( selection ) {
  693. /**
  694. * @this wp.media.editor
  695. */
  696. this.insert( wp.media.gallery.shortcode( selection ).string() );
  697. }, this );
  698. workflow.state('playlist-edit').on( 'update', function( selection ) {
  699. /**
  700. * @this wp.media.editor
  701. */
  702. this.insert( wp.media.playlist.shortcode( selection ).string() );
  703. }, this );
  704. workflow.state('video-playlist-edit').on( 'update', function( selection ) {
  705. /**
  706. * @this wp.media.editor
  707. */
  708. this.insert( wp.media.playlist.shortcode( selection ).string() );
  709. }, this );
  710. workflow.state('embed').on( 'select', function() {
  711. /**
  712. * @this wp.media.editor
  713. */
  714. var state = workflow.state(),
  715. type = state.get('type'),
  716. embed = state.props.toJSON();
  717. embed.url = embed.url || '';
  718. if ( 'link' === type ) {
  719. _.defaults( embed, {
  720. linkText: embed.url,
  721. linkUrl: embed.url
  722. });
  723. this.send.link( embed ).done( function( resp ) {
  724. wp.media.editor.insert( resp );
  725. });
  726. } else if ( 'image' === type ) {
  727. _.defaults( embed, {
  728. title: embed.url,
  729. linkUrl: '',
  730. align: 'none',
  731. link: 'none'
  732. });
  733. if ( 'none' === embed.link ) {
  734. embed.linkUrl = '';
  735. } else if ( 'file' === embed.link ) {
  736. embed.linkUrl = embed.url;
  737. }
  738. this.insert( wp.media.string.image( embed ) );
  739. }
  740. }, this );
  741. workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
  742. workflow.setState( workflow.options.state );
  743. return workflow;
  744. },
  745. /**
  746. * Determines the proper current workflow id
  747. *
  748. * @param {string} [id=''] A slug used to identify the workflow.
  749. *
  750. * @returns {wpActiveEditor|string|tinymce.activeEditor.id}
  751. */
  752. id: function( id ) {
  753. if ( id ) {
  754. return id;
  755. }
  756. // If an empty `id` is provided, default to `wpActiveEditor`.
  757. id = window.wpActiveEditor;
  758. // If that doesn't work, fall back to `tinymce.activeEditor.id`.
  759. if ( ! id && ! _.isUndefined( window.tinymce ) && tinymce.activeEditor ) {
  760. id = tinymce.activeEditor.id;
  761. }
  762. // Last but not least, fall back to the empty string.
  763. id = id || '';
  764. return id;
  765. },
  766. /**
  767. * Return the workflow specified by id
  768. *
  769. * @param {string} id A slug used to identify the workflow.
  770. *
  771. * @this wp.media.editor
  772. *
  773. * @returns {wp.media.view.MediaFrame} A media workflow.
  774. */
  775. get: function( id ) {
  776. id = this.id( id );
  777. return workflows[ id ];
  778. },
  779. /**
  780. * Remove the workflow represented by id from the workflow cache
  781. *
  782. * @param {string} id A slug used to identify the workflow.
  783. *
  784. * @this wp.media.editor
  785. */
  786. remove: function( id ) {
  787. id = this.id( id );
  788. delete workflows[ id ];
  789. },
  790. /** @namespace wp.media.editor.send */
  791. send: {
  792. /**
  793. * Called when sending an attachment to the editor
  794. * from the medial modal.
  795. *
  796. * @param {Object} props Attachment details (align, link, size, etc).
  797. * @param {Object} attachment The attachment object, media version of Post.
  798. * @returns {Promise}
  799. */
  800. attachment: function( props, attachment ) {
  801. var caption = attachment.caption,
  802. options, html;
  803. // If captions are disabled, clear the caption.
  804. if ( ! wp.media.view.settings.captions ) {
  805. delete attachment.caption;
  806. }
  807. props = wp.media.string.props( props, attachment );
  808. options = {
  809. id: attachment.id,
  810. post_content: attachment.description,
  811. post_excerpt: caption
  812. };
  813. if ( props.linkUrl ) {
  814. options.url = props.linkUrl;
  815. }
  816. if ( 'image' === attachment.type ) {
  817. html = wp.media.string.image( props );
  818. _.each({
  819. align: 'align',
  820. size: 'image-size',
  821. alt: 'image_alt'
  822. }, function( option, prop ) {
  823. if ( props[ prop ] )
  824. options[ option ] = props[ prop ];
  825. });
  826. } else if ( 'video' === attachment.type ) {
  827. html = wp.media.string.video( props, attachment );
  828. } else if ( 'audio' === attachment.type ) {
  829. html = wp.media.string.audio( props, attachment );
  830. } else {
  831. html = wp.media.string.link( props );
  832. options.post_title = props.title;
  833. }
  834. return wp.media.post( 'send-attachment-to-editor', {
  835. nonce: wp.media.view.settings.nonce.sendToEditor,
  836. attachment: options,
  837. html: html,
  838. post_id: wp.media.view.settings.post.id
  839. });
  840. },
  841. /**
  842. * Called when 'Insert From URL' source is not an image. Example: YouTube url.
  843. *
  844. * @param {Object} embed
  845. * @returns {Promise}
  846. */
  847. link: function( embed ) {
  848. return wp.media.post( 'send-link-to-editor', {
  849. nonce: wp.media.view.settings.nonce.sendToEditor,
  850. src: embed.linkUrl,
  851. link_text: embed.linkText,
  852. html: wp.media.string.link( embed ),
  853. post_id: wp.media.view.settings.post.id
  854. });
  855. }
  856. },
  857. /**
  858. * Open a workflow
  859. *
  860. * @param {string} [id=undefined] Optional. A slug used to identify the workflow.
  861. * @param {Object} [options={}]
  862. *
  863. * @this wp.media.editor
  864. *
  865. * @returns {wp.media.view.MediaFrame}
  866. */
  867. open: function( id, options ) {
  868. var workflow;
  869. options = options || {};
  870. id = this.id( id );
  871. this.activeEditor = id;
  872. workflow = this.get( id );
  873. // Redo workflow if state has changed
  874. if ( ! workflow || ( workflow.options && options.state !== workflow.options.state ) ) {
  875. workflow = this.add( id, options );
  876. }
  877. wp.media.frame = workflow;
  878. return workflow.open();
  879. },
  880. /**
  881. * Bind click event for .insert-media using event delegation
  882. */
  883. init: function() {
  884. $(document.body)
  885. .on( 'click.add-media-button', '.insert-media', function( event ) {
  886. var elem = $( event.currentTarget ),
  887. editor = elem.data('editor'),
  888. options = {
  889. frame: 'post',
  890. state: 'insert',
  891. title: wp.media.view.l10n.addMedia,
  892. multiple: true
  893. };
  894. event.preventDefault();
  895. if ( elem.hasClass( 'gallery' ) ) {
  896. options.state = 'gallery';
  897. options.title = wp.media.view.l10n.createGalleryTitle;
  898. }
  899. wp.media.editor.open( editor, options );
  900. });
  901. // Initialize and render the Editor drag-and-drop uploader.
  902. new wp.media.view.EditorUploader().render();
  903. }
  904. };
  905. _.bindAll( wp.media.editor, 'open' );
  906. $( wp.media.editor.init );
  907. }(jQuery, _));