whoami7 - Manager
:
/
home
/
topsuzmw
/
www
/
wp-includes
/
private
/
Upload File:
files >> /home/topsuzmw/www/wp-includes/private/js.zip
PK 4�Z��+ + tags.min.jsnu �[��� /*! This file is auto-generated */ jQuery(function(o){var s=!1;o("#the-list").on("click",".delete-tag",function(){var t,e=o(this),n=e.parents("tr"),r=!0;return(r="undefined"!=showNotice?showNotice.warn():r)&&(t=e.attr("href").replace(/[^?]*\?/,"").replace(/action=delete/,"action=delete-tag"),o.post(ajaxurl,t,function(e){"1"==e?(o("#ajax-response").empty(),n.fadeOut("normal",function(){n.remove()}),o('select#parent option[value="'+t.match(/tag_ID=(\d+)/)[1]+'"]').remove(),o("a.tag-link-"+t.match(/tag_ID=(\d+)/)[1]).remove()):("-1"==e?o("#ajax-response").empty().append('<div class="notice notice-error"><p>'+wp.i18n.__("Sorry, you are not allowed to do that.")+"</p></div>"):o("#ajax-response").empty().append('<div class="notice notice-error"><p>'+wp.i18n.__("An error occurred while processing your request. Please try again later.")+"</p></div>"),n.children().css("backgroundColor",""))}),n.children().css("backgroundColor","#f33")),!1}),o("#edittag").on("click",".delete",function(e){if("undefined"==typeof showNotice)return!0;showNotice.warn()||e.preventDefault()}),o("#submit").on("click",function(){var a=o(this).parents("form");return s||(s=!0,a.find(".submit .spinner").addClass("is-active"),o.post(ajaxurl,o("#addtag").serialize(),function(e){var t,n,r;if(s=!1,a.find(".submit .spinner").removeClass("is-active"),o("#ajax-response").empty(),(t=wpAjax.parseAjaxResponse(e,"ajax-response")).errors&&"empty_term_name"===t.responses[0].errors[0].code&&validateForm(a),t&&!t.errors){if(0<(e=a.find("select#parent").val())&&0<o("#tag-"+e).length?o(".tags #tag-"+e).after(t.responses[0].supplemental.noparents):o(".tags").prepend(t.responses[0].supplemental.parents),o(".tags .no-items").remove(),a.find("select#parent")){for(e=t.responses[1].supplemental,n="",r=0;r<t.responses[1].position;r++)n+=" ";a.find("select#parent option:selected").after('<option value="'+e.term_id+'">'+n+e.name+"</option>")}o('input:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="reset"]):visible, textarea:visible',a).val("")}})),!1})});PK 4�Z��D�� � svg-painter.jsnu �[��� /** * Attempt to re-color SVG icons used in the admin menu or the toolbar * * @output wp-admin/js/svg-painter.js */ window.wp = window.wp || {}; wp.svgPainter = ( function( $, window, document, undefined ) { 'use strict'; var selector, painter, colorscheme = {}, elements = []; $( function() { wp.svgPainter.init(); }); return { init: function() { painter = this; selector = $( '#adminmenu .wp-menu-image, #wpadminbar .ab-item' ); painter.setColors(); painter.findElements(); painter.paint(); }, setColors: function( colors ) { if ( typeof colors === 'undefined' && typeof window._wpColorScheme !== 'undefined' ) { colors = window._wpColorScheme; } if ( colors && colors.icons && colors.icons.base && colors.icons.current && colors.icons.focus ) { colorscheme = colors.icons; } }, findElements: function() { selector.each( function() { var $this = $(this), bgImage = $this.css( 'background-image' ); if ( bgImage && bgImage.indexOf( 'data:image/svg+xml;base64' ) != -1 ) { elements.push( $this ); } }); }, paint: function() { // Loop through all elements. $.each( elements, function( index, $element ) { var $menuitem = $element.parent().parent(); if ( $menuitem.hasClass( 'current' ) || $menuitem.hasClass( 'wp-has-current-submenu' ) ) { // Paint icon in 'current' color. painter.paintElement( $element, 'current' ); } else { // Paint icon in base color. painter.paintElement( $element, 'base' ); // Set hover callbacks. $menuitem.on( 'mouseenter', function() { painter.paintElement( $element, 'focus' ); } ).on( 'mouseleave', function() { // Match the delay from hoverIntent. window.setTimeout( function() { painter.paintElement( $element, 'base' ); }, 100 ); } ); } }); }, paintElement: function( $element, colorType ) { var xml, encoded, color; if ( ! colorType || ! colorscheme.hasOwnProperty( colorType ) ) { return; } color = colorscheme[ colorType ]; // Only accept hex colors: #101 or #101010. if ( ! color.match( /^(#[0-9a-f]{3}|#[0-9a-f]{6})$/i ) ) { return; } xml = $element.data( 'wp-ui-svg-' + color ); if ( xml === 'none' ) { return; } if ( ! xml ) { encoded = $element.css( 'background-image' ).match( /.+data:image\/svg\+xml;base64,([A-Za-z0-9\+\/\=]+)/ ); if ( ! encoded || ! encoded[1] ) { $element.data( 'wp-ui-svg-' + color, 'none' ); return; } try { xml = window.atob( encoded[1] ); } catch ( error ) {} if ( xml ) { // Replace `fill` attributes. xml = xml.replace( /fill="(.+?)"/g, 'fill="' + color + '"'); // Replace `style` attributes. xml = xml.replace( /style="(.+?)"/g, 'style="fill:' + color + '"'); // Replace `fill` properties in `<style>` tags. xml = xml.replace( /fill:.*?;/g, 'fill: ' + color + ';'); xml = window.btoa( xml ); $element.data( 'wp-ui-svg-' + color, xml ); } else { $element.data( 'wp-ui-svg-' + color, 'none' ); return; } } $element.attr( 'style', 'background-image: url("data:image/svg+xml;base64,' + xml + '") !important;' ); } }; })( jQuery, window, document ); PK 4�ZM���c c theme-plugin-editor.jsnu �[��� /** * @output wp-admin/js/theme-plugin-editor.js */ /* eslint no-magic-numbers: ["error", { "ignore": [-1, 0, 1] }] */ if ( ! window.wp ) { window.wp = {}; } wp.themePluginEditor = (function( $ ) { 'use strict'; var component, TreeLinks, __ = wp.i18n.__, _n = wp.i18n._n, sprintf = wp.i18n.sprintf; component = { codeEditor: {}, instance: null, noticeElements: {}, dirty: false, lintErrors: [] }; /** * Initialize component. * * @since 4.9.0 * * @param {jQuery} form - Form element. * @param {Object} settings - Settings. * @param {Object|boolean} settings.codeEditor - Code editor settings (or `false` if syntax highlighting is disabled). * @return {void} */ component.init = function init( form, settings ) { component.form = form; if ( settings ) { $.extend( component, settings ); } component.noticeTemplate = wp.template( 'wp-file-editor-notice' ); component.noticesContainer = component.form.find( '.editor-notices' ); component.submitButton = component.form.find( ':input[name=submit]' ); component.spinner = component.form.find( '.submit .spinner' ); component.form.on( 'submit', component.submit ); component.textarea = component.form.find( '#newcontent' ); component.textarea.on( 'change', component.onChange ); component.warning = $( '.file-editor-warning' ); component.docsLookUpButton = component.form.find( '#docs-lookup' ); component.docsLookUpList = component.form.find( '#docs-list' ); if ( component.warning.length > 0 ) { component.showWarning(); } if ( false !== component.codeEditor ) { /* * Defer adding notices until after DOM ready as workaround for WP Admin injecting * its own managed dismiss buttons and also to prevent the editor from showing a notice * when the file had linting errors to begin with. */ _.defer( function() { component.initCodeEditor(); } ); } $( component.initFileBrowser ); $( window ).on( 'beforeunload', function() { if ( component.dirty ) { return __( 'The changes you made will be lost if you navigate away from this page.' ); } return undefined; } ); component.docsLookUpList.on( 'change', function() { var option = $( this ).val(); if ( '' === option ) { component.docsLookUpButton.prop( 'disabled', true ); } else { component.docsLookUpButton.prop( 'disabled', false ); } } ); }; /** * Set up and display the warning modal. * * @since 4.9.0 * @return {void} */ component.showWarning = function() { // Get the text within the modal. var rawMessage = component.warning.find( '.file-editor-warning-message' ).text(); // Hide all the #wpwrap content from assistive technologies. $( '#wpwrap' ).attr( 'aria-hidden', 'true' ); // Detach the warning modal from its position and append it to the body. $( document.body ) .addClass( 'modal-open' ) .append( component.warning.detach() ); // Reveal the modal and set focus on the go back button. component.warning .removeClass( 'hidden' ) .find( '.file-editor-warning-go-back' ).trigger( 'focus' ); // Get the links and buttons within the modal. component.warningTabbables = component.warning.find( 'a, button' ); // Attach event handlers. component.warningTabbables.on( 'keydown', component.constrainTabbing ); component.warning.on( 'click', '.file-editor-warning-dismiss', component.dismissWarning ); // Make screen readers announce the warning message after a short delay (necessary for some screen readers). setTimeout( function() { wp.a11y.speak( wp.sanitize.stripTags( rawMessage.replace( /\s+/g, ' ' ) ), 'assertive' ); }, 1000 ); }; /** * Constrain tabbing within the warning modal. * * @since 4.9.0 * @param {Object} event jQuery event object. * @return {void} */ component.constrainTabbing = function( event ) { var firstTabbable, lastTabbable; if ( 9 !== event.which ) { return; } firstTabbable = component.warningTabbables.first()[0]; lastTabbable = component.warningTabbables.last()[0]; if ( lastTabbable === event.target && ! event.shiftKey ) { firstTabbable.focus(); event.preventDefault(); } else if ( firstTabbable === event.target && event.shiftKey ) { lastTabbable.focus(); event.preventDefault(); } }; /** * Dismiss the warning modal. * * @since 4.9.0 * @return {void} */ component.dismissWarning = function() { wp.ajax.post( 'dismiss-wp-pointer', { pointer: component.themeOrPlugin + '_editor_notice' }); // Hide modal. component.warning.remove(); $( '#wpwrap' ).removeAttr( 'aria-hidden' ); $( 'body' ).removeClass( 'modal-open' ); }; /** * Callback for when a change happens. * * @since 4.9.0 * @return {void} */ component.onChange = function() { component.dirty = true; component.removeNotice( 'file_saved' ); }; /** * Submit file via Ajax. * * @since 4.9.0 * @param {jQuery.Event} event - Event. * @return {void} */ component.submit = function( event ) { var data = {}, request; event.preventDefault(); // Prevent form submission in favor of Ajax below. $.each( component.form.serializeArray(), function() { data[ this.name ] = this.value; } ); // Use value from codemirror if present. if ( component.instance ) { data.newcontent = component.instance.codemirror.getValue(); } if ( component.isSaving ) { return; } // Scroll to the line that has the error. if ( component.lintErrors.length ) { component.instance.codemirror.setCursor( component.lintErrors[0].from.line ); return; } component.isSaving = true; component.textarea.prop( 'readonly', true ); if ( component.instance ) { component.instance.codemirror.setOption( 'readOnly', true ); } component.spinner.addClass( 'is-active' ); request = wp.ajax.post( 'edit-theme-plugin-file', data ); // Remove previous save notice before saving. if ( component.lastSaveNoticeCode ) { component.removeNotice( component.lastSaveNoticeCode ); } request.done( function( response ) { component.lastSaveNoticeCode = 'file_saved'; component.addNotice({ code: component.lastSaveNoticeCode, type: 'success', message: response.message, dismissible: true }); component.dirty = false; } ); request.fail( function( response ) { var notice = $.extend( { code: 'save_error', message: __( 'An error occurred while saving your changes. Please try again. If the problem persists, you may need to manually update the file via FTP.' ) }, response, { type: 'error', dismissible: true } ); component.lastSaveNoticeCode = notice.code; component.addNotice( notice ); } ); request.always( function() { component.spinner.removeClass( 'is-active' ); component.isSaving = false; component.textarea.prop( 'readonly', false ); if ( component.instance ) { component.instance.codemirror.setOption( 'readOnly', false ); } } ); }; /** * Add notice. * * @since 4.9.0 * * @param {Object} notice - Notice. * @param {string} notice.code - Code. * @param {string} notice.type - Type. * @param {string} notice.message - Message. * @param {boolean} [notice.dismissible=false] - Dismissible. * @param {Function} [notice.onDismiss] - Callback for when a user dismisses the notice. * @return {jQuery} Notice element. */ component.addNotice = function( notice ) { var noticeElement; if ( ! notice.code ) { throw new Error( 'Missing code.' ); } // Only let one notice of a given type be displayed at a time. component.removeNotice( notice.code ); noticeElement = $( component.noticeTemplate( notice ) ); noticeElement.hide(); noticeElement.find( '.notice-dismiss' ).on( 'click', function() { component.removeNotice( notice.code ); if ( notice.onDismiss ) { notice.onDismiss( notice ); } } ); wp.a11y.speak( notice.message ); component.noticesContainer.append( noticeElement ); noticeElement.slideDown( 'fast' ); component.noticeElements[ notice.code ] = noticeElement; return noticeElement; }; /** * Remove notice. * * @since 4.9.0 * * @param {string} code - Notice code. * @return {boolean} Whether a notice was removed. */ component.removeNotice = function( code ) { if ( component.noticeElements[ code ] ) { component.noticeElements[ code ].slideUp( 'fast', function() { $( this ).remove(); } ); delete component.noticeElements[ code ]; return true; } return false; }; /** * Initialize code editor. * * @since 4.9.0 * @return {void} */ component.initCodeEditor = function initCodeEditor() { var codeEditorSettings, editor; codeEditorSettings = $.extend( {}, component.codeEditor ); /** * Handle tabbing to the field before the editor. * * @since 4.9.0 * * @return {void} */ codeEditorSettings.onTabPrevious = function() { $( '#templateside' ).find( ':tabbable' ).last().trigger( 'focus' ); }; /** * Handle tabbing to the field after the editor. * * @since 4.9.0 * * @return {void} */ codeEditorSettings.onTabNext = function() { $( '#template' ).find( ':tabbable:not(.CodeMirror-code)' ).first().trigger( 'focus' ); }; /** * Handle change to the linting errors. * * @since 4.9.0 * * @param {Array} errors - List of linting errors. * @return {void} */ codeEditorSettings.onChangeLintingErrors = function( errors ) { component.lintErrors = errors; // Only disable the button in onUpdateErrorNotice when there are errors so users can still feel they can click the button. if ( 0 === errors.length ) { component.submitButton.toggleClass( 'disabled', false ); } }; /** * Update error notice. * * @since 4.9.0 * * @param {Array} errorAnnotations - Error annotations. * @return {void} */ codeEditorSettings.onUpdateErrorNotice = function onUpdateErrorNotice( errorAnnotations ) { var noticeElement; component.submitButton.toggleClass( 'disabled', errorAnnotations.length > 0 ); if ( 0 !== errorAnnotations.length ) { noticeElement = component.addNotice({ code: 'lint_errors', type: 'error', message: sprintf( /* translators: %s: Error count. */ _n( 'There is %s error which must be fixed before you can update this file.', 'There are %s errors which must be fixed before you can update this file.', errorAnnotations.length ), String( errorAnnotations.length ) ), dismissible: false }); noticeElement.find( 'input[type=checkbox]' ).on( 'click', function() { codeEditorSettings.onChangeLintingErrors( [] ); component.removeNotice( 'lint_errors' ); } ); } else { component.removeNotice( 'lint_errors' ); } }; editor = wp.codeEditor.initialize( $( '#newcontent' ), codeEditorSettings ); editor.codemirror.on( 'change', component.onChange ); // Improve the editor accessibility. $( editor.codemirror.display.lineDiv ) .attr({ role: 'textbox', 'aria-multiline': 'true', 'aria-labelledby': 'theme-plugin-editor-label', 'aria-describedby': 'editor-keyboard-trap-help-1 editor-keyboard-trap-help-2 editor-keyboard-trap-help-3 editor-keyboard-trap-help-4' }); // Focus the editor when clicking on its label. $( '#theme-plugin-editor-label' ).on( 'click', function() { editor.codemirror.focus(); }); component.instance = editor; }; /** * Initialization of the file browser's folder states. * * @since 4.9.0 * @return {void} */ component.initFileBrowser = function initFileBrowser() { var $templateside = $( '#templateside' ); // Collapse all folders. $templateside.find( '[role="group"]' ).parent().attr( 'aria-expanded', false ); // Expand ancestors to the current file. $templateside.find( '.notice' ).parents( '[aria-expanded]' ).attr( 'aria-expanded', true ); // Find Tree elements and enhance them. $templateside.find( '[role="tree"]' ).each( function() { var treeLinks = new TreeLinks( this ); treeLinks.init(); } ); // Scroll the current file into view. $templateside.find( '.current-file:first' ).each( function() { if ( this.scrollIntoViewIfNeeded ) { this.scrollIntoViewIfNeeded(); } else { this.scrollIntoView( false ); } } ); }; /* jshint ignore:start */ /* jscs:disable */ /* eslint-disable */ /** * Creates a new TreeitemLink. * * @since 4.9.0 * @class * @private * @see {@link https://www.w3.org/TR/wai-aria-practices-1.1/examples/treeview/treeview-2/treeview-2b.html|W3C Treeview Example} * @license W3C-20150513 */ var TreeitemLink = (function () { /** * This content is licensed according to the W3C Software License at * https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * * File: TreeitemLink.js * * Desc: Treeitem widget that implements ARIA Authoring Practices * for a tree being used as a file viewer * * Author: Jon Gunderson, Ku Ja Eun and Nicholas Hoyt */ /** * @constructor * * @desc * Treeitem object for representing the state and user interactions for a * treeItem widget * * @param node * An element with the role=tree attribute */ var TreeitemLink = function (node, treeObj, group) { // Check whether node is a DOM element. if (typeof node !== 'object') { return; } node.tabIndex = -1; this.tree = treeObj; this.groupTreeitem = group; this.domNode = node; this.label = node.textContent.trim(); this.stopDefaultClick = false; if (node.getAttribute('aria-label')) { this.label = node.getAttribute('aria-label').trim(); } this.isExpandable = false; this.isVisible = false; this.inGroup = false; if (group) { this.inGroup = true; } var elem = node.firstElementChild; while (elem) { if (elem.tagName.toLowerCase() == 'ul') { elem.setAttribute('role', 'group'); this.isExpandable = true; break; } elem = elem.nextElementSibling; } this.keyCode = Object.freeze({ RETURN: 13, SPACE: 32, PAGEUP: 33, PAGEDOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }); }; TreeitemLink.prototype.init = function () { this.domNode.tabIndex = -1; if (!this.domNode.getAttribute('role')) { this.domNode.setAttribute('role', 'treeitem'); } this.domNode.addEventListener('keydown', this.handleKeydown.bind(this)); this.domNode.addEventListener('click', this.handleClick.bind(this)); this.domNode.addEventListener('focus', this.handleFocus.bind(this)); this.domNode.addEventListener('blur', this.handleBlur.bind(this)); if (this.isExpandable) { this.domNode.firstElementChild.addEventListener('mouseover', this.handleMouseOver.bind(this)); this.domNode.firstElementChild.addEventListener('mouseout', this.handleMouseOut.bind(this)); } else { this.domNode.addEventListener('mouseover', this.handleMouseOver.bind(this)); this.domNode.addEventListener('mouseout', this.handleMouseOut.bind(this)); } }; TreeitemLink.prototype.isExpanded = function () { if (this.isExpandable) { return this.domNode.getAttribute('aria-expanded') === 'true'; } return false; }; /* EVENT HANDLERS */ TreeitemLink.prototype.handleKeydown = function (event) { var tgt = event.currentTarget, flag = false, _char = event.key, clickEvent; function isPrintableCharacter(str) { return str.length === 1 && str.match(/\S/); } function printableCharacter(item) { if (_char == '*') { item.tree.expandAllSiblingItems(item); flag = true; } else { if (isPrintableCharacter(_char)) { item.tree.setFocusByFirstCharacter(item, _char); flag = true; } } } this.stopDefaultClick = false; if (event.altKey || event.ctrlKey || event.metaKey) { return; } if (event.shift) { if (event.keyCode == this.keyCode.SPACE || event.keyCode == this.keyCode.RETURN) { event.stopPropagation(); this.stopDefaultClick = true; } else { if (isPrintableCharacter(_char)) { printableCharacter(this); } } } else { switch (event.keyCode) { case this.keyCode.SPACE: case this.keyCode.RETURN: if (this.isExpandable) { if (this.isExpanded()) { this.tree.collapseTreeitem(this); } else { this.tree.expandTreeitem(this); } flag = true; } else { event.stopPropagation(); this.stopDefaultClick = true; } break; case this.keyCode.UP: this.tree.setFocusToPreviousItem(this); flag = true; break; case this.keyCode.DOWN: this.tree.setFocusToNextItem(this); flag = true; break; case this.keyCode.RIGHT: if (this.isExpandable) { if (this.isExpanded()) { this.tree.setFocusToNextItem(this); } else { this.tree.expandTreeitem(this); } } flag = true; break; case this.keyCode.LEFT: if (this.isExpandable && this.isExpanded()) { this.tree.collapseTreeitem(this); flag = true; } else { if (this.inGroup) { this.tree.setFocusToParentItem(this); flag = true; } } break; case this.keyCode.HOME: this.tree.setFocusToFirstItem(); flag = true; break; case this.keyCode.END: this.tree.setFocusToLastItem(); flag = true; break; default: if (isPrintableCharacter(_char)) { printableCharacter(this); } break; } } if (flag) { event.stopPropagation(); event.preventDefault(); } }; TreeitemLink.prototype.handleClick = function (event) { // Only process click events that directly happened on this treeitem. if (event.target !== this.domNode && event.target !== this.domNode.firstElementChild) { return; } if (this.isExpandable) { if (this.isExpanded()) { this.tree.collapseTreeitem(this); } else { this.tree.expandTreeitem(this); } event.stopPropagation(); } }; TreeitemLink.prototype.handleFocus = function (event) { var node = this.domNode; if (this.isExpandable) { node = node.firstElementChild; } node.classList.add('focus'); }; TreeitemLink.prototype.handleBlur = function (event) { var node = this.domNode; if (this.isExpandable) { node = node.firstElementChild; } node.classList.remove('focus'); }; TreeitemLink.prototype.handleMouseOver = function (event) { event.currentTarget.classList.add('hover'); }; TreeitemLink.prototype.handleMouseOut = function (event) { event.currentTarget.classList.remove('hover'); }; return TreeitemLink; })(); /** * Creates a new TreeLinks. * * @since 4.9.0 * @class * @private * @see {@link https://www.w3.org/TR/wai-aria-practices-1.1/examples/treeview/treeview-2/treeview-2b.html|W3C Treeview Example} * @license W3C-20150513 */ TreeLinks = (function () { /* * This content is licensed according to the W3C Software License at * https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * * File: TreeLinks.js * * Desc: Tree widget that implements ARIA Authoring Practices * for a tree being used as a file viewer * * Author: Jon Gunderson, Ku Ja Eun and Nicholas Hoyt */ /* * @constructor * * @desc * Tree item object for representing the state and user interactions for a * tree widget * * @param node * An element with the role=tree attribute */ var TreeLinks = function (node) { // Check whether node is a DOM element. if (typeof node !== 'object') { return; } this.domNode = node; this.treeitems = []; this.firstChars = []; this.firstTreeitem = null; this.lastTreeitem = null; }; TreeLinks.prototype.init = function () { function findTreeitems(node, tree, group) { var elem = node.firstElementChild; var ti = group; while (elem) { if ((elem.tagName.toLowerCase() === 'li' && elem.firstElementChild.tagName.toLowerCase() === 'span') || elem.tagName.toLowerCase() === 'a') { ti = new TreeitemLink(elem, tree, group); ti.init(); tree.treeitems.push(ti); tree.firstChars.push(ti.label.substring(0, 1).toLowerCase()); } if (elem.firstElementChild) { findTreeitems(elem, tree, ti); } elem = elem.nextElementSibling; } } // Initialize pop up menus. if (!this.domNode.getAttribute('role')) { this.domNode.setAttribute('role', 'tree'); } findTreeitems(this.domNode, this, false); this.updateVisibleTreeitems(); this.firstTreeitem.domNode.tabIndex = 0; }; TreeLinks.prototype.setFocusToItem = function (treeitem) { for (var i = 0; i < this.treeitems.length; i++) { var ti = this.treeitems[i]; if (ti === treeitem) { ti.domNode.tabIndex = 0; ti.domNode.focus(); } else { ti.domNode.tabIndex = -1; } } }; TreeLinks.prototype.setFocusToNextItem = function (currentItem) { var nextItem = false; for (var i = (this.treeitems.length - 1); i >= 0; i--) { var ti = this.treeitems[i]; if (ti === currentItem) { break; } if (ti.isVisible) { nextItem = ti; } } if (nextItem) { this.setFocusToItem(nextItem); } }; TreeLinks.prototype.setFocusToPreviousItem = function (currentItem) { var prevItem = false; for (var i = 0; i < this.treeitems.length; i++) { var ti = this.treeitems[i]; if (ti === currentItem) { break; } if (ti.isVisible) { prevItem = ti; } } if (prevItem) { this.setFocusToItem(prevItem); } }; TreeLinks.prototype.setFocusToParentItem = function (currentItem) { if (currentItem.groupTreeitem) { this.setFocusToItem(currentItem.groupTreeitem); } }; TreeLinks.prototype.setFocusToFirstItem = function () { this.setFocusToItem(this.firstTreeitem); }; TreeLinks.prototype.setFocusToLastItem = function () { this.setFocusToItem(this.lastTreeitem); }; TreeLinks.prototype.expandTreeitem = function (currentItem) { if (currentItem.isExpandable) { currentItem.domNode.setAttribute('aria-expanded', true); this.updateVisibleTreeitems(); } }; TreeLinks.prototype.expandAllSiblingItems = function (currentItem) { for (var i = 0; i < this.treeitems.length; i++) { var ti = this.treeitems[i]; if ((ti.groupTreeitem === currentItem.groupTreeitem) && ti.isExpandable) { this.expandTreeitem(ti); } } }; TreeLinks.prototype.collapseTreeitem = function (currentItem) { var groupTreeitem = false; if (currentItem.isExpanded()) { groupTreeitem = currentItem; } else { groupTreeitem = currentItem.groupTreeitem; } if (groupTreeitem) { groupTreeitem.domNode.setAttribute('aria-expanded', false); this.updateVisibleTreeitems(); this.setFocusToItem(groupTreeitem); } }; TreeLinks.prototype.updateVisibleTreeitems = function () { this.firstTreeitem = this.treeitems[0]; for (var i = 0; i < this.treeitems.length; i++) { var ti = this.treeitems[i]; var parent = ti.domNode.parentNode; ti.isVisible = true; while (parent && (parent !== this.domNode)) { if (parent.getAttribute('aria-expanded') == 'false') { ti.isVisible = false; } parent = parent.parentNode; } if (ti.isVisible) { this.lastTreeitem = ti; } } }; TreeLinks.prototype.setFocusByFirstCharacter = function (currentItem, _char) { var start, index; _char = _char.toLowerCase(); // Get start index for search based on position of currentItem. start = this.treeitems.indexOf(currentItem) + 1; if (start === this.treeitems.length) { start = 0; } // Check remaining slots in the menu. index = this.getIndexFirstChars(start, _char); // If not found in remaining slots, check from beginning. if (index === -1) { index = this.getIndexFirstChars(0, _char); } // If match was found... if (index > -1) { this.setFocusToItem(this.treeitems[index]); } }; TreeLinks.prototype.getIndexFirstChars = function (startIndex, _char) { for (var i = startIndex; i < this.firstChars.length; i++) { if (this.treeitems[i].isVisible) { if (_char === this.firstChars[i]) { return i; } } } return -1; }; return TreeLinks; })(); /* jshint ignore:end */ /* jscs:enable */ /* eslint-enable */ return component; })( jQuery ); /** * Removed in 5.5.0, needed for back-compatibility. * * @since 4.9.0 * @deprecated 5.5.0 * * @type {object} */ wp.themePluginEditor.l10n = wp.themePluginEditor.l10n || { saveAlert: '', saveError: '', lintError: { alternative: 'wp.i18n', func: function() { return { singular: '', plural: '' }; } } }; wp.themePluginEditor.l10n = window.wp.deprecateL10nObject( 'wp.themePluginEditor.l10n', wp.themePluginEditor.l10n, '5.5.0' ); PK 4�Z;AK�c c password-strength-meter.min.jsnu �[��� /*! This file is auto-generated */ window.wp=window.wp||{},function(a){var e=wp.i18n.__,n=wp.i18n.sprintf;wp.passwordStrength={meter:function(e,n,t){return Array.isArray(n)||(n=[n.toString()]),e!=t&&t&&0<t.length?5:void 0===window.zxcvbn?-1:zxcvbn(e,n).score},userInputBlacklist:function(){return window.console.log(n(e("%1$s is deprecated since version %2$s! Use %3$s instead. Please consider writing more inclusive code."),"wp.passwordStrength.userInputBlacklist()","5.5.0","wp.passwordStrength.userInputDisallowedList()")),wp.passwordStrength.userInputDisallowedList()},userInputDisallowedList:function(){var e,n,t,r,s=[],i=[],o=["user_login","first_name","last_name","nickname","display_name","email","url","description","weblog_title","admin_email"];for(s.push(document.title),s.push(document.URL),n=o.length,e=0;e<n;e++)0!==(r=a("#"+o[e])).length&&(s.push(r[0].defaultValue),s.push(r.val()));for(t=s.length,e=0;e<t;e++)s[e]&&(i=i.concat(s[e].replace(/\W/g," ").split(" ")));return i=a.grep(i,function(e,n){return!(""===e||e.length<4)&&a.inArray(e,i)===n})}},window.passwordStrength=wp.passwordStrength.meter}(jQuery);PK 4�Zr�y$ $ auth-app.min.jsnu �[��� /*! This file is auto-generated */ !function(t,s){var p=t("#app_name"),r=t("#approve"),e=t("#reject"),n=p.closest("form"),i={userLogin:s.user_login,successUrl:s.success,rejectUrl:s.reject};r.on("click",function(e){var a=p.val(),o=t('input[name="app_id"]',n).val();e.preventDefault(),r.prop("aria-disabled")||(0===a.length?p.trigger("focus"):(r.prop("aria-disabled",!0).addClass("disabled"),e={name:a},0<o.length&&(e.app_id=o),e=wp.hooks.applyFilters("wp_application_passwords_approve_app_request",e,i),wp.apiRequest({path:"/wp/v2/users/me/application-passwords?_locale=user",method:"POST",data:e}).done(function(e,a,o){wp.hooks.doAction("wp_application_passwords_approve_app_request_success",e,a,o);var a=s.success;a?(o=a+(-1===a.indexOf("?")?"?":"&")+"site_url="+encodeURIComponent(s.site_url)+"&user_login="+encodeURIComponent(s.user_login)+"&password="+encodeURIComponent(e.password),window.location=o):(a=wp.i18n.sprintf('<label for="new-application-password-value">'+wp.i18n.__("Your new password for %s is:")+"</label>","<strong></strong>")+' <input id="new-application-password-value" type="text" class="code" readonly="readonly" value="" />',o=t("<div></div>").attr("role","alert").attr("tabindex",-1).addClass("notice notice-success notice-alt").append(t("<p></p>").addClass("application-password-display").html(a)).append("<p>"+wp.i18n.__("Be sure to save this in a safe location. You will not be able to retrieve it.")+"</p>"),t("strong",o).text(e.name),t("input",o).val(e.password),n.replaceWith(o),o.trigger("focus"))}).fail(function(e,a,o){var s=o,p=null,s=(e.responseJSON&&(p=e.responseJSON).message&&(s=p.message),t("<div></div>").attr("role","alert").addClass("notice notice-error").append(t("<p></p>").text(s)));t("h1").after(s),r.removeProp("aria-disabled",!1).removeClass("disabled"),wp.hooks.doAction("wp_application_passwords_approve_app_request_error",p,a,o,e)})))}),e.on("click",function(e){e.preventDefault(),wp.hooks.doAction("wp_application_passwords_reject_app",i),window.location=s.reject}),n.on("submit",function(e){e.preventDefault()})}(jQuery,authApp);PK 4�Z >iZ� � user-suggest.jsnu �[��� /** * Suggests users in a multisite environment. * * For input fields where the admin can select a user based on email or * username, this script shows an autocompletion menu for these inputs. Should * only be used in a multisite environment. Only users in the currently active * site are shown. * * @since 3.4.0 * @output wp-admin/js/user-suggest.js */ /* global ajaxurl, current_site_id, isRtl */ (function( $ ) { var id = ( typeof current_site_id !== 'undefined' ) ? '&site_id=' + current_site_id : ''; $( function() { var position = { offset: '0, -1' }; if ( typeof isRtl !== 'undefined' && isRtl ) { position.my = 'right top'; position.at = 'right bottom'; } /** * Adds an autocomplete function to input fields marked with the class * 'wp-suggest-user'. * * A minimum of two characters is required to trigger the suggestions. The * autocompletion menu is shown at the left bottom of the input field. On * RTL installations, it is shown at the right top. Adds the class 'open' to * the input field when the autocompletion menu is shown. * * Does a backend call to retrieve the users. * * Optional data-attributes: * - data-autocomplete-type (add, search) * The action that is going to be performed: search for existing users * or add a new one. Default: add * - data-autocomplete-field (user_login, user_email) * The field that is returned as the value for the suggestion. * Default: user_login * * @see wp-admin/includes/admin-actions.php:wp_ajax_autocomplete_user() */ $( '.wp-suggest-user' ).each( function(){ var $this = $( this ), autocompleteType = ( typeof $this.data( 'autocompleteType' ) !== 'undefined' ) ? $this.data( 'autocompleteType' ) : 'add', autocompleteField = ( typeof $this.data( 'autocompleteField' ) !== 'undefined' ) ? $this.data( 'autocompleteField' ) : 'user_login'; $this.autocomplete({ source: ajaxurl + '?action=autocomplete-user&autocomplete_type=' + autocompleteType + '&autocomplete_field=' + autocompleteField + id, delay: 500, minLength: 2, position: position, open: function() { $( this ).addClass( 'open' ); }, close: function() { $( this ).removeClass( 'open' ); } }); }); }); })( jQuery ); PK 4�Z.�֛�= �= widgets/custom-html-widgets.jsnu �[��� /** * @output wp-admin/js/widgets/custom-html-widgets.js */ /* global wp */ /* eslint consistent-this: [ "error", "control" ] */ /* eslint no-magic-numbers: ["error", { "ignore": [0,1,-1] }] */ /** * @namespace wp.customHtmlWidget * @memberOf wp */ wp.customHtmlWidgets = ( function( $ ) { 'use strict'; var component = { idBases: [ 'custom_html' ], codeEditorSettings: {}, l10n: { errorNotice: { singular: '', plural: '' } } }; component.CustomHtmlWidgetControl = Backbone.View.extend(/** @lends wp.customHtmlWidgets.CustomHtmlWidgetControl.prototype */{ /** * View events. * * @type {Object} */ events: {}, /** * Text widget control. * * @constructs wp.customHtmlWidgets.CustomHtmlWidgetControl * @augments Backbone.View * @abstract * * @param {Object} options - Options. * @param {jQuery} options.el - Control field container element. * @param {jQuery} options.syncContainer - Container element where fields are synced for the server. * * @return {void} */ initialize: function initialize( options ) { var control = this; if ( ! options.el ) { throw new Error( 'Missing options.el' ); } if ( ! options.syncContainer ) { throw new Error( 'Missing options.syncContainer' ); } Backbone.View.prototype.initialize.call( control, options ); control.syncContainer = options.syncContainer; control.widgetIdBase = control.syncContainer.parent().find( '.id_base' ).val(); control.widgetNumber = control.syncContainer.parent().find( '.widget_number' ).val(); control.customizeSettingId = 'widget_' + control.widgetIdBase + '[' + String( control.widgetNumber ) + ']'; control.$el.addClass( 'custom-html-widget-fields' ); control.$el.html( wp.template( 'widget-custom-html-control-fields' )( { codeEditorDisabled: component.codeEditorSettings.disabled } ) ); control.errorNoticeContainer = control.$el.find( '.code-editor-error-container' ); control.currentErrorAnnotations = []; control.saveButton = control.syncContainer.add( control.syncContainer.parent().find( '.widget-control-actions' ) ).find( '.widget-control-save, #savewidget' ); control.saveButton.addClass( 'custom-html-widget-save-button' ); // To facilitate style targeting. control.fields = { title: control.$el.find( '.title' ), content: control.$el.find( '.content' ) }; // Sync input fields to hidden sync fields which actually get sent to the server. _.each( control.fields, function( fieldInput, fieldName ) { fieldInput.on( 'input change', function updateSyncField() { var syncInput = control.syncContainer.find( '.sync-input.' + fieldName ); if ( syncInput.val() !== fieldInput.val() ) { syncInput.val( fieldInput.val() ); syncInput.trigger( 'change' ); } }); // Note that syncInput cannot be re-used because it will be destroyed with each widget-updated event. fieldInput.val( control.syncContainer.find( '.sync-input.' + fieldName ).val() ); }); }, /** * Update input fields from the sync fields. * * This function is called at the widget-updated and widget-synced events. * A field will only be updated if it is not currently focused, to avoid * overwriting content that the user is entering. * * @return {void} */ updateFields: function updateFields() { var control = this, syncInput; if ( ! control.fields.title.is( document.activeElement ) ) { syncInput = control.syncContainer.find( '.sync-input.title' ); control.fields.title.val( syncInput.val() ); } /* * Prevent updating content when the editor is focused or if there are current error annotations, * to prevent the editor's contents from getting sanitized as soon as a user removes focus from * the editor. This is particularly important for users who cannot unfiltered_html. */ control.contentUpdateBypassed = control.fields.content.is( document.activeElement ) || control.editor && control.editor.codemirror.state.focused || 0 !== control.currentErrorAnnotations.length; if ( ! control.contentUpdateBypassed ) { syncInput = control.syncContainer.find( '.sync-input.content' ); control.fields.content.val( syncInput.val() ); } }, /** * Show linting error notice. * * @param {Array} errorAnnotations - Error annotations. * @return {void} */ updateErrorNotice: function( errorAnnotations ) { var control = this, errorNotice, message = '', customizeSetting; if ( 1 === errorAnnotations.length ) { message = component.l10n.errorNotice.singular.replace( '%d', '1' ); } else if ( errorAnnotations.length > 1 ) { message = component.l10n.errorNotice.plural.replace( '%d', String( errorAnnotations.length ) ); } if ( control.fields.content[0].setCustomValidity ) { control.fields.content[0].setCustomValidity( message ); } if ( wp.customize && wp.customize.has( control.customizeSettingId ) ) { customizeSetting = wp.customize( control.customizeSettingId ); customizeSetting.notifications.remove( 'htmlhint_error' ); if ( 0 !== errorAnnotations.length ) { customizeSetting.notifications.add( 'htmlhint_error', new wp.customize.Notification( 'htmlhint_error', { message: message, type: 'error' } ) ); } } else if ( 0 !== errorAnnotations.length ) { errorNotice = $( '<div class="inline notice notice-error notice-alt" role="alert"></div>' ); errorNotice.append( $( '<p></p>', { text: message } ) ); control.errorNoticeContainer.empty(); control.errorNoticeContainer.append( errorNotice ); control.errorNoticeContainer.slideDown( 'fast' ); wp.a11y.speak( message ); } else { control.errorNoticeContainer.slideUp( 'fast' ); } }, /** * Initialize editor. * * @return {void} */ initializeEditor: function initializeEditor() { var control = this, settings; if ( component.codeEditorSettings.disabled ) { return; } settings = _.extend( {}, component.codeEditorSettings, { /** * Handle tabbing to the field before the editor. * * @ignore * * @return {void} */ onTabPrevious: function onTabPrevious() { control.fields.title.focus(); }, /** * Handle tabbing to the field after the editor. * * @ignore * * @return {void} */ onTabNext: function onTabNext() { var tabbables = control.syncContainer.add( control.syncContainer.parent().find( '.widget-position, .widget-control-actions' ) ).find( ':tabbable' ); tabbables.first().focus(); }, /** * Disable save button and store linting errors for use in updateFields. * * @ignore * * @param {Array} errorAnnotations - Error notifications. * @return {void} */ onChangeLintingErrors: function onChangeLintingErrors( errorAnnotations ) { control.currentErrorAnnotations = errorAnnotations; }, /** * Update error notice. * * @ignore * * @param {Array} errorAnnotations - Error annotations. * @return {void} */ onUpdateErrorNotice: function onUpdateErrorNotice( errorAnnotations ) { control.saveButton.toggleClass( 'validation-blocked disabled', errorAnnotations.length > 0 ); control.updateErrorNotice( errorAnnotations ); } }); control.editor = wp.codeEditor.initialize( control.fields.content, settings ); // Improve the editor accessibility. $( control.editor.codemirror.display.lineDiv ) .attr({ role: 'textbox', 'aria-multiline': 'true', 'aria-labelledby': control.fields.content[0].id + '-label', 'aria-describedby': 'editor-keyboard-trap-help-1 editor-keyboard-trap-help-2 editor-keyboard-trap-help-3 editor-keyboard-trap-help-4' }); // Focus the editor when clicking on its label. $( '#' + control.fields.content[0].id + '-label' ).on( 'click', function() { control.editor.codemirror.focus(); }); control.fields.content.on( 'change', function() { if ( this.value !== control.editor.codemirror.getValue() ) { control.editor.codemirror.setValue( this.value ); } }); control.editor.codemirror.on( 'change', function() { var value = control.editor.codemirror.getValue(); if ( value !== control.fields.content.val() ) { control.fields.content.val( value ).trigger( 'change' ); } }); // Make sure the editor gets updated if the content was updated on the server (sanitization) but not updated in the editor since it was focused. control.editor.codemirror.on( 'blur', function() { if ( control.contentUpdateBypassed ) { control.syncContainer.find( '.sync-input.content' ).trigger( 'change' ); } }); // Prevent hitting Esc from collapsing the widget control. if ( wp.customize ) { control.editor.codemirror.on( 'keydown', function onKeydown( codemirror, event ) { var escKeyCode = 27; if ( escKeyCode === event.keyCode ) { event.stopPropagation(); } }); } } }); /** * Mapping of widget ID to instances of CustomHtmlWidgetControl subclasses. * * @alias wp.customHtmlWidgets.widgetControls * * @type {Object.<string, wp.textWidgets.CustomHtmlWidgetControl>} */ component.widgetControls = {}; /** * Handle widget being added or initialized for the first time at the widget-added event. * * @alias wp.customHtmlWidgets.handleWidgetAdded * * @param {jQuery.Event} event - Event. * @param {jQuery} widgetContainer - Widget container element. * * @return {void} */ component.handleWidgetAdded = function handleWidgetAdded( event, widgetContainer ) { var widgetForm, idBase, widgetControl, widgetId, animatedCheckDelay = 50, renderWhenAnimationDone, fieldContainer, syncContainer; widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' ); // Note: '.form' appears in the customizer, whereas 'form' on the widgets admin screen. idBase = widgetForm.find( '> .id_base' ).val(); if ( -1 === component.idBases.indexOf( idBase ) ) { return; } // Prevent initializing already-added widgets. widgetId = widgetForm.find( '.widget-id' ).val(); if ( component.widgetControls[ widgetId ] ) { return; } /* * Create a container element for the widget control fields. * This is inserted into the DOM immediately before the the .widget-content * element because the contents of this element are essentially "managed" * by PHP, where each widget update cause the entire element to be emptied * and replaced with the rendered output of WP_Widget::form() which is * sent back in Ajax request made to save/update the widget instance. * To prevent a "flash of replaced DOM elements and re-initialized JS * components", the JS template is rendered outside of the normal form * container. */ fieldContainer = $( '<div></div>' ); syncContainer = widgetContainer.find( '.widget-content:first' ); syncContainer.before( fieldContainer ); widgetControl = new component.CustomHtmlWidgetControl({ el: fieldContainer, syncContainer: syncContainer }); component.widgetControls[ widgetId ] = widgetControl; /* * Render the widget once the widget parent's container finishes animating, * as the widget-added event fires with a slideDown of the container. * This ensures that the textarea is visible and the editor can be initialized. */ renderWhenAnimationDone = function() { if ( ! ( wp.customize ? widgetContainer.parent().hasClass( 'expanded' ) : widgetContainer.hasClass( 'open' ) ) ) { // Core merge: The wp.customize condition can be eliminated with this change being in core: https://github.com/xwp/wordpress-develop/pull/247/commits/5322387d setTimeout( renderWhenAnimationDone, animatedCheckDelay ); } else { widgetControl.initializeEditor(); } }; renderWhenAnimationDone(); }; /** * Setup widget in accessibility mode. * * @alias wp.customHtmlWidgets.setupAccessibleMode * * @return {void} */ component.setupAccessibleMode = function setupAccessibleMode() { var widgetForm, idBase, widgetControl, fieldContainer, syncContainer; widgetForm = $( '.editwidget > form' ); if ( 0 === widgetForm.length ) { return; } idBase = widgetForm.find( '.id_base' ).val(); if ( -1 === component.idBases.indexOf( idBase ) ) { return; } fieldContainer = $( '<div></div>' ); syncContainer = widgetForm.find( '> .widget-inside' ); syncContainer.before( fieldContainer ); widgetControl = new component.CustomHtmlWidgetControl({ el: fieldContainer, syncContainer: syncContainer }); widgetControl.initializeEditor(); }; /** * Sync widget instance data sanitized from server back onto widget model. * * This gets called via the 'widget-updated' event when saving a widget from * the widgets admin screen and also via the 'widget-synced' event when making * a change to a widget in the customizer. * * @alias wp.customHtmlWidgets.handleWidgetUpdated * * @param {jQuery.Event} event - Event. * @param {jQuery} widgetContainer - Widget container element. * @return {void} */ component.handleWidgetUpdated = function handleWidgetUpdated( event, widgetContainer ) { var widgetForm, widgetId, widgetControl, idBase; widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' ); idBase = widgetForm.find( '> .id_base' ).val(); if ( -1 === component.idBases.indexOf( idBase ) ) { return; } widgetId = widgetForm.find( '> .widget-id' ).val(); widgetControl = component.widgetControls[ widgetId ]; if ( ! widgetControl ) { return; } widgetControl.updateFields(); }; /** * Initialize functionality. * * This function exists to prevent the JS file from having to boot itself. * When WordPress enqueues this script, it should have an inline script * attached which calls wp.textWidgets.init(). * * @alias wp.customHtmlWidgets.init * * @param {Object} settings - Options for code editor, exported from PHP. * * @return {void} */ component.init = function init( settings ) { var $document = $( document ); _.extend( component.codeEditorSettings, settings ); $document.on( 'widget-added', component.handleWidgetAdded ); $document.on( 'widget-synced widget-updated', component.handleWidgetUpdated ); /* * Manually trigger widget-added events for media widgets on the admin * screen once they are expanded. The widget-added event is not triggered * for each pre-existing widget on the widgets admin screen like it is * on the customizer. Likewise, the customizer only triggers widget-added * when the widget is expanded to just-in-time construct the widget form * when it is actually going to be displayed. So the following implements * the same for the widgets admin screen, to invoke the widget-added * handler when a pre-existing media widget is expanded. */ $( function initializeExistingWidgetContainers() { var widgetContainers; if ( 'widgets' !== window.pagenow ) { return; } widgetContainers = $( '.widgets-holder-wrap:not(#available-widgets)' ).find( 'div.widget' ); widgetContainers.one( 'click.toggle-widget-expanded', function toggleWidgetExpanded() { var widgetContainer = $( this ); component.handleWidgetAdded( new jQuery.Event( 'widget-added' ), widgetContainer ); }); // Accessibility mode. if ( document.readyState === 'complete' ) { // Page is fully loaded. component.setupAccessibleMode(); } else { // Page is still loading. $( window ).on( 'load', function() { component.setupAccessibleMode(); }); } }); }; return component; })( jQuery ); PK 4�Z'��p� p� widgets/media-widgets.jsnu �[��� /** * @output wp-admin/js/widgets/media-widgets.js */ /* eslint consistent-this: [ "error", "control" ] */ /** * @namespace wp.mediaWidgets * @memberOf wp */ wp.mediaWidgets = ( function( $ ) { 'use strict'; var component = {}; /** * Widget control (view) constructors, mapping widget id_base to subclass of MediaWidgetControl. * * Media widgets register themselves by assigning subclasses of MediaWidgetControl onto this object by widget ID base. * * @memberOf wp.mediaWidgets * * @type {Object.<string, wp.mediaWidgets.MediaWidgetModel>} */ component.controlConstructors = {}; /** * Widget model constructors, mapping widget id_base to subclass of MediaWidgetModel. * * Media widgets register themselves by assigning subclasses of MediaWidgetControl onto this object by widget ID base. * * @memberOf wp.mediaWidgets * * @type {Object.<string, wp.mediaWidgets.MediaWidgetModel>} */ component.modelConstructors = {}; component.PersistentDisplaySettingsLibrary = wp.media.controller.Library.extend(/** @lends wp.mediaWidgets.PersistentDisplaySettingsLibrary.prototype */{ /** * Library which persists the customized display settings across selections. * * @constructs wp.mediaWidgets.PersistentDisplaySettingsLibrary * @augments wp.media.controller.Library * * @param {Object} options - Options. * * @return {void} */ initialize: function initialize( options ) { _.bindAll( this, 'handleDisplaySettingChange' ); wp.media.controller.Library.prototype.initialize.call( this, options ); }, /** * Sync changes to the current display settings back into the current customized. * * @param {Backbone.Model} displaySettings - Modified display settings. * @return {void} */ handleDisplaySettingChange: function handleDisplaySettingChange( displaySettings ) { this.get( 'selectedDisplaySettings' ).set( displaySettings.attributes ); }, /** * Get the display settings model. * * Model returned is updated with the current customized display settings, * and an event listener is added so that changes made to the settings * will sync back into the model storing the session's customized display * settings. * * @param {Backbone.Model} model - Display settings model. * @return {Backbone.Model} Display settings model. */ display: function getDisplaySettingsModel( model ) { var display, selectedDisplaySettings = this.get( 'selectedDisplaySettings' ); display = wp.media.controller.Library.prototype.display.call( this, model ); display.off( 'change', this.handleDisplaySettingChange ); // Prevent duplicated event handlers. display.set( selectedDisplaySettings.attributes ); if ( 'custom' === selectedDisplaySettings.get( 'link_type' ) ) { display.linkUrl = selectedDisplaySettings.get( 'link_url' ); } display.on( 'change', this.handleDisplaySettingChange ); return display; } }); /** * Extended view for managing the embed UI. * * @class wp.mediaWidgets.MediaEmbedView * @augments wp.media.view.Embed */ component.MediaEmbedView = wp.media.view.Embed.extend(/** @lends wp.mediaWidgets.MediaEmbedView.prototype */{ /** * Initialize. * * @since 4.9.0 * * @param {Object} options - Options. * @return {void} */ initialize: function( options ) { var view = this, embedController; // eslint-disable-line consistent-this wp.media.view.Embed.prototype.initialize.call( view, options ); if ( 'image' !== view.controller.options.mimeType ) { embedController = view.controller.states.get( 'embed' ); embedController.off( 'scan', embedController.scanImage, embedController ); } }, /** * Refresh embed view. * * Forked override of {wp.media.view.Embed#refresh()} to suppress irrelevant "link text" field. * * @return {void} */ refresh: function refresh() { /** * @class wp.mediaWidgets~Constructor */ var Constructor; if ( 'image' === this.controller.options.mimeType ) { Constructor = wp.media.view.EmbedImage; } else { // This should be eliminated once #40450 lands of when this is merged into core. Constructor = wp.media.view.EmbedLink.extend(/** @lends wp.mediaWidgets~Constructor.prototype */{ /** * Set the disabled state on the Add to Widget button. * * @param {boolean} disabled - Disabled. * @return {void} */ setAddToWidgetButtonDisabled: function setAddToWidgetButtonDisabled( disabled ) { this.views.parent.views.parent.views.get( '.media-frame-toolbar' )[0].$el.find( '.media-button-select' ).prop( 'disabled', disabled ); }, /** * Set or clear an error notice. * * @param {string} notice - Notice. * @return {void} */ setErrorNotice: function setErrorNotice( notice ) { var embedLinkView = this, noticeContainer; // eslint-disable-line consistent-this noticeContainer = embedLinkView.views.parent.$el.find( '> .notice:first-child' ); if ( ! notice ) { if ( noticeContainer.length ) { noticeContainer.slideUp( 'fast' ); } } else { if ( ! noticeContainer.length ) { noticeContainer = $( '<div class="media-widget-embed-notice notice notice-error notice-alt" role="alert"></div>' ); noticeContainer.hide(); embedLinkView.views.parent.$el.prepend( noticeContainer ); } noticeContainer.empty(); noticeContainer.append( $( '<p>', { html: notice })); noticeContainer.slideDown( 'fast' ); } }, /** * Update oEmbed. * * @since 4.9.0 * * @return {void} */ updateoEmbed: function() { var embedLinkView = this, url; // eslint-disable-line consistent-this url = embedLinkView.model.get( 'url' ); // Abort if the URL field was emptied out. if ( ! url ) { embedLinkView.setErrorNotice( '' ); embedLinkView.setAddToWidgetButtonDisabled( true ); return; } if ( ! url.match( /^(http|https):\/\/.+\// ) ) { embedLinkView.controller.$el.find( '#embed-url-field' ).addClass( 'invalid' ); embedLinkView.setAddToWidgetButtonDisabled( true ); } wp.media.view.EmbedLink.prototype.updateoEmbed.call( embedLinkView ); }, /** * Fetch media. * * @return {void} */ fetch: function() { var embedLinkView = this, fetchSuccess, matches, fileExt, urlParser, url, re, youTubeEmbedMatch; // eslint-disable-line consistent-this url = embedLinkView.model.get( 'url' ); if ( embedLinkView.dfd && 'pending' === embedLinkView.dfd.state() ) { embedLinkView.dfd.abort(); } fetchSuccess = function( response ) { embedLinkView.renderoEmbed({ data: { body: response } }); embedLinkView.controller.$el.find( '#embed-url-field' ).removeClass( 'invalid' ); embedLinkView.setErrorNotice( '' ); embedLinkView.setAddToWidgetButtonDisabled( false ); }; urlParser = document.createElement( 'a' ); urlParser.href = url; matches = urlParser.pathname.toLowerCase().match( /\.(\w+)$/ ); if ( matches ) { fileExt = matches[1]; if ( ! wp.media.view.settings.embedMimes[ fileExt ] ) { embedLinkView.renderFail(); } else if ( 0 !== wp.media.view.settings.embedMimes[ fileExt ].indexOf( embedLinkView.controller.options.mimeType ) ) { embedLinkView.renderFail(); } else { fetchSuccess( '<!--success-->' ); } return; } // Support YouTube embed links. re = /https?:\/\/www\.youtube\.com\/embed\/([^/]+)/; youTubeEmbedMatch = re.exec( url ); if ( youTubeEmbedMatch ) { url = 'https://www.youtube.com/watch?v=' + youTubeEmbedMatch[ 1 ]; // silently change url to proper oembed-able version. embedLinkView.model.attributes.url = url; } embedLinkView.dfd = wp.apiRequest({ url: wp.media.view.settings.oEmbedProxyUrl, data: { url: url, maxwidth: embedLinkView.model.get( 'width' ), maxheight: embedLinkView.model.get( 'height' ), discover: false }, type: 'GET', dataType: 'json', context: embedLinkView }); embedLinkView.dfd.done( function( response ) { if ( embedLinkView.controller.options.mimeType !== response.type ) { embedLinkView.renderFail(); return; } fetchSuccess( response.html ); }); embedLinkView.dfd.fail( _.bind( embedLinkView.renderFail, embedLinkView ) ); }, /** * Handle render failure. * * Overrides the {EmbedLink#renderFail()} method to prevent showing the "Link Text" field. * The element is getting display:none in the stylesheet, but the underlying method uses * uses {jQuery.fn.show()} which adds an inline style. This avoids the need for !important. * * @return {void} */ renderFail: function renderFail() { var embedLinkView = this; // eslint-disable-line consistent-this embedLinkView.controller.$el.find( '#embed-url-field' ).addClass( 'invalid' ); embedLinkView.setErrorNotice( embedLinkView.controller.options.invalidEmbedTypeError || 'ERROR' ); embedLinkView.setAddToWidgetButtonDisabled( true ); } }); } this.settings( new Constructor({ controller: this.controller, model: this.model.props, priority: 40 })); } }); /** * Custom media frame for selecting uploaded media or providing media by URL. * * @class wp.mediaWidgets.MediaFrameSelect * @augments wp.media.view.MediaFrame.Post */ component.MediaFrameSelect = wp.media.view.MediaFrame.Post.extend(/** @lends wp.mediaWidgets.MediaFrameSelect.prototype */{ /** * Create the default states. * * @return {void} */ createStates: function createStates() { var mime = this.options.mimeType, specificMimes = []; _.each( wp.media.view.settings.embedMimes, function( embedMime ) { if ( 0 === embedMime.indexOf( mime ) ) { specificMimes.push( embedMime ); } }); if ( specificMimes.length > 0 ) { mime = specificMimes; } this.states.add([ // Main states. new component.PersistentDisplaySettingsLibrary({ id: 'insert', title: this.options.title, selection: this.options.selection, priority: 20, toolbar: 'main-insert', filterable: 'dates', library: wp.media.query({ type: mime }), multiple: false, editable: true, selectedDisplaySettings: this.options.selectedDisplaySettings, displaySettings: _.isUndefined( this.options.showDisplaySettings ) ? true : this.options.showDisplaySettings, displayUserSettings: false // We use the display settings from the current/default widget instance props. }), new wp.media.controller.EditImage({ model: this.options.editImage }), // Embed states. new wp.media.controller.Embed({ metadata: this.options.metadata, type: 'image' === this.options.mimeType ? 'image' : 'link', invalidEmbedTypeError: this.options.invalidEmbedTypeError }) ]); }, /** * Main insert toolbar. * * Forked override of {wp.media.view.MediaFrame.Post#mainInsertToolbar()} to override text. * * @param {wp.Backbone.View} view - Toolbar view. * @this {wp.media.controller.Library} * @return {void} */ mainInsertToolbar: function mainInsertToolbar( view ) { var controller = this; // eslint-disable-line consistent-this view.set( 'insert', { style: 'primary', priority: 80, text: controller.options.text, // The whole reason for the fork. requires: { selection: true }, /** * Handle click. * * @ignore * * @fires wp.media.controller.State#insert() * @return {void} */ click: function onClick() { var state = controller.state(), selection = state.get( 'selection' ); controller.close(); state.trigger( 'insert', selection ).reset(); } }); }, /** * Main embed toolbar. * * Forked override of {wp.media.view.MediaFrame.Post#mainEmbedToolbar()} to override text. * * @param {wp.Backbone.View} toolbar - Toolbar view. * @this {wp.media.controller.Library} * @return {void} */ mainEmbedToolbar: function mainEmbedToolbar( toolbar ) { toolbar.view = new wp.media.view.Toolbar.Embed({ controller: this, text: this.options.text, event: 'insert' }); }, /** * Embed content. * * Forked override of {wp.media.view.MediaFrame.Post#embedContent()} to suppress irrelevant "link text" field. * * @return {void} */ embedContent: function embedContent() { var view = new component.MediaEmbedView({ controller: this, model: this.state() }).render(); this.content.set( view ); } }); component.MediaWidgetControl = Backbone.View.extend(/** @lends wp.mediaWidgets.MediaWidgetControl.prototype */{ /** * Translation strings. * * The mapping of translation strings is handled by media widget subclasses, * exported from PHP to JS such as is done in WP_Widget_Media_Image::enqueue_admin_scripts(). * * @type {Object} */ l10n: { add_to_widget: '{{add_to_widget}}', add_media: '{{add_media}}' }, /** * Widget ID base. * * This may be defined by the subclass. It may be exported from PHP to JS * such as is done in WP_Widget_Media_Image::enqueue_admin_scripts(). If not, * it will attempt to be discovered by looking to see if this control * instance extends each member of component.controlConstructors, and if * it does extend one, will use the key as the id_base. * * @type {string} */ id_base: '', /** * Mime type. * * This must be defined by the subclass. It may be exported from PHP to JS * such as is done in WP_Widget_Media_Image::enqueue_admin_scripts(). * * @type {string} */ mime_type: '', /** * View events. * * @type {Object} */ events: { 'click .notice-missing-attachment a': 'handleMediaLibraryLinkClick', 'click .select-media': 'selectMedia', 'click .placeholder': 'selectMedia', 'click .edit-media': 'editMedia' }, /** * Show display settings. * * @type {boolean} */ showDisplaySettings: true, /** * Media Widget Control. * * @constructs wp.mediaWidgets.MediaWidgetControl * @augments Backbone.View * @abstract * * @param {Object} options - Options. * @param {Backbone.Model} options.model - Model. * @param {jQuery} options.el - Control field container element. * @param {jQuery} options.syncContainer - Container element where fields are synced for the server. * * @return {void} */ initialize: function initialize( options ) { var control = this; Backbone.View.prototype.initialize.call( control, options ); if ( ! ( control.model instanceof component.MediaWidgetModel ) ) { throw new Error( 'Missing options.model' ); } if ( ! options.el ) { throw new Error( 'Missing options.el' ); } if ( ! options.syncContainer ) { throw new Error( 'Missing options.syncContainer' ); } control.syncContainer = options.syncContainer; control.$el.addClass( 'media-widget-control' ); // Allow methods to be passed in with control context preserved. _.bindAll( control, 'syncModelToInputs', 'render', 'updateSelectedAttachment', 'renderPreview' ); if ( ! control.id_base ) { _.find( component.controlConstructors, function( Constructor, idBase ) { if ( control instanceof Constructor ) { control.id_base = idBase; return true; } return false; }); if ( ! control.id_base ) { throw new Error( 'Missing id_base.' ); } } // Track attributes needed to renderPreview in it's own model. control.previewTemplateProps = new Backbone.Model( control.mapModelToPreviewTemplateProps() ); // Re-render the preview when the attachment changes. control.selectedAttachment = new wp.media.model.Attachment(); control.renderPreview = _.debounce( control.renderPreview ); control.listenTo( control.previewTemplateProps, 'change', control.renderPreview ); // Make sure a copy of the selected attachment is always fetched. control.model.on( 'change:attachment_id', control.updateSelectedAttachment ); control.model.on( 'change:url', control.updateSelectedAttachment ); control.updateSelectedAttachment(); /* * Sync the widget instance model attributes onto the hidden inputs that widgets currently use to store the state. * In the future, when widgets are JS-driven, the underlying widget instance data should be exposed as a model * from the start, without having to sync with hidden fields. See <https://core.trac.wordpress.org/ticket/33507>. */ control.listenTo( control.model, 'change', control.syncModelToInputs ); control.listenTo( control.model, 'change', control.syncModelToPreviewProps ); control.listenTo( control.model, 'change', control.render ); // Update the title. control.$el.on( 'input change', '.title', function updateTitle() { control.model.set({ title: $( this ).val().trim() }); }); // Update link_url attribute. control.$el.on( 'input change', '.link', function updateLinkUrl() { var linkUrl = $( this ).val().trim(), linkType = 'custom'; if ( control.selectedAttachment.get( 'linkUrl' ) === linkUrl || control.selectedAttachment.get( 'link' ) === linkUrl ) { linkType = 'post'; } else if ( control.selectedAttachment.get( 'url' ) === linkUrl ) { linkType = 'file'; } control.model.set( { link_url: linkUrl, link_type: linkType }); // Update display settings for the next time the user opens to select from the media library. control.displaySettings.set( { link: linkType, linkUrl: linkUrl }); }); /* * Copy current display settings from the widget model to serve as basis * of customized display settings for the current media frame session. * Changes to display settings will be synced into this model, and * when a new selection is made, the settings from this will be synced * into that AttachmentDisplay's model to persist the setting changes. */ control.displaySettings = new Backbone.Model( _.pick( control.mapModelToMediaFrameProps( _.extend( control.model.defaults(), control.model.toJSON() ) ), _.keys( wp.media.view.settings.defaultProps ) ) ); }, /** * Update the selected attachment if necessary. * * @return {void} */ updateSelectedAttachment: function updateSelectedAttachment() { var control = this, attachment; if ( 0 === control.model.get( 'attachment_id' ) ) { control.selectedAttachment.clear(); control.model.set( 'error', false ); } else if ( control.model.get( 'attachment_id' ) !== control.selectedAttachment.get( 'id' ) ) { attachment = new wp.media.model.Attachment({ id: control.model.get( 'attachment_id' ) }); attachment.fetch() .done( function done() { control.model.set( 'error', false ); control.selectedAttachment.set( attachment.toJSON() ); }) .fail( function fail() { control.model.set( 'error', 'missing_attachment' ); }); } }, /** * Sync the model attributes to the hidden inputs, and update previewTemplateProps. * * @return {void} */ syncModelToPreviewProps: function syncModelToPreviewProps() { var control = this; control.previewTemplateProps.set( control.mapModelToPreviewTemplateProps() ); }, /** * Sync the model attributes to the hidden inputs, and update previewTemplateProps. * * @return {void} */ syncModelToInputs: function syncModelToInputs() { var control = this; control.syncContainer.find( '.media-widget-instance-property' ).each( function() { var input = $( this ), value, propertyName; propertyName = input.data( 'property' ); value = control.model.get( propertyName ); if ( _.isUndefined( value ) ) { return; } if ( 'array' === control.model.schema[ propertyName ].type && _.isArray( value ) ) { value = value.join( ',' ); } else if ( 'boolean' === control.model.schema[ propertyName ].type ) { value = value ? '1' : ''; // Because in PHP, strval( true ) === '1' && strval( false ) === ''. } else { value = String( value ); } if ( input.val() !== value ) { input.val( value ); input.trigger( 'change' ); } }); }, /** * Get template. * * @return {Function} Template. */ template: function template() { var control = this; if ( ! $( '#tmpl-widget-media-' + control.id_base + '-control' ).length ) { throw new Error( 'Missing widget control template for ' + control.id_base ); } return wp.template( 'widget-media-' + control.id_base + '-control' ); }, /** * Render template. * * @return {void} */ render: function render() { var control = this, titleInput; if ( ! control.templateRendered ) { control.$el.html( control.template()( control.model.toJSON() ) ); control.renderPreview(); // Hereafter it will re-render when control.selectedAttachment changes. control.templateRendered = true; } titleInput = control.$el.find( '.title' ); if ( ! titleInput.is( document.activeElement ) ) { titleInput.val( control.model.get( 'title' ) ); } control.$el.toggleClass( 'selected', control.isSelected() ); }, /** * Render media preview. * * @abstract * @return {void} */ renderPreview: function renderPreview() { throw new Error( 'renderPreview must be implemented' ); }, /** * Whether a media item is selected. * * @return {boolean} Whether selected and no error. */ isSelected: function isSelected() { var control = this; if ( control.model.get( 'error' ) ) { return false; } return Boolean( control.model.get( 'attachment_id' ) || control.model.get( 'url' ) ); }, /** * Handle click on link to Media Library to open modal, such as the link that appears when in the missing attachment error notice. * * @param {jQuery.Event} event - Event. * @return {void} */ handleMediaLibraryLinkClick: function handleMediaLibraryLinkClick( event ) { var control = this; event.preventDefault(); control.selectMedia(); }, /** * Open the media select frame to chose an item. * * @return {void} */ selectMedia: function selectMedia() { var control = this, selection, mediaFrame, defaultSync, mediaFrameProps, selectionModels = []; if ( control.isSelected() && 0 !== control.model.get( 'attachment_id' ) ) { selectionModels.push( control.selectedAttachment ); } selection = new wp.media.model.Selection( selectionModels, { multiple: false } ); mediaFrameProps = control.mapModelToMediaFrameProps( control.model.toJSON() ); if ( mediaFrameProps.size ) { control.displaySettings.set( 'size', mediaFrameProps.size ); } mediaFrame = new component.MediaFrameSelect({ title: control.l10n.add_media, frame: 'post', text: control.l10n.add_to_widget, selection: selection, mimeType: control.mime_type, selectedDisplaySettings: control.displaySettings, showDisplaySettings: control.showDisplaySettings, metadata: mediaFrameProps, state: control.isSelected() && 0 === control.model.get( 'attachment_id' ) ? 'embed' : 'insert', invalidEmbedTypeError: control.l10n.unsupported_file_type }); wp.media.frame = mediaFrame; // See wp.media(). // Handle selection of a media item. mediaFrame.on( 'insert', function onInsert() { var attachment = {}, state = mediaFrame.state(); // Update cached attachment object to avoid having to re-fetch. This also triggers re-rendering of preview. if ( 'embed' === state.get( 'id' ) ) { _.extend( attachment, { id: 0 }, state.props.toJSON() ); } else { _.extend( attachment, state.get( 'selection' ).first().toJSON() ); } control.selectedAttachment.set( attachment ); control.model.set( 'error', false ); // Update widget instance. control.model.set( control.getModelPropsFromMediaFrame( mediaFrame ) ); }); // Disable syncing of attachment changes back to server (except for deletions). See <https://core.trac.wordpress.org/ticket/40403>. defaultSync = wp.media.model.Attachment.prototype.sync; wp.media.model.Attachment.prototype.sync = function( method ) { if ( 'delete' === method ) { return defaultSync.apply( this, arguments ); } else { return $.Deferred().rejectWith( this ).promise(); } }; mediaFrame.on( 'close', function onClose() { wp.media.model.Attachment.prototype.sync = defaultSync; }); mediaFrame.$el.addClass( 'media-widget' ); mediaFrame.open(); // Clear the selected attachment when it is deleted in the media select frame. if ( selection ) { selection.on( 'destroy', function onDestroy( attachment ) { if ( control.model.get( 'attachment_id' ) === attachment.get( 'id' ) ) { control.model.set({ attachment_id: 0, url: '' }); } }); } /* * Make sure focus is set inside of modal so that hitting Esc will close * the modal and not inadvertently cause the widget to collapse in the customizer. */ mediaFrame.$el.find( '.media-frame-menu .media-menu-item.active' ).focus(); }, /** * Get the instance props from the media selection frame. * * @param {wp.media.view.MediaFrame.Select} mediaFrame - Select frame. * @return {Object} Props. */ getModelPropsFromMediaFrame: function getModelPropsFromMediaFrame( mediaFrame ) { var control = this, state, mediaFrameProps, modelProps; state = mediaFrame.state(); if ( 'insert' === state.get( 'id' ) ) { mediaFrameProps = state.get( 'selection' ).first().toJSON(); mediaFrameProps.postUrl = mediaFrameProps.link; if ( control.showDisplaySettings ) { _.extend( mediaFrameProps, mediaFrame.content.get( '.attachments-browser' ).sidebar.get( 'display' ).model.toJSON() ); } if ( mediaFrameProps.sizes && mediaFrameProps.size && mediaFrameProps.sizes[ mediaFrameProps.size ] ) { mediaFrameProps.url = mediaFrameProps.sizes[ mediaFrameProps.size ].url; } } else if ( 'embed' === state.get( 'id' ) ) { mediaFrameProps = _.extend( state.props.toJSON(), { attachment_id: 0 }, // Because some media frames use `attachment_id` not `id`. control.model.getEmbedResetProps() ); } else { throw new Error( 'Unexpected state: ' + state.get( 'id' ) ); } if ( mediaFrameProps.id ) { mediaFrameProps.attachment_id = mediaFrameProps.id; } modelProps = control.mapMediaToModelProps( mediaFrameProps ); // Clear the extension prop so sources will be reset for video and audio media. _.each( wp.media.view.settings.embedExts, function( ext ) { if ( ext in control.model.schema && modelProps.url !== modelProps[ ext ] ) { modelProps[ ext ] = ''; } }); return modelProps; }, /** * Map media frame props to model props. * * @param {Object} mediaFrameProps - Media frame props. * @return {Object} Model props. */ mapMediaToModelProps: function mapMediaToModelProps( mediaFrameProps ) { var control = this, mediaFramePropToModelPropMap = {}, modelProps = {}, extension; _.each( control.model.schema, function( fieldSchema, modelProp ) { // Ignore widget title attribute. if ( 'title' === modelProp ) { return; } mediaFramePropToModelPropMap[ fieldSchema.media_prop || modelProp ] = modelProp; }); _.each( mediaFrameProps, function( value, mediaProp ) { var propName = mediaFramePropToModelPropMap[ mediaProp ] || mediaProp; if ( control.model.schema[ propName ] ) { modelProps[ propName ] = value; } }); if ( 'custom' === mediaFrameProps.size ) { modelProps.width = mediaFrameProps.customWidth; modelProps.height = mediaFrameProps.customHeight; } if ( 'post' === mediaFrameProps.link ) { modelProps.link_url = mediaFrameProps.postUrl || mediaFrameProps.linkUrl; } else if ( 'file' === mediaFrameProps.link ) { modelProps.link_url = mediaFrameProps.url; } // Because some media frames use `id` instead of `attachment_id`. if ( ! mediaFrameProps.attachment_id && mediaFrameProps.id ) { modelProps.attachment_id = mediaFrameProps.id; } if ( mediaFrameProps.url ) { extension = mediaFrameProps.url.replace( /#.*$/, '' ).replace( /\?.*$/, '' ).split( '.' ).pop().toLowerCase(); if ( extension in control.model.schema ) { modelProps[ extension ] = mediaFrameProps.url; } } // Always omit the titles derived from mediaFrameProps. return _.omit( modelProps, 'title' ); }, /** * Map model props to media frame props. * * @param {Object} modelProps - Model props. * @return {Object} Media frame props. */ mapModelToMediaFrameProps: function mapModelToMediaFrameProps( modelProps ) { var control = this, mediaFrameProps = {}; _.each( modelProps, function( value, modelProp ) { var fieldSchema = control.model.schema[ modelProp ] || {}; mediaFrameProps[ fieldSchema.media_prop || modelProp ] = value; }); // Some media frames use attachment_id. mediaFrameProps.attachment_id = mediaFrameProps.id; if ( 'custom' === mediaFrameProps.size ) { mediaFrameProps.customWidth = control.model.get( 'width' ); mediaFrameProps.customHeight = control.model.get( 'height' ); } return mediaFrameProps; }, /** * Map model props to previewTemplateProps. * * @return {Object} Preview Template Props. */ mapModelToPreviewTemplateProps: function mapModelToPreviewTemplateProps() { var control = this, previewTemplateProps = {}; _.each( control.model.schema, function( value, prop ) { if ( ! value.hasOwnProperty( 'should_preview_update' ) || value.should_preview_update ) { previewTemplateProps[ prop ] = control.model.get( prop ); } }); // Templates need to be aware of the error. previewTemplateProps.error = control.model.get( 'error' ); return previewTemplateProps; }, /** * Open the media frame to modify the selected item. * * @abstract * @return {void} */ editMedia: function editMedia() { throw new Error( 'editMedia not implemented' ); } }); /** * Media widget model. * * @class wp.mediaWidgets.MediaWidgetModel * @augments Backbone.Model */ component.MediaWidgetModel = Backbone.Model.extend(/** @lends wp.mediaWidgets.MediaWidgetModel.prototype */{ /** * Id attribute. * * @type {string} */ idAttribute: 'widget_id', /** * Instance schema. * * This adheres to JSON Schema and subclasses should have their schema * exported from PHP to JS such as is done in WP_Widget_Media_Image::enqueue_admin_scripts(). * * @type {Object.<string, Object>} */ schema: { title: { type: 'string', 'default': '' }, attachment_id: { type: 'integer', 'default': 0 }, url: { type: 'string', 'default': '' } }, /** * Get default attribute values. * * @return {Object} Mapping of property names to their default values. */ defaults: function() { var defaults = {}; _.each( this.schema, function( fieldSchema, field ) { defaults[ field ] = fieldSchema['default']; }); return defaults; }, /** * Set attribute value(s). * * This is a wrapped version of Backbone.Model#set() which allows us to * cast the attribute values from the hidden inputs' string values into * the appropriate data types (integers or booleans). * * @param {string|Object} key - Attribute name or attribute pairs. * @param {mixed|Object} [val] - Attribute value or options object. * @param {Object} [options] - Options when attribute name and value are passed separately. * @return {wp.mediaWidgets.MediaWidgetModel} This model. */ set: function set( key, val, options ) { var model = this, attrs, opts, castedAttrs; // eslint-disable-line consistent-this if ( null === key ) { return model; } if ( 'object' === typeof key ) { attrs = key; opts = val; } else { attrs = {}; attrs[ key ] = val; opts = options; } castedAttrs = {}; _.each( attrs, function( value, name ) { var type; if ( ! model.schema[ name ] ) { castedAttrs[ name ] = value; return; } type = model.schema[ name ].type; if ( 'array' === type ) { castedAttrs[ name ] = value; if ( ! _.isArray( castedAttrs[ name ] ) ) { castedAttrs[ name ] = castedAttrs[ name ].split( /,/ ); // Good enough for parsing an ID list. } if ( model.schema[ name ].items && 'integer' === model.schema[ name ].items.type ) { castedAttrs[ name ] = _.filter( _.map( castedAttrs[ name ], function( id ) { return parseInt( id, 10 ); }, function( id ) { return 'number' === typeof id; } ) ); } } else if ( 'integer' === type ) { castedAttrs[ name ] = parseInt( value, 10 ); } else if ( 'boolean' === type ) { castedAttrs[ name ] = ! ( ! value || '0' === value || 'false' === value ); } else { castedAttrs[ name ] = value; } }); return Backbone.Model.prototype.set.call( this, castedAttrs, opts ); }, /** * Get props which are merged on top of the model when an embed is chosen (as opposed to an attachment). * * @return {Object} Reset/override props. */ getEmbedResetProps: function getEmbedResetProps() { return { id: 0 }; } }); /** * Collection of all widget model instances. * * @memberOf wp.mediaWidgets * * @type {Backbone.Collection} */ component.modelCollection = new ( Backbone.Collection.extend( { model: component.MediaWidgetModel }) )(); /** * Mapping of widget ID to instances of MediaWidgetControl subclasses. * * @memberOf wp.mediaWidgets * * @type {Object.<string, wp.mediaWidgets.MediaWidgetControl>} */ component.widgetControls = {}; /** * Handle widget being added or initialized for the first time at the widget-added event. * * @memberOf wp.mediaWidgets * * @param {jQuery.Event} event - Event. * @param {jQuery} widgetContainer - Widget container element. * * @return {void} */ component.handleWidgetAdded = function handleWidgetAdded( event, widgetContainer ) { var fieldContainer, syncContainer, widgetForm, idBase, ControlConstructor, ModelConstructor, modelAttributes, widgetControl, widgetModel, widgetId, animatedCheckDelay = 50, renderWhenAnimationDone; widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' ); // Note: '.form' appears in the customizer, whereas 'form' on the widgets admin screen. idBase = widgetForm.find( '> .id_base' ).val(); widgetId = widgetForm.find( '> .widget-id' ).val(); // Prevent initializing already-added widgets. if ( component.widgetControls[ widgetId ] ) { return; } ControlConstructor = component.controlConstructors[ idBase ]; if ( ! ControlConstructor ) { return; } ModelConstructor = component.modelConstructors[ idBase ] || component.MediaWidgetModel; /* * Create a container element for the widget control (Backbone.View). * This is inserted into the DOM immediately before the .widget-content * element because the contents of this element are essentially "managed" * by PHP, where each widget update cause the entire element to be emptied * and replaced with the rendered output of WP_Widget::form() which is * sent back in Ajax request made to save/update the widget instance. * To prevent a "flash of replaced DOM elements and re-initialized JS * components", the JS template is rendered outside of the normal form * container. */ fieldContainer = $( '<div></div>' ); syncContainer = widgetContainer.find( '.widget-content:first' ); syncContainer.before( fieldContainer ); /* * Sync the widget instance model attributes onto the hidden inputs that widgets currently use to store the state. * In the future, when widgets are JS-driven, the underlying widget instance data should be exposed as a model * from the start, without having to sync with hidden fields. See <https://core.trac.wordpress.org/ticket/33507>. */ modelAttributes = {}; syncContainer.find( '.media-widget-instance-property' ).each( function() { var input = $( this ); modelAttributes[ input.data( 'property' ) ] = input.val(); }); modelAttributes.widget_id = widgetId; widgetModel = new ModelConstructor( modelAttributes ); widgetControl = new ControlConstructor({ el: fieldContainer, syncContainer: syncContainer, model: widgetModel }); /* * Render the widget once the widget parent's container finishes animating, * as the widget-added event fires with a slideDown of the container. * This ensures that the container's dimensions are fixed so that ME.js * can initialize with the proper dimensions. */ renderWhenAnimationDone = function() { if ( ! widgetContainer.hasClass( 'open' ) ) { setTimeout( renderWhenAnimationDone, animatedCheckDelay ); } else { widgetControl.render(); } }; renderWhenAnimationDone(); /* * Note that the model and control currently won't ever get garbage-collected * when a widget gets removed/deleted because there is no widget-removed event. */ component.modelCollection.add( [ widgetModel ] ); component.widgetControls[ widgetModel.get( 'widget_id' ) ] = widgetControl; }; /** * Setup widget in accessibility mode. * * @memberOf wp.mediaWidgets * * @return {void} */ component.setupAccessibleMode = function setupAccessibleMode() { var widgetForm, widgetId, idBase, widgetControl, ControlConstructor, ModelConstructor, modelAttributes, fieldContainer, syncContainer; widgetForm = $( '.editwidget > form' ); if ( 0 === widgetForm.length ) { return; } idBase = widgetForm.find( '.id_base' ).val(); ControlConstructor = component.controlConstructors[ idBase ]; if ( ! ControlConstructor ) { return; } widgetId = widgetForm.find( '> .widget-control-actions > .widget-id' ).val(); ModelConstructor = component.modelConstructors[ idBase ] || component.MediaWidgetModel; fieldContainer = $( '<div></div>' ); syncContainer = widgetForm.find( '> .widget-inside' ); syncContainer.before( fieldContainer ); modelAttributes = {}; syncContainer.find( '.media-widget-instance-property' ).each( function() { var input = $( this ); modelAttributes[ input.data( 'property' ) ] = input.val(); }); modelAttributes.widget_id = widgetId; widgetControl = new ControlConstructor({ el: fieldContainer, syncContainer: syncContainer, model: new ModelConstructor( modelAttributes ) }); component.modelCollection.add( [ widgetControl.model ] ); component.widgetControls[ widgetControl.model.get( 'widget_id' ) ] = widgetControl; widgetControl.render(); }; /** * Sync widget instance data sanitized from server back onto widget model. * * This gets called via the 'widget-updated' event when saving a widget from * the widgets admin screen and also via the 'widget-synced' event when making * a change to a widget in the customizer. * * @memberOf wp.mediaWidgets * * @param {jQuery.Event} event - Event. * @param {jQuery} widgetContainer - Widget container element. * * @return {void} */ component.handleWidgetUpdated = function handleWidgetUpdated( event, widgetContainer ) { var widgetForm, widgetContent, widgetId, widgetControl, attributes = {}; widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' ); widgetId = widgetForm.find( '> .widget-id' ).val(); widgetControl = component.widgetControls[ widgetId ]; if ( ! widgetControl ) { return; } // Make sure the server-sanitized values get synced back into the model. widgetContent = widgetForm.find( '> .widget-content' ); widgetContent.find( '.media-widget-instance-property' ).each( function() { var property = $( this ).data( 'property' ); attributes[ property ] = $( this ).val(); }); // Suspend syncing model back to inputs when syncing from inputs to model, preventing infinite loop. widgetControl.stopListening( widgetControl.model, 'change', widgetControl.syncModelToInputs ); widgetControl.model.set( attributes ); widgetControl.listenTo( widgetControl.model, 'change', widgetControl.syncModelToInputs ); }; /** * Initialize functionality. * * This function exists to prevent the JS file from having to boot itself. * When WordPress enqueues this script, it should have an inline script * attached which calls wp.mediaWidgets.init(). * * @memberOf wp.mediaWidgets * * @return {void} */ component.init = function init() { var $document = $( document ); $document.on( 'widget-added', component.handleWidgetAdded ); $document.on( 'widget-synced widget-updated', component.handleWidgetUpdated ); /* * Manually trigger widget-added events for media widgets on the admin * screen once they are expanded. The widget-added event is not triggered * for each pre-existing widget on the widgets admin screen like it is * on the customizer. Likewise, the customizer only triggers widget-added * when the widget is expanded to just-in-time construct the widget form * when it is actually going to be displayed. So the following implements * the same for the widgets admin screen, to invoke the widget-added * handler when a pre-existing media widget is expanded. */ $( function initializeExistingWidgetContainers() { var widgetContainers; if ( 'widgets' !== window.pagenow ) { return; } widgetContainers = $( '.widgets-holder-wrap:not(#available-widgets)' ).find( 'div.widget' ); widgetContainers.one( 'click.toggle-widget-expanded', function toggleWidgetExpanded() { var widgetContainer = $( this ); component.handleWidgetAdded( new jQuery.Event( 'widget-added' ), widgetContainer ); }); // Accessibility mode. if ( document.readyState === 'complete' ) { // Page is fully loaded. component.setupAccessibleMode(); } else { // Page is still loading. $( window ).on( 'load', function() { component.setupAccessibleMode(); }); } }); }; return component; })( jQuery ); PK 4�Z�r� � ! widgets/media-video-widget.min.jsnu �[��� /*! This file is auto-generated */ !function(t){"use strict";var i=wp.media.view.MediaFrame.VideoDetails.extend({createStates:function(){this.states.add([new wp.media.controller.VideoDetails({media:this.media}),new wp.media.controller.MediaLibrary({type:"video",id:"add-video-source",title:wp.media.view.l10n.videoAddSourceTitle,toolbar:"add-video-source",media:this.media,menu:!1}),new wp.media.controller.MediaLibrary({type:"text",id:"add-track",title:wp.media.view.l10n.videoAddTrackTitle,toolbar:"add-track",media:this.media,menu:"video-details"})])}}),e=t.MediaWidgetModel.extend({}),d=t.MediaWidgetControl.extend({showDisplaySettings:!1,oembedResponses:{},mapModelToMediaFrameProps:function(e){e=t.MediaWidgetControl.prototype.mapModelToMediaFrameProps.call(this,e);return e.link="embed",e},fetchEmbed:function(){var t=this,d=t.model.get("url");t.oembedResponses[d]||(t.fetchEmbedDfd&&"pending"===t.fetchEmbedDfd.state()&&t.fetchEmbedDfd.abort(),t.fetchEmbedDfd=wp.apiRequest({url:wp.media.view.settings.oEmbedProxyUrl,data:{url:t.model.get("url"),maxwidth:t.model.get("width"),maxheight:t.model.get("height"),discover:!1},type:"GET",dataType:"json",context:t}),t.fetchEmbedDfd.done(function(e){t.oembedResponses[d]=e,t.renderPreview()}),t.fetchEmbedDfd.fail(function(){t.oembedResponses[d]=null}))},isHostedVideo:function(){return!0},renderPreview:function(){var e,t,d=this,i="",o=!1,a=d.model.get("attachment_id"),s=d.model.get("url"),m=d.model.get("error");(a||s)&&((t=d.selectedAttachment.get("mime"))&&a?_.contains(_.values(wp.media.view.settings.embedMimes),t)||(m="unsupported_file_type"):a||((t=document.createElement("a")).href=s,(t=t.pathname.toLowerCase().match(/\.(\w+)$/))?_.contains(_.keys(wp.media.view.settings.embedMimes),t[1])||(m="unsupported_file_type"):o=!0),o&&(d.fetchEmbed(),d.oembedResponses[s])&&(e=d.oembedResponses[s].thumbnail_url,i=d.oembedResponses[s].html.replace(/\swidth="\d+"/,' width="100%"').replace(/\sheight="\d+"/,"")),t=d.$el.find(".media-widget-preview"),d=wp.template("wp-media-widget-video-preview"),t.html(d({model:{attachment_id:a,html:i,src:s,poster:e},is_oembed:o,error:m})),wp.mediaelement.initialize())},editMedia:function(){var t=this,e=t.mapModelToMediaFrameProps(t.model.toJSON()),d=new i({frame:"video",state:"video-details",metadata:e});(wp.media.frame=d).$el.addClass("media-widget"),e=function(e){t.selectedAttachment.set(e),t.model.set(_.extend(_.omit(t.model.defaults(),"title"),t.mapMediaToModelProps(e),{error:!1}))},d.state("video-details").on("update",e),d.state("replace-video").on("replace",e),d.on("close",function(){d.detach()}),d.open()}});t.controlConstructors.media_video=d,t.modelConstructors.media_video=e}(wp.mediaWidgets);PK 4�Z�i��� � "