mirror of
https://github.com/WordPress/WordPress.git
synced 2024-11-08 20:01:12 +01:00
887998f7ed
* Update deprecated `isHostedVideo` method to always return `true` since all oEmbeds are now supported. * Disable `scanImage` for non-image media widgets. * Ensure embed URL field element is matched from current media frame instance due to bug where media frames are not destroyed upon closing. * Update error message for invalid video URLs to ask user to check the URL for validity. Props gk.loveweb, octalmage, westonruter. See #42039, #40935. Fixes #41052. Built from https://develop.svn.wordpress.org/trunk@41933 git-svn-id: http://core.svn.wordpress.org/trunk@41767 1a063a9b-81f0-0310-95a4-ce76da25c4cd
1 line
14 KiB
JavaScript
1 line
14 KiB
JavaScript
wp.mediaWidgets=function(a){"use strict";var b={};return b.controlConstructors={},b.modelConstructors={},b.PersistentDisplaySettingsLibrary=wp.media.controller.Library.extend({initialize:function(a){_.bindAll(this,"handleDisplaySettingChange"),wp.media.controller.Library.prototype.initialize.call(this,a)},handleDisplaySettingChange:function(a){this.get("selectedDisplaySettings").set(a.attributes)},display:function(a){var b,c=this.get("selectedDisplaySettings");return b=wp.media.controller.Library.prototype.display.call(this,a),b.off("change",this.handleDisplaySettingChange),b.set(c.attributes),"custom"===c.get("link_type")&&(b.linkUrl=c.get("link_url")),b.on("change",this.handleDisplaySettingChange),b}}),b.MediaEmbedView=wp.media.view.Embed.extend({initialize:function(a){var b,c=this;wp.media.view.Embed.prototype.initialize.call(c,a),"image"!==c.controller.options.mimeType&&(b=c.controller.states.get("embed"),b.off("scan",b.scanImage,b))},refresh:function(){var b;b="image"===this.controller.options.mimeType?wp.media.view.EmbedImage:wp.media.view.EmbedLink.extend({setAddToWidgetButtonDisabled:function(a){this.views.parent.views.parent.views.get(".media-frame-toolbar")[0].$el.find(".media-button-select").prop("disabled",a)},setErrorNotice:function(b){var c,d=this;c=d.views.parent.$el.find("> .notice:first-child"),b?(c.length||(c=a('<div class="media-widget-embed-notice notice notice-error notice-alt"></div>'),c.hide(),d.views.parent.$el.prepend(c)),c.empty(),c.append(a("<p>",{html:b})),c.slideDown("fast")):c.length&&c.slideUp("fast")},updateoEmbed:function(){var a,b=this;return(a=b.model.get("url"))?(a.match(/^(http|https):\/\/.+\//)||(b.controller.$el.find("#embed-url-field").addClass("invalid"),b.setAddToWidgetButtonDisabled(!0)),void wp.media.view.EmbedLink.prototype.updateoEmbed.call(b)):(b.setErrorNotice(""),void b.setAddToWidgetButtonDisabled(!0))},fetch:function(){var a,b,c,d,e,f,g,h=this;return e=h.model.get("url"),h.dfd&&"pending"===h.dfd.state()&&h.dfd.abort(),a=function(a){h.renderoEmbed({data:{body:a}}),h.controller.$el.find("#embed-url-field").removeClass("invalid"),h.setErrorNotice(""),h.setAddToWidgetButtonDisabled(!1)},d=document.createElement("a"),d.href=e,(b=d.pathname.toLowerCase().match(/\.(\w+)$/))?(c=b[1],void(wp.media.view.settings.embedMimes[c]?0!==wp.media.view.settings.embedMimes[c].indexOf(h.controller.options.mimeType)?h.renderFail():a("<!--success-->"):h.renderFail())):(f=/https?:\/\/www\.youtube\.com\/embed\/([^\/]+)/,g=f.exec(e),g&&(e="https://www.youtube.com/watch?v="+g[1],h.model.attributes.url=e),h.dfd=wp.apiRequest({url:wp.media.view.settings.oEmbedProxyUrl,data:{url:e,maxwidth:h.model.get("width"),maxheight:h.model.get("height"),discover:!1},type:"GET",dataType:"json",context:h}),h.dfd.done(function(b){return h.controller.options.mimeType!==b.type?void h.renderFail():void a(b.html)}),void h.dfd.fail(_.bind(h.renderFail,h)))},renderFail:function(){var a=this;a.controller.$el.find("#embed-url-field").addClass("invalid"),a.setErrorNotice(a.controller.options.invalidEmbedTypeError||"ERROR"),a.setAddToWidgetButtonDisabled(!0)}}),this.settings(new b({controller:this.controller,model:this.model.props,priority:40}))}}),b.MediaFrameSelect=wp.media.view.MediaFrame.Post.extend({createStates:function(){var a=this.options.mimeType,c=[];_.each(wp.media.view.settings.embedMimes,function(b){0===b.indexOf(a)&&c.push(b)}),c.length>0&&(a=c),this.states.add([new b.PersistentDisplaySettingsLibrary({id:"insert",title:this.options.title,selection:this.options.selection,priority:20,toolbar:"main-insert",filterable:"dates",library:wp.media.query({type:a}),multiple:!1,editable:!0,selectedDisplaySettings:this.options.selectedDisplaySettings,displaySettings:!!_.isUndefined(this.options.showDisplaySettings)||this.options.showDisplaySettings,displayUserSettings:!1}),new wp.media.controller.EditImage({model:this.options.editImage}),new wp.media.controller.Embed({metadata:this.options.metadata,type:"image"===this.options.mimeType?"image":"link",invalidEmbedTypeError:this.options.invalidEmbedTypeError})])},mainInsertToolbar:function(a){var b=this;a.set("insert",{style:"primary",priority:80,text:b.options.text,requires:{selection:!0},click:function(){var a=b.state(),c=a.get("selection");b.close(),a.trigger("insert",c).reset()}})},mainEmbedToolbar:function(a){a.view=new wp.media.view.Toolbar.Embed({controller:this,text:this.options.text,event:"insert"})},embedContent:function(){var a=new b.MediaEmbedView({controller:this,model:this.state()}).render();this.content.set(a),wp.media.isTouchDevice||a.url.focus()}}),b.MediaWidgetControl=Backbone.View.extend({l10n:{add_to_widget:"{{add_to_widget}}",add_media:"{{add_media}}"},id_base:"",mime_type:"",events:{"click .notice-missing-attachment a":"handleMediaLibraryLinkClick","click .select-media":"selectMedia","click .placeholder":"selectMedia","click .edit-media":"editMedia"},showDisplaySettings:!0,initialize:function(c){var d=this;if(Backbone.View.prototype.initialize.call(d,c),!(d.model instanceof b.MediaWidgetModel))throw new Error("Missing options.model");if(!c.el)throw new Error("Missing options.el");if(!c.syncContainer)throw new Error("Missing options.syncContainer");if(d.syncContainer=c.syncContainer,d.$el.addClass("media-widget-control"),_.bindAll(d,"syncModelToInputs","render","updateSelectedAttachment","renderPreview"),!d.id_base&&(_.find(b.controlConstructors,function(a,b){return d instanceof a&&(d.id_base=b,!0)}),!d.id_base))throw new Error("Missing id_base.");d.previewTemplateProps=new Backbone.Model(d.mapModelToPreviewTemplateProps()),d.selectedAttachment=new wp.media.model.Attachment,d.renderPreview=_.debounce(d.renderPreview),d.listenTo(d.previewTemplateProps,"change",d.renderPreview),d.model.on("change:attachment_id",d.updateSelectedAttachment),d.model.on("change:url",d.updateSelectedAttachment),d.updateSelectedAttachment(),d.listenTo(d.model,"change",d.syncModelToInputs),d.listenTo(d.model,"change",d.syncModelToPreviewProps),d.listenTo(d.model,"change",d.render),d.$el.on("input change",".title",function(){d.model.set({title:a.trim(a(this).val())})}),d.$el.on("input change",".link",function(){var b=a.trim(a(this).val()),c="custom";d.selectedAttachment.get("linkUrl")===b||d.selectedAttachment.get("link")===b?c="post":d.selectedAttachment.get("url")===b&&(c="file"),d.model.set({link_url:b,link_type:c}),d.displaySettings.set({link:c,linkUrl:b})}),d.displaySettings=new Backbone.Model(_.pick(d.mapModelToMediaFrameProps(_.extend(d.model.defaults(),d.model.toJSON())),_.keys(wp.media.view.settings.defaultProps)))},updateSelectedAttachment:function(){var a,b=this;0===b.model.get("attachment_id")?(b.selectedAttachment.clear(),b.model.set("error",!1)):b.model.get("attachment_id")!==b.selectedAttachment.get("id")&&(a=new wp.media.model.Attachment({id:b.model.get("attachment_id")}),a.fetch().done(function(){b.model.set("error",!1),b.selectedAttachment.set(a.toJSON())}).fail(function(){b.model.set("error","missing_attachment")}))},syncModelToPreviewProps:function(){var a=this;a.previewTemplateProps.set(a.mapModelToPreviewTemplateProps())},syncModelToInputs:function(){var b=this;b.syncContainer.find(".media-widget-instance-property").each(function(){var c,d,e=a(this);d=e.data("property"),c=b.model.get(d),_.isUndefined(c)||(c="array"===b.model.schema[d].type&&_.isArray(c)?c.join(","):"boolean"===b.model.schema[d].type?c?"1":"":String(c),e.val()!==c&&(e.val(c),e.trigger("change")))})},template:function(){var b=this;if(!a("#tmpl-widget-media-"+b.id_base+"-control").length)throw new Error("Missing widget control template for "+b.id_base);return wp.template("widget-media-"+b.id_base+"-control")},render:function(){var a,b=this;b.templateRendered||(b.$el.html(b.template()(b.model.toJSON())),b.renderPreview(),b.templateRendered=!0),a=b.$el.find(".title"),a.is(document.activeElement)||a.val(b.model.get("title")),b.$el.toggleClass("selected",b.isSelected())},renderPreview:function(){throw new Error("renderPreview must be implemented")},isSelected:function(){var a=this;return!a.model.get("error")&&Boolean(a.model.get("attachment_id")||a.model.get("url"))},handleMediaLibraryLinkClick:function(a){var b=this;a.preventDefault(),b.selectMedia()},selectMedia:function(){var c,d,e,f,g=this,h=[];g.isSelected()&&0!==g.model.get("attachment_id")&&h.push(g.selectedAttachment),c=new wp.media.model.Selection(h,{multiple:!1}),f=g.mapModelToMediaFrameProps(g.model.toJSON()),f.size&&g.displaySettings.set("size",f.size),d=new b.MediaFrameSelect({title:g.l10n.add_media,frame:"post",text:g.l10n.add_to_widget,selection:c,mimeType:g.mime_type,selectedDisplaySettings:g.displaySettings,showDisplaySettings:g.showDisplaySettings,metadata:f,state:g.isSelected()&&0===g.model.get("attachment_id")?"embed":"insert",invalidEmbedTypeError:g.l10n.unsupported_file_type}),wp.media.frame=d,d.on("insert",function(){var a={},b=d.state();"embed"===b.get("id")?_.extend(a,{id:0},b.props.toJSON()):_.extend(a,b.get("selection").first().toJSON()),g.selectedAttachment.set(a),g.model.set("error",!1),g.model.set(g.getModelPropsFromMediaFrame(d))}),e=wp.media.model.Attachment.prototype.sync,wp.media.model.Attachment.prototype.sync=function(b){return"delete"===b?e.apply(this,arguments):a.Deferred().rejectWith(this).promise()},d.on("close",function(){wp.media.model.Attachment.prototype.sync=e}),d.$el.addClass("media-widget"),d.open(),c&&c.on("destroy",function(a){g.model.get("attachment_id")===a.get("id")&&g.model.set({attachment_id:0,url:""})}),d.$el.find(".media-frame-menu .media-menu-item.active").focus()},getModelPropsFromMediaFrame:function(a){var b,c,d,e=this;if(b=a.state(),"insert"===b.get("id"))c=b.get("selection").first().toJSON(),c.postUrl=c.link,e.showDisplaySettings&&_.extend(c,a.content.get(".attachments-browser").sidebar.get("display").model.toJSON()),c.sizes&&c.size&&c.sizes[c.size]&&(c.url=c.sizes[c.size].url);else{if("embed"!==b.get("id"))throw new Error("Unexpected state: "+b.get("id"));c=_.extend(b.props.toJSON(),{attachment_id:0},e.model.getEmbedResetProps())}return c.id&&(c.attachment_id=c.id),d=e.mapMediaToModelProps(c),_.each(wp.media.view.settings.embedExts,function(a){a in e.model.schema&&d.url!==d[a]&&(d[a]="")}),d},mapMediaToModelProps:function(a){var b,c=this,d={},e={};return _.each(c.model.schema,function(a,b){"title"!==b&&(d[a.media_prop||b]=b)}),_.each(a,function(a,b){var f=d[b]||b;c.model.schema[f]&&(e[f]=a)}),"custom"===a.size&&(e.width=a.customWidth,e.height=a.customHeight),"post"===a.link?e.link_url=a.postUrl||a.linkUrl:"file"===a.link&&(e.link_url=a.url),!a.attachment_id&&a.id&&(e.attachment_id=a.id),a.url&&(b=a.url.replace(/#.*$/,"").replace(/\?.*$/,"").split(".").pop().toLowerCase(),b in c.model.schema&&(e[b]=a.url)),_.omit(e,"title")},mapModelToMediaFrameProps:function(a){var b=this,c={};return _.each(a,function(a,d){var e=b.model.schema[d]||{};c[e.media_prop||d]=a}),c.attachment_id=c.id,"custom"===c.size&&(c.customWidth=b.model.get("width"),c.customHeight=b.model.get("height")),c},mapModelToPreviewTemplateProps:function(){var a=this,b={};return _.each(a.model.schema,function(c,d){c.hasOwnProperty("should_preview_update")&&!c.should_preview_update||(b[d]=a.model.get(d))}),b.error=a.model.get("error"),b},editMedia:function(){throw new Error("editMedia not implemented")}}),b.MediaWidgetModel=Backbone.Model.extend({idAttribute:"widget_id",schema:{title:{type:"string","default":""},attachment_id:{type:"integer","default":0},url:{type:"string","default":""}},defaults:function(){var a={};return _.each(this.schema,function(b,c){a[c]=b["default"]}),a},set:function(a,b,c){var d,e,f,g=this;return null===a?g:("object"==typeof a?(d=a,e=b):(d={},d[a]=b,e=c),f={},_.each(d,function(a,b){var c;return g.schema[b]?(c=g.schema[b].type,void("array"===c?(f[b]=a,_.isArray(f[b])||(f[b]=f[b].split(/,/)),g.schema[b].items&&"integer"===g.schema[b].items.type&&(f[b]=_.filter(_.map(f[b],function(a){return parseInt(a,10)},function(a){return"number"==typeof a})))):"integer"===c?f[b]=parseInt(a,10):"boolean"===c?f[b]=!(!a||"0"===a||"false"===a):f[b]=a)):void(f[b]=a)}),Backbone.Model.prototype.set.call(this,f,e))},getEmbedResetProps:function(){return{id:0}}}),b.modelCollection=new(Backbone.Collection.extend({model:b.MediaWidgetModel})),b.widgetControls={},b.handleWidgetAdded=function(c,d){var e,f,g,h,i,j,k,l,m,n,o,p=50;g=d.find("> .widget-inside > .form, > .widget-inside > form"),h=g.find("> .id_base").val(),n=g.find("> .widget-id").val(),b.widgetControls[n]||(i=b.controlConstructors[h],i&&(j=b.modelConstructors[h]||b.MediaWidgetModel,e=a("<div></div>"),f=d.find(".widget-content:first"),f.before(e),k={},f.find(".media-widget-instance-property").each(function(){var b=a(this);k[b.data("property")]=b.val()}),k.widget_id=n,m=new j(k),l=new i({el:e,syncContainer:f,model:m}),o=function(){d.hasClass("open")?l.render():setTimeout(o,p)},o(),b.modelCollection.add([m]),b.widgetControls[m.get("widget_id")]=l))},b.setupAccessibleMode=function(){var c,d,e,f,g,h,i,j,k;c=a(".editwidget > form"),0!==c.length&&(e=c.find("> .widget-control-actions > .id_base").val(),g=b.controlConstructors[e],g&&(d=c.find("> .widget-control-actions > .widget-id").val(),h=b.modelConstructors[e]||b.MediaWidgetModel,j=a("<div></div>"),k=c.find("> .widget-inside"),k.before(j),i={},k.find(".media-widget-instance-property").each(function(){var b=a(this);i[b.data("property")]=b.val()}),i.widget_id=d,f=new g({el:j,syncContainer:k,model:new h(i)}),b.modelCollection.add([f.model]),b.widgetControls[f.model.get("widget_id")]=f,f.render()))},b.handleWidgetUpdated=function(c,d){var e,f,g,h,i={};e=d.find("> .widget-inside > .form, > .widget-inside > form"),g=e.find("> .widget-id").val(),h=b.widgetControls[g],h&&(f=e.find("> .widget-content"),f.find(".media-widget-instance-property").each(function(){var b=a(this).data("property");i[b]=a(this).val()}),h.stopListening(h.model,"change",h.syncModelToInputs),h.model.set(i),h.listenTo(h.model,"change",h.syncModelToInputs))},b.init=function(){var c=a(document);c.on("widget-added",b.handleWidgetAdded),c.on("widget-synced widget-updated",b.handleWidgetUpdated),a(function(){var c;"widgets"===window.pagenow&&(c=a(".widgets-holder-wrap:not(#available-widgets)").find("div.widget"),c.one("click.toggle-widget-expanded",function(){var c=a(this);b.handleWidgetAdded(new jQuery.Event("widget-added"),c)}),a(window).on("load",function(){b.setupAccessibleMode()}))})},b}(jQuery); |