Initial commit

This commit is contained in:
ayakael 2025-03-31 12:02:18 -04:00
commit 57a2089dd9
No known key found for this signature in database
GPG key ID: 70904985A46AF9AF
1541 changed files with 595392 additions and 0 deletions

453
wp-includes/js/admin-bar.js Normal file
View file

@ -0,0 +1,453 @@
/**
* @output wp-includes/js/admin-bar.js
*/
/**
* Admin bar with Vanilla JS, no external dependencies.
*
* @since 5.3.1
*
* @param {Object} document The document object.
* @param {Object} window The window object.
* @param {Object} navigator The navigator object.
*
* @return {void}
*/
( function( document, window, navigator ) {
document.addEventListener( 'DOMContentLoaded', function() {
var adminBar = document.getElementById( 'wpadminbar' ),
topMenuItems,
allMenuItems,
adminBarLogout,
adminBarSearchForm,
shortlink,
skipLink,
mobileEvent,
adminBarSearchInput,
i;
if ( ! adminBar || ! ( 'querySelectorAll' in adminBar ) ) {
return;
}
topMenuItems = adminBar.querySelectorAll( 'li.menupop' );
allMenuItems = adminBar.querySelectorAll( '.ab-item' );
adminBarLogout = document.getElementById( 'wp-admin-bar-logout' );
adminBarSearchForm = document.getElementById( 'adminbarsearch' );
shortlink = document.getElementById( 'wp-admin-bar-get-shortlink' );
skipLink = adminBar.querySelector( '.screen-reader-shortcut' );
mobileEvent = /Mobile\/.+Safari/.test( navigator.userAgent ) ? 'touchstart' : 'click';
// Remove nojs class after the DOM is loaded.
removeClass( adminBar, 'nojs' );
if ( 'ontouchstart' in window ) {
// Remove hover class when the user touches outside the menu items.
document.body.addEventListener( mobileEvent, function( e ) {
if ( ! getClosest( e.target, 'li.menupop' ) ) {
removeAllHoverClass( topMenuItems );
}
} );
// Add listener for menu items to toggle hover class by touches.
// Remove the callback later for better performance.
adminBar.addEventListener( 'touchstart', function bindMobileEvents() {
for ( var i = 0; i < topMenuItems.length; i++ ) {
topMenuItems[i].addEventListener( 'click', mobileHover.bind( null, topMenuItems ) );
}
adminBar.removeEventListener( 'touchstart', bindMobileEvents );
} );
}
// Scroll page to top when clicking on the admin bar.
adminBar.addEventListener( 'click', scrollToTop );
for ( i = 0; i < topMenuItems.length; i++ ) {
// Adds or removes the hover class based on the hover intent.
window.hoverintent(
topMenuItems[i],
addClass.bind( null, topMenuItems[i], 'hover' ),
removeClass.bind( null, topMenuItems[i], 'hover' )
).options( {
timeout: 180
} );
// Toggle hover class if the enter key is pressed.
topMenuItems[i].addEventListener( 'keydown', toggleHoverIfEnter );
}
// Remove hover class if the escape key is pressed.
for ( i = 0; i < allMenuItems.length; i++ ) {
allMenuItems[i].addEventListener( 'keydown', removeHoverIfEscape );
}
if ( adminBarSearchForm ) {
adminBarSearchInput = document.getElementById( 'adminbar-search' );
// Adds the adminbar-focused class on focus.
adminBarSearchInput.addEventListener( 'focus', function() {
addClass( adminBarSearchForm, 'adminbar-focused' );
} );
// Removes the adminbar-focused class on blur.
adminBarSearchInput.addEventListener( 'blur', function() {
removeClass( adminBarSearchForm, 'adminbar-focused' );
} );
}
if ( skipLink ) {
// Focus the target of skip link after pressing Enter.
skipLink.addEventListener( 'keydown', focusTargetAfterEnter );
}
if ( shortlink ) {
shortlink.addEventListener( 'click', clickShortlink );
}
// Prevents the toolbar from covering up content when a hash is present in the URL.
if ( window.location.hash ) {
window.scrollBy( 0, -32 );
}
// Clear sessionStorage on logging out.
if ( adminBarLogout ) {
adminBarLogout.addEventListener( 'click', emptySessionStorage );
}
} );
/**
* Remove hover class for top level menu item when escape is pressed.
*
* @since 5.3.1
*
* @param {Event} event The keydown event.
*/
function removeHoverIfEscape( event ) {
var wrapper;
if ( event.which !== 27 ) {
return;
}
wrapper = getClosest( event.target, '.menupop' );
if ( ! wrapper ) {
return;
}
wrapper.querySelector( '.menupop > .ab-item' ).focus();
removeClass( wrapper, 'hover' );
}
/**
* Toggle hover class for top level menu item when enter is pressed.
*
* @since 5.3.1
*
* @param {Event} event The keydown event.
*/
function toggleHoverIfEnter( event ) {
var wrapper;
if ( event.which !== 13 ) {
return;
}
if ( !! getClosest( event.target, '.ab-sub-wrapper' ) ) {
return;
}
wrapper = getClosest( event.target, '.menupop' );
if ( ! wrapper ) {
return;
}
event.preventDefault();
if ( hasClass( wrapper, 'hover' ) ) {
removeClass( wrapper, 'hover' );
} else {
addClass( wrapper, 'hover' );
}
}
/**
* Focus the target of skip link after pressing Enter.
*
* @since 5.3.1
*
* @param {Event} event The keydown event.
*/
function focusTargetAfterEnter( event ) {
var id, userAgent;
if ( event.which !== 13 ) {
return;
}
id = event.target.getAttribute( 'href' );
userAgent = navigator.userAgent.toLowerCase();
if ( userAgent.indexOf( 'applewebkit' ) > -1 && id && id.charAt( 0 ) === '#' ) {
setTimeout( function() {
var target = document.getElementById( id.replace( '#', '' ) );
if ( target ) {
target.setAttribute( 'tabIndex', '0' );
target.focus();
}
}, 100 );
}
}
/**
* Toogle hover class for mobile devices.
*
* @since 5.3.1
*
* @param {NodeList} topMenuItems All menu items.
* @param {Event} event The click event.
*/
function mobileHover( topMenuItems, event ) {
var wrapper;
if ( !! getClosest( event.target, '.ab-sub-wrapper' ) ) {
return;
}
event.preventDefault();
wrapper = getClosest( event.target, '.menupop' );
if ( ! wrapper ) {
return;
}
if ( hasClass( wrapper, 'hover' ) ) {
removeClass( wrapper, 'hover' );
} else {
removeAllHoverClass( topMenuItems );
addClass( wrapper, 'hover' );
}
}
/**
* Handles the click on the Shortlink link in the adminbar.
*
* @since 3.1.0
* @since 5.3.1 Use querySelector to clean up the function.
*
* @param {Event} event The click event.
* @return {boolean} Returns false to prevent default click behavior.
*/
function clickShortlink( event ) {
var wrapper = event.target.parentNode,
input;
if ( wrapper ) {
input = wrapper.querySelector( '.shortlink-input' );
}
if ( ! input ) {
return;
}
// (Old) IE doesn't support preventDefault, and does support returnValue.
if ( event.preventDefault ) {
event.preventDefault();
}
event.returnValue = false;
addClass( wrapper, 'selected' );
input.focus();
input.select();
input.onblur = function() {
removeClass( wrapper, 'selected' );
};
return false;
}
/**
* Clear sessionStorage on logging out.
*
* @since 5.3.1
*/
function emptySessionStorage() {
if ( 'sessionStorage' in window ) {
try {
for ( var key in sessionStorage ) {
if ( key.indexOf( 'wp-autosave-' ) > -1 ) {
sessionStorage.removeItem( key );
}
}
} catch ( er ) {}
}
}
/**
* Check if element has class.
*
* @since 5.3.1
*
* @param {HTMLElement} element The HTML element.
* @param {string} className The class name.
* @return {boolean} Whether the element has the className.
*/
function hasClass( element, className ) {
var classNames;
if ( ! element ) {
return false;
}
if ( element.classList && element.classList.contains ) {
return element.classList.contains( className );
} else if ( element.className ) {
classNames = element.className.split( ' ' );
return classNames.indexOf( className ) > -1;
}
return false;
}
/**
* Add class to an element.
*
* @since 5.3.1
*
* @param {HTMLElement} element The HTML element.
* @param {string} className The class name.
*/
function addClass( element, className ) {
if ( ! element ) {
return;
}
if ( element.classList && element.classList.add ) {
element.classList.add( className );
} else if ( ! hasClass( element, className ) ) {
if ( element.className ) {
element.className += ' ';
}
element.className += className;
}
}
/**
* Remove class from an element.
*
* @since 5.3.1
*
* @param {HTMLElement} element The HTML element.
* @param {string} className The class name.
*/
function removeClass( element, className ) {
var testName,
classes;
if ( ! element || ! hasClass( element, className ) ) {
return;
}
if ( element.classList && element.classList.remove ) {
element.classList.remove( className );
} else {
testName = ' ' + className + ' ';
classes = ' ' + element.className + ' ';
while ( classes.indexOf( testName ) > -1 ) {
classes = classes.replace( testName, '' );
}
element.className = classes.replace( /^[\s]+|[\s]+$/g, '' );
}
}
/**
* Remove hover class for all menu items.
*
* @since 5.3.1
*
* @param {NodeList} topMenuItems All menu items.
*/
function removeAllHoverClass( topMenuItems ) {
if ( topMenuItems && topMenuItems.length ) {
for ( var i = 0; i < topMenuItems.length; i++ ) {
removeClass( topMenuItems[i], 'hover' );
}
}
}
/**
* Scrolls to the top of the page.
*
* @since 3.4.0
*
* @param {Event} event The Click event.
*
* @return {void}
*/
function scrollToTop( event ) {
// Only scroll when clicking on the wpadminbar, not on menus or submenus.
if (
event.target &&
event.target.id !== 'wpadminbar' &&
event.target.id !== 'wp-admin-bar-top-secondary'
) {
return;
}
try {
window.scrollTo( {
top: -32,
left: 0,
behavior: 'smooth'
} );
} catch ( er ) {
window.scrollTo( 0, -32 );
}
}
/**
* Get closest Element.
*
* @since 5.3.1
*
* @param {HTMLElement} el Element to get parent.
* @param {string} selector CSS selector to match.
*/
function getClosest( el, selector ) {
if ( ! window.Element.prototype.matches ) {
// Polyfill from https://developer.mozilla.org/en-US/docs/Web/API/Element/matches.
window.Element.prototype.matches =
window.Element.prototype.matchesSelector ||
window.Element.prototype.mozMatchesSelector ||
window.Element.prototype.msMatchesSelector ||
window.Element.prototype.oMatchesSelector ||
window.Element.prototype.webkitMatchesSelector ||
function( s ) {
var matches = ( this.document || this.ownerDocument ).querySelectorAll( s ),
i = matches.length;
while ( --i >= 0 && matches.item( i ) !== this ) { }
return i > -1;
};
}
// Get the closest matching elent.
for ( ; el && el !== document; el = el.parentNode ) {
if ( el.matches( selector ) ) {
return el;
}
}
return null;
}
} )( document, window, navigator );

2
wp-includes/js/admin-bar.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
!function(l,u,d){function m(e){var t;27===e.which&&(t=w(e.target,".menupop"))&&(t.querySelector(".menupop > .ab-item").focus(),y(t,"hover"))}function f(e){var t;13===e.which&&(w(e.target,".ab-sub-wrapper")||(t=w(e.target,".menupop"))&&(e.preventDefault(),(o(t,"hover")?y:b)(t,"hover")))}function p(e){var t;13===e.which&&(t=e.target.getAttribute("href"),-1<d.userAgent.toLowerCase().indexOf("applewebkit")&&t&&"#"===t.charAt(0)&&setTimeout(function(){var e=l.getElementById(t.replace("#",""));e&&(e.setAttribute("tabIndex","0"),e.focus())},100))}function h(e,t){w(t.target,".ab-sub-wrapper")||(t.preventDefault(),(t=w(t.target,".menupop"))&&(o(t,"hover")?y(t,"hover"):(E(e),b(t,"hover"))))}function v(e){var t,n=e.target.parentNode;if(t=n?n.querySelector(".shortlink-input"):t)return e.preventDefault&&e.preventDefault(),e.returnValue=!1,b(n,"selected"),t.focus(),t.select(),!(t.onblur=function(){y(n,"selected")})}function g(){if("sessionStorage"in u)try{for(var e in sessionStorage)-1<e.indexOf("wp-autosave-")&&sessionStorage.removeItem(e)}catch(e){}}function o(e,t){return e&&(e.classList&&e.classList.contains?e.classList.contains(t):e.className&&-1<e.className.split(" ").indexOf(t))}function b(e,t){e&&(e.classList&&e.classList.add?e.classList.add(t):o(e,t)||(e.className&&(e.className+=" "),e.className+=t))}function y(e,t){var n,r;if(e&&o(e,t))if(e.classList&&e.classList.remove)e.classList.remove(t);else{for(n=" "+t+" ",r=" "+e.className+" ";-1<r.indexOf(n);)r=r.replace(n,"");e.className=r.replace(/^[\s]+|[\s]+$/g,"")}}function E(e){if(e&&e.length)for(var t=0;t<e.length;t++)y(e[t],"hover")}function L(e){if(!e.target||"wpadminbar"===e.target.id||"wp-admin-bar-top-secondary"===e.target.id)try{u.scrollTo({top:-32,left:0,behavior:"smooth"})}catch(e){u.scrollTo(0,-32)}}function w(e,t){for(u.Element.prototype.matches||(u.Element.prototype.matches=u.Element.prototype.matchesSelector||u.Element.prototype.mozMatchesSelector||u.Element.prototype.msMatchesSelector||u.Element.prototype.oMatchesSelector||u.Element.prototype.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),n=t.length;0<=--n&&t.item(n)!==this;);return-1<n});e&&e!==l;e=e.parentNode)if(e.matches(t))return e;return null}l.addEventListener("DOMContentLoaded",function(){var n,e,t,r,o,a,s,i,c=l.getElementById("wpadminbar");if(c&&"querySelectorAll"in c){n=c.querySelectorAll("li.menupop"),e=c.querySelectorAll(".ab-item"),t=l.getElementById("wp-admin-bar-logout"),r=l.getElementById("adminbarsearch"),o=l.getElementById("wp-admin-bar-get-shortlink"),a=c.querySelector(".screen-reader-shortcut"),s=/Mobile\/.+Safari/.test(d.userAgent)?"touchstart":"click",y(c,"nojs"),"ontouchstart"in u&&(l.body.addEventListener(s,function(e){w(e.target,"li.menupop")||E(n)}),c.addEventListener("touchstart",function e(){for(var t=0;t<n.length;t++)n[t].addEventListener("click",h.bind(null,n));c.removeEventListener("touchstart",e)})),c.addEventListener("click",L);for(i=0;i<n.length;i++)u.hoverintent(n[i],b.bind(null,n[i],"hover"),y.bind(null,n[i],"hover")).options({timeout:180}),n[i].addEventListener("keydown",f);for(i=0;i<e.length;i++)e[i].addEventListener("keydown",m);r&&((s=l.getElementById("adminbar-search")).addEventListener("focus",function(){b(r,"adminbar-focused")}),s.addEventListener("blur",function(){y(r,"adminbar-focused")})),a&&a.addEventListener("keydown",p),o&&o.addEventListener("click",v),u.location.hash&&u.scrollBy(0,-32),t&&t.addEventListener("click",g)}})}(document,window,navigator);

View file

@ -0,0 +1,124 @@
/**
* Thin jQuery.ajax wrapper for WP REST API requests.
*
* Currently only applies to requests that do not use the `wp-api.js` Backbone
* client library, though this may change. Serves several purposes:
*
* - Allows overriding these requests as needed by customized WP installations.
* - Sends the REST API nonce as a request header.
* - Allows specifying only an endpoint namespace/path instead of a full URL.
*
* @since 4.9.0
* @since 5.6.0 Added overriding of the "PUT" and "DELETE" methods with "POST".
* Added an "application/json" Accept header to all requests.
* @output wp-includes/js/api-request.js
*/
( function( $ ) {
var wpApiSettings = window.wpApiSettings;
function apiRequest( options ) {
options = apiRequest.buildAjaxOptions( options );
return apiRequest.transport( options );
}
apiRequest.buildAjaxOptions = function( options ) {
var url = options.url;
var path = options.path;
var method = options.method;
var namespaceTrimmed, endpointTrimmed, apiRoot;
var headers, addNonceHeader, addAcceptHeader, headerName;
if (
typeof options.namespace === 'string' &&
typeof options.endpoint === 'string'
) {
namespaceTrimmed = options.namespace.replace( /^\/|\/$/g, '' );
endpointTrimmed = options.endpoint.replace( /^\//, '' );
if ( endpointTrimmed ) {
path = namespaceTrimmed + '/' + endpointTrimmed;
} else {
path = namespaceTrimmed;
}
}
if ( typeof path === 'string' ) {
apiRoot = wpApiSettings.root;
path = path.replace( /^\//, '' );
// API root may already include query parameter prefix
// if site is configured to use plain permalinks.
if ( 'string' === typeof apiRoot && -1 !== apiRoot.indexOf( '?' ) ) {
path = path.replace( '?', '&' );
}
url = apiRoot + path;
}
// If ?_wpnonce=... is present, no need to add a nonce header.
addNonceHeader = ! ( options.data && options.data._wpnonce );
addAcceptHeader = true;
headers = options.headers || {};
for ( headerName in headers ) {
if ( ! headers.hasOwnProperty( headerName ) ) {
continue;
}
// If an 'X-WP-Nonce' or 'Accept' header (or any case-insensitive variation
// thereof) was specified, no need to add the header again.
switch ( headerName.toLowerCase() ) {
case 'x-wp-nonce':
addNonceHeader = false;
break;
case 'accept':
addAcceptHeader = false;
break;
}
}
if ( addNonceHeader ) {
// Do not mutate the original headers object, if any.
headers = $.extend( {
'X-WP-Nonce': wpApiSettings.nonce
}, headers );
}
if ( addAcceptHeader ) {
headers = $.extend( {
'Accept': 'application/json, */*;q=0.1'
}, headers );
}
if ( typeof method === 'string' ) {
method = method.toUpperCase();
if ( 'PUT' === method || 'DELETE' === method ) {
headers = $.extend( {
'X-HTTP-Method-Override': method
}, headers );
method = 'POST';
}
}
// Do not mutate the original options object.
options = $.extend( {}, options, {
headers: headers,
url: url,
method: method
} );
delete options.path;
delete options.namespace;
delete options.endpoint;
return options;
};
apiRequest.transport = $.ajax;
/** @namespace wp */
window.wp = window.wp || {};
window.wp.apiRequest = apiRequest;
} )( jQuery );

2
wp-includes/js/api-request.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
!function(c){var w=window.wpApiSettings;function t(e){return e=t.buildAjaxOptions(e),t.transport(e)}t.buildAjaxOptions=function(e){var t,n,a,p,o,r,i=e.url,d=e.path,s=e.method;for(r in"string"==typeof e.namespace&&"string"==typeof e.endpoint&&(n=e.namespace.replace(/^\/|\/$/g,""),d=(t=e.endpoint.replace(/^\//,""))?n+"/"+t:n),"string"==typeof d&&(n=w.root,d=d.replace(/^\//,""),"string"==typeof n&&-1!==n.indexOf("?")&&(d=d.replace("?","&")),i=n+d),p=!(e.data&&e.data._wpnonce),o=!0,a=e.headers||{})if(a.hasOwnProperty(r))switch(r.toLowerCase()){case"x-wp-nonce":p=!1;break;case"accept":o=!1}return p&&(a=c.extend({"X-WP-Nonce":w.nonce},a)),o&&(a=c.extend({Accept:"application/json, */*;q=0.1"},a)),"string"==typeof s&&("PUT"!==(s=s.toUpperCase())&&"DELETE"!==s||(a=c.extend({"X-HTTP-Method-Override":s},a),s="POST")),delete(e=c.extend({},e,{headers:a,url:i,method:s})).path,delete e.namespace,delete e.endpoint,e},t.transport=c.ajax,window.wp=window.wp||{},window.wp.apiRequest=t}(jQuery);

903
wp-includes/js/autosave.js Normal file
View file

@ -0,0 +1,903 @@
/**
* @output wp-includes/js/autosave.js
*/
/* global tinymce, wpCookies, autosaveL10n, switchEditors */
// Back-compat.
window.autosave = function() {
return true;
};
/**
* Adds autosave to the window object on dom ready.
*
* @since 3.9.0
*
* @param {jQuery} $ jQuery object.
* @param {window} The window object.
*
*/
( function( $, window ) {
/**
* Auto saves the post.
*
* @since 3.9.0
*
* @return {Object}
* {{
* getPostData: getPostData,
* getCompareString: getCompareString,
* disableButtons: disableButtons,
* enableButtons: enableButtons,
* local: ({hasStorage, getSavedPostData, save, suspend, resume}|*),
* server: ({tempBlockSave, triggerSave, postChanged, suspend, resume}|*)
* }}
* The object with all functions for autosave.
*/
function autosave() {
var initialCompareString,
initialCompareData = {},
lastTriggerSave = 0,
$document = $( document );
/**
* Sets the initial compare data.
*
* @since 5.6.1
*/
function setInitialCompare() {
initialCompareData = {
post_title: $( '#title' ).val() || '',
content: $( '#content' ).val() || '',
excerpt: $( '#excerpt' ).val() || ''
};
initialCompareString = getCompareString( initialCompareData );
}
/**
* Returns the data saved in both local and remote autosave.
*
* @since 3.9.0
*
* @param {string} type The type of autosave either local or remote.
*
* @return {Object} Object containing the post data.
*/
function getPostData( type ) {
var post_name, parent_id, data,
time = ( new Date() ).getTime(),
cats = [],
editor = getEditor();
// Don't run editor.save() more often than every 3 seconds.
// It is resource intensive and might slow down typing in long posts on slow devices.
if ( editor && editor.isDirty() && ! editor.isHidden() && time - 3000 > lastTriggerSave ) {
editor.save();
lastTriggerSave = time;
}
data = {
post_id: $( '#post_ID' ).val() || 0,
post_type: $( '#post_type' ).val() || '',
post_author: $( '#post_author' ).val() || '',
post_title: $( '#title' ).val() || '',
content: $( '#content' ).val() || '',
excerpt: $( '#excerpt' ).val() || ''
};
if ( type === 'local' ) {
return data;
}
$( 'input[id^="in-category-"]:checked' ).each( function() {
cats.push( this.value );
});
data.catslist = cats.join(',');
if ( post_name = $( '#post_name' ).val() ) {
data.post_name = post_name;
}
if ( parent_id = $( '#parent_id' ).val() ) {
data.parent_id = parent_id;
}
if ( $( '#comment_status' ).prop( 'checked' ) ) {
data.comment_status = 'open';
}
if ( $( '#ping_status' ).prop( 'checked' ) ) {
data.ping_status = 'open';
}
if ( $( '#auto_draft' ).val() === '1' ) {
data.auto_draft = '1';
}
return data;
}
/**
* Concatenates the title, content and excerpt. This is used to track changes
* when auto-saving.
*
* @since 3.9.0
*
* @param {Object} postData The object containing the post data.
*
* @return {string} A concatenated string with title, content and excerpt.
*/
function getCompareString( postData ) {
if ( typeof postData === 'object' ) {
return ( postData.post_title || '' ) + '::' + ( postData.content || '' ) + '::' + ( postData.excerpt || '' );
}
return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' );
}
/**
* Disables save buttons.
*
* @since 3.9.0
*
* @return {void}
*/
function disableButtons() {
$document.trigger('autosave-disable-buttons');
// Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
setTimeout( enableButtons, 5000 );
}
/**
* Enables save buttons.
*
* @since 3.9.0
*
* @return {void}
*/
function enableButtons() {
$document.trigger( 'autosave-enable-buttons' );
}
/**
* Gets the content editor.
*
* @since 4.6.0
*
* @return {boolean|*} Returns either false if the editor is undefined,
* or the instance of the content editor.
*/
function getEditor() {
return typeof tinymce !== 'undefined' && tinymce.get('content');
}
/**
* Autosave in localStorage.
*
* @since 3.9.0
*
* @return {
* {
* hasStorage: *,
* getSavedPostData: getSavedPostData,
* save: save,
* suspend: suspend,
* resume: resume
* }
* }
* The object with all functions for local storage autosave.
*/
function autosaveLocal() {
var blog_id, post_id, hasStorage, intervalTimer,
lastCompareString,
isSuspended = false;
/**
* Checks if the browser supports sessionStorage and it's not disabled.
*
* @since 3.9.0
*
* @return {boolean} True if the sessionStorage is supported and enabled.
*/
function checkStorage() {
var test = Math.random().toString(),
result = false;
try {
window.sessionStorage.setItem( 'wp-test', test );
result = window.sessionStorage.getItem( 'wp-test' ) === test;
window.sessionStorage.removeItem( 'wp-test' );
} catch(e) {}
hasStorage = result;
return result;
}
/**
* Initializes the local storage.
*
* @since 3.9.0
*
* @return {boolean|Object} False if no sessionStorage in the browser or an Object
* containing all postData for this blog.
*/
function getStorage() {
var stored_obj = false;
// Separate local storage containers for each blog_id.
if ( hasStorage && blog_id ) {
stored_obj = sessionStorage.getItem( 'wp-autosave-' + blog_id );
if ( stored_obj ) {
stored_obj = JSON.parse( stored_obj );
} else {
stored_obj = {};
}
}
return stored_obj;
}
/**
* Sets the storage for this blog. Confirms that the data was saved
* successfully.
*
* @since 3.9.0
*
* @return {boolean} True if the data was saved successfully, false if it wasn't saved.
*/
function setStorage( stored_obj ) {
var key;
if ( hasStorage && blog_id ) {
key = 'wp-autosave-' + blog_id;
sessionStorage.setItem( key, JSON.stringify( stored_obj ) );
return sessionStorage.getItem( key ) !== null;
}
return false;
}
/**
* Gets the saved post data for the current post.
*
* @since 3.9.0
*
* @return {boolean|Object} False if no storage or no data or the postData as an Object.
*/
function getSavedPostData() {
var stored = getStorage();
if ( ! stored || ! post_id ) {
return false;
}
return stored[ 'post_' + post_id ] || false;
}
/**
* Sets (save or delete) post data in the storage.
*
* If stored_data evaluates to 'false' the storage key for the current post will be removed.
*
* @since 3.9.0
*
* @param {Object|boolean|null} stored_data The post data to store or null/false/empty to delete the key.
*
* @return {boolean} True if data is stored, false if data was removed.
*/
function setData( stored_data ) {
var stored = getStorage();
if ( ! stored || ! post_id ) {
return false;
}
if ( stored_data ) {
stored[ 'post_' + post_id ] = stored_data;
} else if ( stored.hasOwnProperty( 'post_' + post_id ) ) {
delete stored[ 'post_' + post_id ];
} else {
return false;
}
return setStorage( stored );
}
/**
* Sets isSuspended to true.
*
* @since 3.9.0
*
* @return {void}
*/
function suspend() {
isSuspended = true;
}
/**
* Sets isSuspended to false.
*
* @since 3.9.0
*
* @return {void}
*/
function resume() {
isSuspended = false;
}
/**
* Saves post data for the current post.
*
* Runs on a 15 seconds interval, saves when there are differences in the post title or content.
* When the optional data is provided, updates the last saved post data.
*
* @since 3.9.0
*
* @param {Object} data The post data for saving, minimum 'post_title' and 'content'.
*
* @return {boolean} Returns true when data has been saved, otherwise it returns false.
*/
function save( data ) {
var postData, compareString,
result = false;
if ( isSuspended || ! hasStorage ) {
return false;
}
if ( data ) {
postData = getSavedPostData() || {};
$.extend( postData, data );
} else {
postData = getPostData('local');
}
compareString = getCompareString( postData );
if ( typeof lastCompareString === 'undefined' ) {
lastCompareString = initialCompareString;
}
// If the content, title and excerpt did not change since the last save, don't save again.
if ( compareString === lastCompareString ) {
return false;
}
postData.save_time = ( new Date() ).getTime();
postData.status = $( '#post_status' ).val() || '';
result = setData( postData );
if ( result ) {
lastCompareString = compareString;
}
return result;
}
/**
* Initializes the auto save function.
*
* Checks whether the editor is active or not to use the editor events
* to autosave, or uses the values from the elements to autosave.
*
* Runs on DOM ready.
*
* @since 3.9.0
*
* @return {void}
*/
function run() {
post_id = $('#post_ID').val() || 0;
// Check if the local post data is different than the loaded post data.
if ( $( '#wp-content-wrap' ).hasClass( 'tmce-active' ) ) {
/*
* If TinyMCE loads first, check the post 1.5 seconds after it is ready.
* By this time the content has been loaded in the editor and 'saved' to the textarea.
* This prevents false positives.
*/
$document.on( 'tinymce-editor-init.autosave', function() {
window.setTimeout( function() {
checkPost();
}, 1500 );
});
} else {
checkPost();
}
// Save every 15 seconds.
intervalTimer = window.setInterval( save, 15000 );
$( 'form#post' ).on( 'submit.autosave-local', function() {
var editor = getEditor(),
post_id = $('#post_ID').val() || 0;
if ( editor && ! editor.isHidden() ) {
// Last onSubmit event in the editor, needs to run after the content has been moved to the textarea.
editor.on( 'submit', function() {
save({
post_title: $( '#title' ).val() || '',
content: $( '#content' ).val() || '',
excerpt: $( '#excerpt' ).val() || ''
});
});
} else {
save({
post_title: $( '#title' ).val() || '',
content: $( '#content' ).val() || '',
excerpt: $( '#excerpt' ).val() || ''
});
}
var secure = ( 'https:' === window.location.protocol );
wpCookies.set( 'wp-saving-post', post_id + '-check', 24 * 60 * 60, false, false, secure );
});
}
/**
* Compares 2 strings. Removes whitespaces in the strings before comparing them.
*
* @since 3.9.0
*
* @param {string} str1 The first string.
* @param {string} str2 The second string.
* @return {boolean} True if the strings are the same.
*/
function compare( str1, str2 ) {
function removeSpaces( string ) {
return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
}
return ( removeSpaces( str1 || '' ) === removeSpaces( str2 || '' ) );
}
/**
* Checks if the saved data for the current post (if any) is different than the
* loaded post data on the screen.
*
* Shows a standard message letting the user restore the post data if different.
*
* @since 3.9.0
*
* @return {void}
*/
function checkPost() {
var content, post_title, excerpt, $notice,
postData = getSavedPostData(),
cookie = wpCookies.get( 'wp-saving-post' ),
$newerAutosaveNotice = $( '#has-newer-autosave' ).parent( '.notice' ),
$headerEnd = $( '.wp-header-end' );
if ( cookie === post_id + '-saved' ) {
wpCookies.remove( 'wp-saving-post' );
// The post was saved properly, remove old data and bail.
setData( false );
return;
}
if ( ! postData ) {
return;
}
content = $( '#content' ).val() || '';
post_title = $( '#title' ).val() || '';
excerpt = $( '#excerpt' ).val() || '';
if ( compare( content, postData.content ) && compare( post_title, postData.post_title ) &&
compare( excerpt, postData.excerpt ) ) {
return;
}
/*
* If '.wp-header-end' is found, append the notices after it otherwise
* after the first h1 or h2 heading found within the main content.
*/
if ( ! $headerEnd.length ) {
$headerEnd = $( '.wrap h1, .wrap h2' ).first();
}
$notice = $( '#local-storage-notice' )
.insertAfter( $headerEnd )
.addClass( 'notice-warning' );
if ( $newerAutosaveNotice.length ) {
// If there is a "server" autosave notice, hide it.
// The data in the session storage is either the same or newer.
$newerAutosaveNotice.slideUp( 150, function() {
$notice.slideDown( 150 );
});
} else {
$notice.slideDown( 200 );
}
$notice.find( '.restore-backup' ).on( 'click.autosave-local', function() {
restorePost( postData );
$notice.fadeTo( 250, 0, function() {
$notice.slideUp( 150 );
});
});
}
/**
* Restores the current title, content and excerpt from postData.
*
* @since 3.9.0
*
* @param {Object} postData The object containing all post data.
*
* @return {boolean} True if the post is restored.
*/
function restorePost( postData ) {
var editor;
if ( postData ) {
// Set the last saved data.
lastCompareString = getCompareString( postData );
if ( $( '#title' ).val() !== postData.post_title ) {
$( '#title' ).trigger( 'focus' ).val( postData.post_title || '' );
}
$( '#excerpt' ).val( postData.excerpt || '' );
editor = getEditor();
if ( editor && ! editor.isHidden() && typeof switchEditors !== 'undefined' ) {
if ( editor.settings.wpautop && postData.content ) {
postData.content = switchEditors.wpautop( postData.content );
}
// Make sure there's an undo level in the editor.
editor.undoManager.transact( function() {
editor.setContent( postData.content || '' );
editor.nodeChanged();
});
} else {
// Make sure the Text editor is selected.
$( '#content-html' ).trigger( 'click' );
$( '#content' ).trigger( 'focus' );
// Using document.execCommand() will let the user undo.
document.execCommand( 'selectAll' );
document.execCommand( 'insertText', false, postData.content || '' );
}
return true;
}
return false;
}
blog_id = typeof window.autosaveL10n !== 'undefined' && window.autosaveL10n.blog_id;
/*
* Check if the browser supports sessionStorage and it's not disabled,
* then initialize and run checkPost().
* Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'.
*/
if ( checkStorage() && blog_id && ( $('#content').length || $('#excerpt').length ) ) {
$( run );
}
return {
hasStorage: hasStorage,
getSavedPostData: getSavedPostData,
save: save,
suspend: suspend,
resume: resume
};
}
/**
* Auto saves the post on the server.
*
* @since 3.9.0
*
* @return {Object} {
* {
* tempBlockSave: tempBlockSave,
* triggerSave: triggerSave,
* postChanged: postChanged,
* suspend: suspend,
* resume: resume
* }
* } The object all functions for autosave.
*/
function autosaveServer() {
var _blockSave, _blockSaveTimer, previousCompareString, lastCompareString,
nextRun = 0,
isSuspended = false;
/**
* Blocks saving for the next 10 seconds.
*
* @since 3.9.0
*
* @return {void}
*/
function tempBlockSave() {
_blockSave = true;
window.clearTimeout( _blockSaveTimer );
_blockSaveTimer = window.setTimeout( function() {
_blockSave = false;
}, 10000 );
}
/**
* Sets isSuspended to true.
*
* @since 3.9.0
*
* @return {void}
*/
function suspend() {
isSuspended = true;
}
/**
* Sets isSuspended to false.
*
* @since 3.9.0
*
* @return {void}
*/
function resume() {
isSuspended = false;
}
/**
* Triggers the autosave with the post data.
*
* @since 3.9.0
*
* @param {Object} data The post data.
*
* @return {void}
*/
function response( data ) {
_schedule();
_blockSave = false;
lastCompareString = previousCompareString;
previousCompareString = '';
$document.trigger( 'after-autosave', [data] );
enableButtons();
if ( data.success ) {
// No longer an auto-draft.
$( '#auto_draft' ).val('');
}
}
/**
* Saves immediately.
*
* Resets the timing and tells heartbeat to connect now.
*
* @since 3.9.0
*
* @return {void}
*/
function triggerSave() {
nextRun = 0;
wp.heartbeat.connectNow();
}
/**
* Checks if the post content in the textarea has changed since page load.
*
* This also happens when TinyMCE is active and editor.save() is triggered by
* wp.autosave.getPostData().
*
* @since 3.9.0
*
* @return {boolean} True if the post has been changed.
*/
function postChanged() {
var changed = false;
// If there are TinyMCE instances, loop through them.
if ( window.tinymce ) {
window.tinymce.each( [ 'content', 'excerpt' ], function( field ) {
var editor = window.tinymce.get( field );
if ( ! editor || editor.isHidden() ) {
if ( ( $( '#' + field ).val() || '' ) !== initialCompareData[ field ] ) {
changed = true;
// Break.
return false;
}
} else if ( editor.isDirty() ) {
changed = true;
return false;
}
} );
if ( ( $( '#title' ).val() || '' ) !== initialCompareData.post_title ) {
changed = true;
}
return changed;
}
return getCompareString() !== initialCompareString;
}
/**
* Checks if the post can be saved or not.
*
* If the post hasn't changed or it cannot be updated,
* because the autosave is blocked or suspended, the function returns false.
*
* @since 3.9.0
*
* @return {Object} Returns the post data.
*/
function save() {
var postData, compareString;
// window.autosave() used for back-compat.
if ( isSuspended || _blockSave || ! window.autosave() ) {
return false;
}
if ( ( new Date() ).getTime() < nextRun ) {
return false;
}
postData = getPostData();
compareString = getCompareString( postData );
// First check.
if ( typeof lastCompareString === 'undefined' ) {
lastCompareString = initialCompareString;
}
// No change.
if ( compareString === lastCompareString ) {
return false;
}
previousCompareString = compareString;
tempBlockSave();
disableButtons();
$document.trigger( 'wpcountwords', [ postData.content ] )
.trigger( 'before-autosave', [ postData ] );
postData._wpnonce = $( '#_wpnonce' ).val() || '';
return postData;
}
/**
* Sets the next run, based on the autosave interval.
*
* @private
*
* @since 3.9.0
*
* @return {void}
*/
function _schedule() {
nextRun = ( new Date() ).getTime() + ( autosaveL10n.autosaveInterval * 1000 ) || 60000;
}
/**
* Sets the autosaveData on the autosave heartbeat.
*
* @since 3.9.0
*
* @return {void}
*/
$( function() {
_schedule();
}).on( 'heartbeat-send.autosave', function( event, data ) {
var autosaveData = save();
if ( autosaveData ) {
data.wp_autosave = autosaveData;
}
/**
* Triggers the autosave of the post with the autosave data on the autosave
* heartbeat.
*
* @since 3.9.0
*
* @return {void}
*/
}).on( 'heartbeat-tick.autosave', function( event, data ) {
if ( data.wp_autosave ) {
response( data.wp_autosave );
}
/**
* Disables buttons and throws a notice when the connection is lost.
*
* @since 3.9.0
*
* @return {void}
*/
}).on( 'heartbeat-connection-lost.autosave', function( event, error, status ) {
// When connection is lost, keep user from submitting changes.
if ( 'timeout' === error || 603 === status ) {
var $notice = $('#lost-connection-notice');
if ( ! wp.autosave.local.hasStorage ) {
$notice.find('.hide-if-no-sessionstorage').hide();
}
$notice.show();
disableButtons();
}
/**
* Enables buttons when the connection is restored.
*
* @since 3.9.0
*
* @return {void}
*/
}).on( 'heartbeat-connection-restored.autosave', function() {
$('#lost-connection-notice').hide();
enableButtons();
});
return {
tempBlockSave: tempBlockSave,
triggerSave: triggerSave,
postChanged: postChanged,
suspend: suspend,
resume: resume
};
}
/**
* Sets the autosave time out.
*
* Wait for TinyMCE to initialize plus 1 second. for any external css to finish loading,
* then save to the textarea before setting initialCompareString.
* This avoids any insignificant differences between the initial textarea content and the content
* extracted from the editor.
*
* @since 3.9.0
*
* @return {void}
*/
$( function() {
// Set the initial compare string in case TinyMCE is not used or not loaded first.
setInitialCompare();
}).on( 'tinymce-editor-init.autosave', function( event, editor ) {
// Reset the initialCompare data after the TinyMCE instances have been initialized.
if ( 'content' === editor.id || 'excerpt' === editor.id ) {
window.setTimeout( function() {
editor.save();
setInitialCompare();
}, 1000 );
}
});
return {
getPostData: getPostData,
getCompareString: getCompareString,
disableButtons: disableButtons,
enableButtons: enableButtons,
local: autosaveLocal(),
server: autosaveServer()
};
}
/** @namespace wp */
window.wp = window.wp || {};
window.wp.autosave = autosave();
}( jQuery, window ));

2
wp-includes/js/autosave.min.js vendored Normal file

File diff suppressed because one or more lines are too long

2096
wp-includes/js/backbone.js Normal file

File diff suppressed because it is too large Load diff

2
wp-includes/js/backbone.min.js vendored Normal file

File diff suppressed because one or more lines are too long

954
wp-includes/js/clipboard.js Normal file
View file

@ -0,0 +1,954 @@
/*!
* clipboard.js v2.0.8
* https://clipboardjs.com/
*
* Licensed MIT © Zeno Rocha
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["ClipboardJS"] = factory();
else
root["ClipboardJS"] = factory();
})(this, function() {
return /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 134:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": function() { return /* binding */ clipboard; }
});
// EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js
var tiny_emitter = __webpack_require__(279);
var tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter);
// EXTERNAL MODULE: ./node_modules/good-listener/src/listen.js
var listen = __webpack_require__(370);
var listen_default = /*#__PURE__*/__webpack_require__.n(listen);
// EXTERNAL MODULE: ./node_modules/select/src/select.js
var src_select = __webpack_require__(817);
var select_default = /*#__PURE__*/__webpack_require__.n(src_select);
;// CONCATENATED MODULE: ./src/clipboard-action.js
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* Inner class which performs selection from either `text` or `target`
* properties and then executes copy or cut operations.
*/
var ClipboardAction = /*#__PURE__*/function () {
/**
* @param {Object} options
*/
function ClipboardAction(options) {
_classCallCheck(this, ClipboardAction);
this.resolveOptions(options);
this.initSelection();
}
/**
* Defines base properties passed from constructor.
* @param {Object} options
*/
_createClass(ClipboardAction, [{
key: "resolveOptions",
value: function resolveOptions() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.action = options.action;
this.container = options.container;
this.emitter = options.emitter;
this.target = options.target;
this.text = options.text;
this.trigger = options.trigger;
this.selectedText = '';
}
/**
* Decides which selection strategy is going to be applied based
* on the existence of `text` and `target` properties.
*/
}, {
key: "initSelection",
value: function initSelection() {
if (this.text) {
this.selectFake();
} else if (this.target) {
this.selectTarget();
}
}
/**
* Creates a fake textarea element, sets its value from `text` property,
*/
}, {
key: "createFakeElement",
value: function createFakeElement() {
var isRTL = document.documentElement.getAttribute('dir') === 'rtl';
this.fakeElem = document.createElement('textarea'); // Prevent zooming on iOS
this.fakeElem.style.fontSize = '12pt'; // Reset box model
this.fakeElem.style.border = '0';
this.fakeElem.style.padding = '0';
this.fakeElem.style.margin = '0'; // Move element out of screen horizontally
this.fakeElem.style.position = 'absolute';
this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px'; // Move element to the same position vertically
var yPosition = window.pageYOffset || document.documentElement.scrollTop;
this.fakeElem.style.top = "".concat(yPosition, "px");
this.fakeElem.setAttribute('readonly', '');
this.fakeElem.value = this.text;
return this.fakeElem;
}
/**
* Get's the value of fakeElem,
* and makes a selection on it.
*/
}, {
key: "selectFake",
value: function selectFake() {
var _this = this;
var fakeElem = this.createFakeElement();
this.fakeHandlerCallback = function () {
return _this.removeFake();
};
this.fakeHandler = this.container.addEventListener('click', this.fakeHandlerCallback) || true;
this.container.appendChild(fakeElem);
this.selectedText = select_default()(fakeElem);
this.copyText();
this.removeFake();
}
/**
* Only removes the fake element after another click event, that way
* a user can hit `Ctrl+C` to copy because selection still exists.
*/
}, {
key: "removeFake",
value: function removeFake() {
if (this.fakeHandler) {
this.container.removeEventListener('click', this.fakeHandlerCallback);
this.fakeHandler = null;
this.fakeHandlerCallback = null;
}
if (this.fakeElem) {
this.container.removeChild(this.fakeElem);
this.fakeElem = null;
}
}
/**
* Selects the content from element passed on `target` property.
*/
}, {
key: "selectTarget",
value: function selectTarget() {
this.selectedText = select_default()(this.target);
this.copyText();
}
/**
* Executes the copy operation based on the current selection.
*/
}, {
key: "copyText",
value: function copyText() {
var succeeded;
try {
succeeded = document.execCommand(this.action);
} catch (err) {
succeeded = false;
}
this.handleResult(succeeded);
}
/**
* Fires an event based on the copy operation result.
* @param {Boolean} succeeded
*/
}, {
key: "handleResult",
value: function handleResult(succeeded) {
this.emitter.emit(succeeded ? 'success' : 'error', {
action: this.action,
text: this.selectedText,
trigger: this.trigger,
clearSelection: this.clearSelection.bind(this)
});
}
/**
* Moves focus away from `target` and back to the trigger, removes current selection.
*/
}, {
key: "clearSelection",
value: function clearSelection() {
if (this.trigger) {
this.trigger.focus();
}
document.activeElement.blur();
window.getSelection().removeAllRanges();
}
/**
* Sets the `action` to be performed which can be either 'copy' or 'cut'.
* @param {String} action
*/
}, {
key: "destroy",
/**
* Destroy lifecycle.
*/
value: function destroy() {
this.removeFake();
}
}, {
key: "action",
set: function set() {
var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy';
this._action = action;
if (this._action !== 'copy' && this._action !== 'cut') {
throw new Error('Invalid "action" value, use either "copy" or "cut"');
}
}
/**
* Gets the `action` property.
* @return {String}
*/
,
get: function get() {
return this._action;
}
/**
* Sets the `target` property using an element
* that will be have its content copied.
* @param {Element} target
*/
}, {
key: "target",
set: function set(target) {
if (target !== undefined) {
if (target && _typeof(target) === 'object' && target.nodeType === 1) {
if (this.action === 'copy' && target.hasAttribute('disabled')) {
throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');
}
if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) {
throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');
}
this._target = target;
} else {
throw new Error('Invalid "target" value, use a valid Element');
}
}
}
/**
* Gets the `target` property.
* @return {String|HTMLElement}
*/
,
get: function get() {
return this._target;
}
}]);
return ClipboardAction;
}();
/* harmony default export */ var clipboard_action = (ClipboardAction);
;// CONCATENATED MODULE: ./src/clipboard.js
function clipboard_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { clipboard_typeof = function _typeof(obj) { return typeof obj; }; } else { clipboard_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return clipboard_typeof(obj); }
function clipboard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function clipboard_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function clipboard_createClass(Constructor, protoProps, staticProps) { if (protoProps) clipboard_defineProperties(Constructor.prototype, protoProps); if (staticProps) clipboard_defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (clipboard_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
/**
* Helper function to retrieve attribute value.
* @param {String} suffix
* @param {Element} element
*/
function getAttributeValue(suffix, element) {
var attribute = "data-clipboard-".concat(suffix);
if (!element.hasAttribute(attribute)) {
return;
}
return element.getAttribute(attribute);
}
/**
* Base class which takes one or more elements, adds event listeners to them,
* and instantiates a new `ClipboardAction` on each click.
*/
var Clipboard = /*#__PURE__*/function (_Emitter) {
_inherits(Clipboard, _Emitter);
var _super = _createSuper(Clipboard);
/**
* @param {String|HTMLElement|HTMLCollection|NodeList} trigger
* @param {Object} options
*/
function Clipboard(trigger, options) {
var _this;
clipboard_classCallCheck(this, Clipboard);
_this = _super.call(this);
_this.resolveOptions(options);
_this.listenClick(trigger);
return _this;
}
/**
* Defines if attributes would be resolved using internal setter functions
* or custom functions that were passed in the constructor.
* @param {Object} options
*/
clipboard_createClass(Clipboard, [{
key: "resolveOptions",
value: function resolveOptions() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.action = typeof options.action === 'function' ? options.action : this.defaultAction;
this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;
this.text = typeof options.text === 'function' ? options.text : this.defaultText;
this.container = clipboard_typeof(options.container) === 'object' ? options.container : document.body;
}
/**
* Adds a click event listener to the passed trigger.
* @param {String|HTMLElement|HTMLCollection|NodeList} trigger
*/
}, {
key: "listenClick",
value: function listenClick(trigger) {
var _this2 = this;
this.listener = listen_default()(trigger, 'click', function (e) {
return _this2.onClick(e);
});
}
/**
* Defines a new `ClipboardAction` on each click event.
* @param {Event} e
*/
}, {
key: "onClick",
value: function onClick(e) {
var trigger = e.delegateTarget || e.currentTarget;
if (this.clipboardAction) {
this.clipboardAction = null;
}
this.clipboardAction = new clipboard_action({
action: this.action(trigger),
target: this.target(trigger),
text: this.text(trigger),
container: this.container,
trigger: trigger,
emitter: this
});
}
/**
* Default `action` lookup function.
* @param {Element} trigger
*/
}, {
key: "defaultAction",
value: function defaultAction(trigger) {
return getAttributeValue('action', trigger);
}
/**
* Default `target` lookup function.
* @param {Element} trigger
*/
}, {
key: "defaultTarget",
value: function defaultTarget(trigger) {
var selector = getAttributeValue('target', trigger);
if (selector) {
return document.querySelector(selector);
}
}
/**
* Returns the support of the given action, or all actions if no action is
* given.
* @param {String} [action]
*/
}, {
key: "defaultText",
/**
* Default `text` lookup function.
* @param {Element} trigger
*/
value: function defaultText(trigger) {
return getAttributeValue('text', trigger);
}
/**
* Destroy lifecycle.
*/
}, {
key: "destroy",
value: function destroy() {
this.listener.destroy();
if (this.clipboardAction) {
this.clipboardAction.destroy();
this.clipboardAction = null;
}
}
}], [{
key: "isSupported",
value: function isSupported() {
var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut'];
var actions = typeof action === 'string' ? [action] : action;
var support = !!document.queryCommandSupported;
actions.forEach(function (action) {
support = support && !!document.queryCommandSupported(action);
});
return support;
}
}]);
return Clipboard;
}((tiny_emitter_default()));
/* harmony default export */ var clipboard = (Clipboard);
/***/ }),
/***/ 828:
/***/ (function(module) {
var DOCUMENT_NODE_TYPE = 9;
/**
* A polyfill for Element.matches()
*/
if (typeof Element !== 'undefined' && !Element.prototype.matches) {
var proto = Element.prototype;
proto.matches = proto.matchesSelector ||
proto.mozMatchesSelector ||
proto.msMatchesSelector ||
proto.oMatchesSelector ||
proto.webkitMatchesSelector;
}
/**
* Finds the closest parent that matches a selector.
*
* @param {Element} element
* @param {String} selector
* @return {Function}
*/
function closest (element, selector) {
while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
if (typeof element.matches === 'function' &&
element.matches(selector)) {
return element;
}
element = element.parentNode;
}
}
module.exports = closest;
/***/ }),
/***/ 438:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var closest = __webpack_require__(828);
/**
* Delegates event to a selector.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @param {Boolean} useCapture
* @return {Object}
*/
function _delegate(element, selector, type, callback, useCapture) {
var listenerFn = listener.apply(this, arguments);
element.addEventListener(type, listenerFn, useCapture);
return {
destroy: function() {
element.removeEventListener(type, listenerFn, useCapture);
}
}
}
/**
* Delegates event to a selector.
*
* @param {Element|String|Array} [elements]
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @param {Boolean} useCapture
* @return {Object}
*/
function delegate(elements, selector, type, callback, useCapture) {
// Handle the regular Element usage
if (typeof elements.addEventListener === 'function') {
return _delegate.apply(null, arguments);
}
// Handle Element-less usage, it defaults to global delegation
if (typeof type === 'function') {
// Use `document` as the first parameter, then apply arguments
// This is a short way to .unshift `arguments` without running into deoptimizations
return _delegate.bind(null, document).apply(null, arguments);
}
// Handle Selector-based usage
if (typeof elements === 'string') {
elements = document.querySelectorAll(elements);
}
// Handle Array-like based usage
return Array.prototype.map.call(elements, function (element) {
return _delegate(element, selector, type, callback, useCapture);
});
}
/**
* Finds closest match and invokes callback.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @return {Function}
*/
function listener(element, selector, type, callback) {
return function(e) {
e.delegateTarget = closest(e.target, selector);
if (e.delegateTarget) {
callback.call(element, e);
}
}
}
module.exports = delegate;
/***/ }),
/***/ 879:
/***/ (function(__unused_webpack_module, exports) {
/**
* Check if argument is a HTML element.
*
* @param {Object} value
* @return {Boolean}
*/
exports.node = function(value) {
return value !== undefined
&& value instanceof HTMLElement
&& value.nodeType === 1;
};
/**
* Check if argument is a list of HTML elements.
*
* @param {Object} value
* @return {Boolean}
*/
exports.nodeList = function(value) {
var type = Object.prototype.toString.call(value);
return value !== undefined
&& (type === '[object NodeList]' || type === '[object HTMLCollection]')
&& ('length' in value)
&& (value.length === 0 || exports.node(value[0]));
};
/**
* Check if argument is a string.
*
* @param {Object} value
* @return {Boolean}
*/
exports.string = function(value) {
return typeof value === 'string'
|| value instanceof String;
};
/**
* Check if argument is a function.
*
* @param {Object} value
* @return {Boolean}
*/
exports.fn = function(value) {
var type = Object.prototype.toString.call(value);
return type === '[object Function]';
};
/***/ }),
/***/ 370:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var is = __webpack_require__(879);
var delegate = __webpack_require__(438);
/**
* Validates all params and calls the right
* listener function based on its target type.
*
* @param {String|HTMLElement|HTMLCollection|NodeList} target
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listen(target, type, callback) {
if (!target && !type && !callback) {
throw new Error('Missing required arguments');
}
if (!is.string(type)) {
throw new TypeError('Second argument must be a String');
}
if (!is.fn(callback)) {
throw new TypeError('Third argument must be a Function');
}
if (is.node(target)) {
return listenNode(target, type, callback);
}
else if (is.nodeList(target)) {
return listenNodeList(target, type, callback);
}
else if (is.string(target)) {
return listenSelector(target, type, callback);
}
else {
throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
}
}
/**
* Adds an event listener to a HTML element
* and returns a remove listener function.
*
* @param {HTMLElement} node
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenNode(node, type, callback) {
node.addEventListener(type, callback);
return {
destroy: function() {
node.removeEventListener(type, callback);
}
}
}
/**
* Add an event listener to a list of HTML elements
* and returns a remove listener function.
*
* @param {NodeList|HTMLCollection} nodeList
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenNodeList(nodeList, type, callback) {
Array.prototype.forEach.call(nodeList, function(node) {
node.addEventListener(type, callback);
});
return {
destroy: function() {
Array.prototype.forEach.call(nodeList, function(node) {
node.removeEventListener(type, callback);
});
}
}
}
/**
* Add an event listener to a selector
* and returns a remove listener function.
*
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @return {Object}
*/
function listenSelector(selector, type, callback) {
return delegate(document.body, selector, type, callback);
}
module.exports = listen;
/***/ }),
/***/ 817:
/***/ (function(module) {
function select(element) {
var selectedText;
if (element.nodeName === 'SELECT') {
element.focus();
selectedText = element.value;
}
else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
var isReadOnly = element.hasAttribute('readonly');
if (!isReadOnly) {
element.setAttribute('readonly', '');
}
element.select();
element.setSelectionRange(0, element.value.length);
if (!isReadOnly) {
element.removeAttribute('readonly');
}
selectedText = element.value;
}
else {
if (element.hasAttribute('contenteditable')) {
element.focus();
}
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
selectedText = selection.toString();
}
return selectedText;
}
module.exports = select;
/***/ }),
/***/ 279:
/***/ (function(module) {
function E () {
// Keep this empty so it's easier to inherit from
// (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
}
E.prototype = {
on: function (name, callback, ctx) {
var e = this.e || (this.e = {});
(e[name] || (e[name] = [])).push({
fn: callback,
ctx: ctx
});
return this;
},
once: function (name, callback, ctx) {
var self = this;
function listener () {
self.off(name, listener);
callback.apply(ctx, arguments);
};
listener._ = callback
return this.on(name, listener, ctx);
},
emit: function (name) {
var data = [].slice.call(arguments, 1);
var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
var i = 0;
var len = evtArr.length;
for (i; i < len; i++) {
evtArr[i].fn.apply(evtArr[i].ctx, data);
}
return this;
},
off: function (name, callback) {
var e = this.e || (this.e = {});
var evts = e[name];
var liveEvents = [];
if (evts && callback) {
for (var i = 0, len = evts.length; i < len; i++) {
if (evts[i].fn !== callback && evts[i].fn._ !== callback)
liveEvents.push(evts[i]);
}
}
// Remove event from queue to prevent memory leak
// Suggested by https://github.com/lazd
// Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
(liveEvents.length)
? e[name] = liveEvents
: delete e[name];
return this;
}
};
module.exports = E;
module.exports.TinyEmitter = E;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(__webpack_module_cache__[moduleId]) {
/******/ return __webpack_module_cache__[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/************************************************************************/
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // Load entry module and return exports
/******/ return __webpack_require__(134);
/******/ })()
.default;
});

2
wp-includes/js/clipboard.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,43 @@
// JSHINT has some GPL Compatability issues, so we are faking it out and using esprima for validation
// Based on https://github.com/jquery/esprima/blob/gh-pages/demo/validate.js which is MIT licensed
var fakeJSHINT = new function() {
var syntax, errors;
var that = this;
this.data = [];
this.convertError = function( error ){
return {
line: error.lineNumber,
character: error.column,
reason: error.description,
code: 'E'
};
};
this.parse = function( code ){
try {
syntax = window.esprima.parse(code, { tolerant: true, loc: true });
errors = syntax.errors;
if ( errors.length > 0 ) {
for ( var i = 0; i < errors.length; i++) {
var error = errors[i];
that.data.push( that.convertError( error ) );
}
} else {
that.data = [];
}
} catch (e) {
that.data.push( that.convertError( e ) );
}
};
};
window.JSHINT = function( text ){
fakeJSHINT.parse( text );
};
window.JSHINT.data = function(){
return {
errors: fakeJSHINT.data
};
};

View file

@ -0,0 +1,30 @@
/* global HTMLHint */
/* eslint no-magic-numbers: ["error", { "ignore": [0, 1] }] */
HTMLHint.addRule({
id: 'kses',
description: 'Element or attribute cannot be used.',
init: function( parser, reporter, options ) {
'use strict';
var self = this;
parser.addListener( 'tagstart', function( event ) {
var attr, col, attrName, allowedAttributes, i, len, tagName;
tagName = event.tagName.toLowerCase();
if ( ! options[ tagName ] ) {
reporter.error( 'Tag <' + event.tagName + '> is not allowed.', event.line, event.col, self, event.raw );
return;
}
allowedAttributes = options[ tagName ];
col = event.col + event.tagName.length + 1;
for ( i = 0, len = event.attrs.length; i < len; i++ ) {
attr = event.attrs[ i ];
attrName = attr.name.toLowerCase();
if ( ! allowedAttributes[ attrName ] ) {
reporter.error( 'Tag attribute [' + attr.raw + ' ] is not allowed.', event.line, col + attr.index, self, attr.raw );
}
}
});
}
});

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,432 @@
/* Jison generated parser */
var jsonlint = (function(){
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"JSONString":3,"STRING":4,"JSONNumber":5,"NUMBER":6,"JSONNullLiteral":7,"NULL":8,"JSONBooleanLiteral":9,"TRUE":10,"FALSE":11,"JSONText":12,"JSONValue":13,"EOF":14,"JSONObject":15,"JSONArray":16,"{":17,"}":18,"JSONMemberList":19,"JSONMember":20,":":21,",":22,"[":23,"]":24,"JSONElementList":25,"$accept":0,"$end":1},
terminals_: {2:"error",4:"STRING",6:"NUMBER",8:"NULL",10:"TRUE",11:"FALSE",14:"EOF",17:"{",18:"}",21:":",22:",",23:"[",24:"]"},
productions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]],
performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
var $0 = $$.length - 1;
switch (yystate) {
case 1: // replace escaped characters with actual character
this.$ = yytext.replace(/\\(\\|")/g, "$"+"1")
.replace(/\\n/g,'\n')
.replace(/\\r/g,'\r')
.replace(/\\t/g,'\t')
.replace(/\\v/g,'\v')
.replace(/\\f/g,'\f')
.replace(/\\b/g,'\b');
break;
case 2:this.$ = Number(yytext);
break;
case 3:this.$ = null;
break;
case 4:this.$ = true;
break;
case 5:this.$ = false;
break;
case 6:return this.$ = $$[$0-1];
break;
case 13:this.$ = {};
break;
case 14:this.$ = $$[$0-1];
break;
case 15:this.$ = [$$[$0-2], $$[$0]];
break;
case 16:this.$ = {}; this.$[$$[$0][0]] = $$[$0][1];
break;
case 17:this.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1];
break;
case 18:this.$ = [];
break;
case 19:this.$ = $$[$0-1];
break;
case 20:this.$ = [$$[$0]];
break;
case 21:this.$ = $$[$0-2]; $$[$0-2].push($$[$0]);
break;
}
},
table: [{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],12:1,13:2,15:7,16:8,17:[1,14],23:[1,15]},{1:[3]},{14:[1,16]},{14:[2,7],18:[2,7],22:[2,7],24:[2,7]},{14:[2,8],18:[2,8],22:[2,8],24:[2,8]},{14:[2,9],18:[2,9],22:[2,9],24:[2,9]},{14:[2,10],18:[2,10],22:[2,10],24:[2,10]},{14:[2,11],18:[2,11],22:[2,11],24:[2,11]},{14:[2,12],18:[2,12],22:[2,12],24:[2,12]},{14:[2,3],18:[2,3],22:[2,3],24:[2,3]},{14:[2,4],18:[2,4],22:[2,4],24:[2,4]},{14:[2,5],18:[2,5],22:[2,5],24:[2,5]},{14:[2,1],18:[2,1],21:[2,1],22:[2,1],24:[2,1]},{14:[2,2],18:[2,2],22:[2,2],24:[2,2]},{3:20,4:[1,12],18:[1,17],19:18,20:19},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:23,15:7,16:8,17:[1,14],23:[1,15],24:[1,21],25:22},{1:[2,6]},{14:[2,13],18:[2,13],22:[2,13],24:[2,13]},{18:[1,24],22:[1,25]},{18:[2,16],22:[2,16]},{21:[1,26]},{14:[2,18],18:[2,18],22:[2,18],24:[2,18]},{22:[1,28],24:[1,27]},{22:[2,20],24:[2,20]},{14:[2,14],18:[2,14],22:[2,14],24:[2,14]},{3:20,4:[1,12],20:29},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:30,15:7,16:8,17:[1,14],23:[1,15]},{14:[2,19],18:[2,19],22:[2,19],24:[2,19]},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:31,15:7,16:8,17:[1,14],23:[1,15]},{18:[2,17],22:[2,17]},{18:[2,15],22:[2,15]},{22:[2,21],24:[2,21]}],
defaultActions: {16:[2,6]},
parseError: function parseError(str, hash) {
throw new Error(str);
},
parse: function parse(input) {
var self = this,
stack = [0],
vstack = [null], // semantic value stack
lstack = [], // location stack
table = this.table,
yytext = '',
yylineno = 0,
yyleng = 0,
recovering = 0,
TERROR = 2,
EOF = 1;
//this.reductionCount = this.shiftCount = 0;
this.lexer.setInput(input);
this.lexer.yy = this.yy;
this.yy.lexer = this.lexer;
if (typeof this.lexer.yylloc == 'undefined')
this.lexer.yylloc = {};
var yyloc = this.lexer.yylloc;
lstack.push(yyloc);
if (typeof this.yy.parseError === 'function')
this.parseError = this.yy.parseError;
function popStack (n) {
stack.length = stack.length - 2*n;
vstack.length = vstack.length - n;
lstack.length = lstack.length - n;
}
function lex() {
var token;
token = self.lexer.lex() || 1; // $end = 1
// if token isn't its numeric value, convert
if (typeof token !== 'number') {
token = self.symbols_[token] || token;
}
return token;
}
var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected;
while (true) {
// retreive state number from top of stack
state = stack[stack.length-1];
// use default actions if available
if (this.defaultActions[state]) {
action = this.defaultActions[state];
} else {
if (symbol == null)
symbol = lex();
// read action for current state and first input
action = table[state] && table[state][symbol];
}
// handle parse error
_handle_error:
if (typeof action === 'undefined' || !action.length || !action[0]) {
if (!recovering) {
// Report error
expected = [];
for (p in table[state]) if (this.terminals_[p] && p > 2) {
expected.push("'"+this.terminals_[p]+"'");
}
var errStr = '';
if (this.lexer.showPosition) {
errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + this.terminals_[symbol]+ "'";
} else {
errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
(symbol == 1 /*EOF*/ ? "end of input" :
("'"+(this.terminals_[symbol] || symbol)+"'"));
}
this.parseError(errStr,
{text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
}
// just recovered from another error
if (recovering == 3) {
if (symbol == EOF) {
throw new Error(errStr || 'Parsing halted.');
}
// discard current lookahead and grab another
yyleng = this.lexer.yyleng;
yytext = this.lexer.yytext;
yylineno = this.lexer.yylineno;
yyloc = this.lexer.yylloc;
symbol = lex();
}
// try to recover from error
while (1) {
// check for error recovery rule in this state
if ((TERROR.toString()) in table[state]) {
break;
}
if (state == 0) {
throw new Error(errStr || 'Parsing halted.');
}
popStack(1);
state = stack[stack.length-1];
}
preErrorSymbol = symbol; // save the lookahead token
symbol = TERROR; // insert generic error symbol as new lookahead
state = stack[stack.length-1];
action = table[state] && table[state][TERROR];
recovering = 3; // allow 3 real symbols to be shifted before reporting a new error
}
// this shouldn't happen, unless resolve defaults are off
if (action[0] instanceof Array && action.length > 1) {
throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);
}
switch (action[0]) {
case 1: // shift
//this.shiftCount++;
stack.push(symbol);
vstack.push(this.lexer.yytext);
lstack.push(this.lexer.yylloc);
stack.push(action[1]); // push state
symbol = null;
if (!preErrorSymbol) { // normal execution/no error
yyleng = this.lexer.yyleng;
yytext = this.lexer.yytext;
yylineno = this.lexer.yylineno;
yyloc = this.lexer.yylloc;
if (recovering > 0)
recovering--;
} else { // error just occurred, resume old lookahead f/ before error
symbol = preErrorSymbol;
preErrorSymbol = null;
}
break;
case 2: // reduce
//this.reductionCount++;
len = this.productions_[action[1]][1];
// perform semantic action
yyval.$ = vstack[vstack.length-len]; // default to $$ = $1
// default location, uses first token for firsts, last for lasts
yyval._$ = {
first_line: lstack[lstack.length-(len||1)].first_line,
last_line: lstack[lstack.length-1].last_line,
first_column: lstack[lstack.length-(len||1)].first_column,
last_column: lstack[lstack.length-1].last_column
};
r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
if (typeof r !== 'undefined') {
return r;
}
// pop off stack
if (len) {
stack = stack.slice(0,-1*len*2);
vstack = vstack.slice(0, -1*len);
lstack = lstack.slice(0, -1*len);
}
stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce)
vstack.push(yyval.$);
lstack.push(yyval._$);
// goto new state = table[STATE][NONTERMINAL]
newState = table[stack[stack.length-2]][stack[stack.length-1]];
stack.push(newState);
break;
case 3: // accept
return true;
}
}
return true;
}};
/* Jison generated lexer */
var lexer = (function(){
var lexer = ({EOF:1,
parseError:function parseError(str, hash) {
if (this.yy.parseError) {
this.yy.parseError(str, hash);
} else {
throw new Error(str);
}
},
setInput:function (input) {
this._input = input;
this._more = this._less = this.done = false;
this.yylineno = this.yyleng = 0;
this.yytext = this.matched = this.match = '';
this.conditionStack = ['INITIAL'];
this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};
return this;
},
input:function () {
var ch = this._input[0];
this.yytext+=ch;
this.yyleng++;
this.match+=ch;
this.matched+=ch;
var lines = ch.match(/\n/);
if (lines) this.yylineno++;
this._input = this._input.slice(1);
return ch;
},
unput:function (ch) {
this._input = ch + this._input;
return this;
},
more:function () {
this._more = true;
return this;
},
less:function (n) {
this._input = this.match.slice(n) + this._input;
},
pastInput:function () {
var past = this.matched.substr(0, this.matched.length - this.match.length);
return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
},
upcomingInput:function () {
var next = this.match;
if (next.length < 20) {
next += this._input.substr(0, 20-next.length);
}
return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, "");
},
showPosition:function () {
var pre = this.pastInput();
var c = new Array(pre.length + 1).join("-");
return pre + this.upcomingInput() + "\n" + c+"^";
},
next:function () {
if (this.done) {
return this.EOF;
}
if (!this._input) this.done = true;
var token,
match,
tempMatch,
index,
col,
lines;
if (!this._more) {
this.yytext = '';
this.match = '';
}
var rules = this._currentRules();
for (var i=0;i < rules.length; i++) {
tempMatch = this._input.match(this.rules[rules[i]]);
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
match = tempMatch;
index = i;
if (!this.options.flex) break;
}
}
if (match) {
lines = match[0].match(/\n.*/g);
if (lines) this.yylineno += lines.length;
this.yylloc = {first_line: this.yylloc.last_line,
last_line: this.yylineno+1,
first_column: this.yylloc.last_column,
last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length}
this.yytext += match[0];
this.match += match[0];
this.yyleng = this.yytext.length;
this._more = false;
this._input = this._input.slice(match[0].length);
this.matched += match[0];
token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]);
if (this.done && this._input) this.done = false;
if (token) return token;
else return;
}
if (this._input === "") {
return this.EOF;
} else {
this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),
{text: "", token: null, line: this.yylineno});
}
},
lex:function lex() {
var r = this.next();
if (typeof r !== 'undefined') {
return r;
} else {
return this.lex();
}
},
begin:function begin(condition) {
this.conditionStack.push(condition);
},
popState:function popState() {
return this.conditionStack.pop();
},
_currentRules:function _currentRules() {
return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
},
topState:function () {
return this.conditionStack[this.conditionStack.length-2];
},
pushState:function begin(condition) {
this.begin(condition);
}});
lexer.options = {};
lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
var YYSTATE=YY_START
switch($avoiding_name_collisions) {
case 0:/* skip whitespace */
break;
case 1:return 6
break;
case 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4
break;
case 3:return 17
break;
case 4:return 18
break;
case 5:return 23
break;
case 6:return 24
break;
case 7:return 22
break;
case 8:return 21
break;
case 9:return 10
break;
case 10:return 11
break;
case 11:return 8
break;
case 12:return 14
break;
case 13:return 'INVALID'
break;
}
};
lexer.rules = [/^(?:\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\.[0-9]+)?([eE][-+]?[0-9]+)?\b)/,/^(?:"(?:\\[\\"bfnrt/]|\\u[a-fA-F0-9]{4}|[^\\\0-\x09\x0a-\x1f"])*")/,/^(?:\{)/,/^(?:\})/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?::)/,/^(?:true\b)/,/^(?:false\b)/,/^(?:null\b)/,/^(?:$)/,/^(?:.)/];
lexer.conditions = {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}};
;
return lexer;})()
parser.lexer = lexer;
return parser;
})();
if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.parser = jsonlint;
exports.parse = function () { return jsonlint.parse.apply(jsonlint, arguments); }
exports.main = function commonjsMain(args) {
if (!args[1])
throw new Error('Usage: '+args[0]+' FILE');
if (typeof process !== 'undefined') {
var source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8");
} else {
var cwd = require("file").path(require("file").cwd());
var source = cwd.join(args[1]).read({charset: "utf-8"});
}
return exports.parser.parse(source);
}
if (typeof module !== 'undefined' && require.main === module) {
exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require("system").args);
}
}

View file

@ -0,0 +1,707 @@
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================
/* SOURCE FILE: AnchorPosition.js */
/*
AnchorPosition.js
Author: Matt Kruse
Last modified: 10/11/02
DESCRIPTION: These functions find the position of an <A> tag in a document,
so other elements can be positioned relative to it.
COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform.
FUNCTIONS:
getAnchorPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor. Position is relative to the PAGE.
getAnchorWindowPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor, relative to the WHOLE SCREEN.
NOTES:
1) For popping up separate browser windows, use getAnchorWindowPosition.
Otherwise, use getAnchorPosition
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
*/
// getAnchorPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
// This function will return an Object with x and y properties
var useWindow=false;
var coordinates=new Object();
var x=0,y=0;
// Browser capability sniffing
var use_gebi=false, use_css=false, use_layers=false;
if (document.getElementById) { use_gebi=true; }
else if (document.all) { use_css=true; }
else if (document.layers) { use_layers=true; }
// Logic to find position
if (use_gebi && document.all) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_gebi) {
var o=document.getElementById(anchorname);
x=AnchorPosition_getPageOffsetLeft(o);
y=AnchorPosition_getPageOffsetTop(o);
}
else if (use_css) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_layers) {
var found=0;
for (var i=0; i<document.anchors.length; i++) {
if (document.anchors[i].name==anchorname) { found=1; break; }
}
if (found==0) {
coordinates.x=0; coordinates.y=0; return coordinates;
}
x=document.anchors[i].x;
y=document.anchors[i].y;
}
else {
coordinates.x=0; coordinates.y=0; return coordinates;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// getAnchorWindowPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the window
function getAnchorWindowPosition(anchorname) {
var coordinates=getAnchorPosition(anchorname);
var x=0;
var y=0;
if (document.getElementById) {
if (isNaN(window.screenX)) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
}
else if (document.all) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else if (document.layers) {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
var ol=el.offsetLeft;
while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
return ol;
}
function AnchorPosition_getWindowOffsetLeft (el) {
return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
}
function AnchorPosition_getPageOffsetTop (el) {
var ot=el.offsetTop;
while((el=el.offsetParent) != null) { ot += el.offsetTop; }
return ot;
}
function AnchorPosition_getWindowOffsetTop (el) {
return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
}
/* SOURCE FILE: PopupWindow.js */
/*
PopupWindow.js
Author: Matt Kruse
Last modified: 02/16/04
DESCRIPTION: This object allows you to easily and quickly popup a window
in a certain place. The window can either be a DIV or a separate browser
window.
COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform. Due to bugs in Netscape 4.x, populating the popup
window with <STYLE> tags may cause errors.
USAGE:
// Create an object for a WINDOW popup
var win = new PopupWindow();
// Create an object for a DIV window using the DIV named 'mydiv'
var win = new PopupWindow('mydiv');
// Set the window to automatically hide itself when the user clicks
// anywhere else on the page except the popup
win.autoHide();
// Show the window relative to the anchor name passed in
win.showPopup(anchorname);
// Hide the popup
win.hidePopup();
// Set the size of the popup window (only applies to WINDOW popups
win.setSize(width,height);
// Populate the contents of the popup window that will be shown. If you
// change the contents while it is displayed, you will need to refresh()
win.populate(string);
// set the URL of the window, rather than populating its contents
// manually
win.setUrl("http://www.site.com/");
// Refresh the contents of the popup
win.refresh();
// Specify how many pixels to the right of the anchor the popup will appear
win.offsetX = 50;
// Specify how many pixels below the anchor the popup will appear
win.offsetY = 100;
NOTES:
1) Requires the functions in AnchorPosition.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a PopupWindow object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a PopupWindow object or
the autoHide() will not work correctly.
*/
// Set the position of the popup window based on the anchor
function PopupWindow_getXYPosition(anchorname) {
var coordinates;
if (this.type == "WINDOW") {
coordinates = getAnchorWindowPosition(anchorname);
}
else {
coordinates = getAnchorPosition(anchorname);
}
this.x = coordinates.x;
this.y = coordinates.y;
}
// Set width/height of DIV/popup window
function PopupWindow_setSize(width,height) {
this.width = width;
this.height = height;
}
// Fill the window with contents
function PopupWindow_populate(contents) {
this.contents = contents;
this.populated = false;
}
// Set the URL to go to
function PopupWindow_setUrl(url) {
this.url = url;
}
// Set the window popup properties
function PopupWindow_setWindowProperties(props) {
this.windowProperties = props;
}
// Refresh the displayed contents of the popup
function PopupWindow_refresh() {
if (this.divName != null) {
// refresh the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).innerHTML = this.contents;
}
else if (this.use_css) {
document.all[this.divName].innerHTML = this.contents;
}
else if (this.use_layers) {
var d = document.layers[this.divName];
d.document.open();
d.document.writeln(this.contents);
d.document.close();
}
}
else {
if (this.popupWindow != null && !this.popupWindow.closed) {
if (this.url!="") {
this.popupWindow.location.href=this.url;
}
else {
this.popupWindow.document.open();
this.popupWindow.document.writeln(this.contents);
this.popupWindow.document.close();
}
this.popupWindow.focus();
}
}
}
// Position and show the popup, relative to an anchor object
function PopupWindow_showPopup(anchorname) {
this.getXYPosition(anchorname);
this.x += this.offsetX;
this.y += this.offsetY;
if (!this.populated && (this.contents != "")) {
this.populated = true;
this.refresh();
}
if (this.divName != null) {
// Show the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).style.left = this.x + "px";
document.getElementById(this.divName).style.top = this.y;
document.getElementById(this.divName).style.visibility = "visible";
}
else if (this.use_css) {
document.all[this.divName].style.left = this.x;
document.all[this.divName].style.top = this.y;
document.all[this.divName].style.visibility = "visible";
}
else if (this.use_layers) {
document.layers[this.divName].left = this.x;
document.layers[this.divName].top = this.y;
document.layers[this.divName].visibility = "visible";
}
}
else {
if (this.popupWindow == null || this.popupWindow.closed) {
// If the popup window will go off-screen, move it so it doesn't
if (this.x<0) { this.x=0; }
if (this.y<0) { this.y=0; }
if (screen && screen.availHeight) {
if ((this.y + this.height) > screen.availHeight) {
this.y = screen.availHeight - this.height;
}
}
if (screen && screen.availWidth) {
if ((this.x + this.width) > screen.availWidth) {
this.x = screen.availWidth - this.width;
}
}
var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled );
this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+"");
}
this.refresh();
}
}
// Hide the popup
function PopupWindow_hidePopup() {
if (this.divName != null) {
if (this.use_gebi) {
document.getElementById(this.divName).style.visibility = "hidden";
}
else if (this.use_css) {
document.all[this.divName].style.visibility = "hidden";
}
else if (this.use_layers) {
document.layers[this.divName].visibility = "hidden";
}
}
else {
if (this.popupWindow && !this.popupWindow.closed) {
this.popupWindow.close();
this.popupWindow = null;
}
}
}
// Pass an event and return whether or not it was the popup DIV that was clicked
function PopupWindow_isClicked(e) {
if (this.divName != null) {
if (this.use_layers) {
var clickX = e.pageX;
var clickY = e.pageY;
var t = document.layers[this.divName];
if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) {
return true;
}
else { return false; }
}
else if (document.all) { // Need to hard-code this to trap IE for error-handling
var t = window.event.srcElement;
while (t.parentElement != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentElement;
}
return false;
}
else if (this.use_gebi && e) {
var t = e.originalTarget;
while (t.parentNode != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentNode;
}
return false;
}
return false;
}
return false;
}
// Check an onMouseDown event to see if we should hide
function PopupWindow_hideIfNotClicked(e) {
if (this.autoHideEnabled && !this.isClicked(e)) {
this.hidePopup();
}
}
// Call this to make the DIV disable automatically when mouse is clicked outside it
function PopupWindow_autoHide() {
this.autoHideEnabled = true;
}
// This global function checks all PopupWindow objects onmouseup to see if they should be hidden
function PopupWindow_hidePopupWindows(e) {
for (var i=0; i<popupWindowObjects.length; i++) {
if (popupWindowObjects[i] != null) {
var p = popupWindowObjects[i];
p.hideIfNotClicked(e);
}
}
}
// Run this immediately to attach the event listener
function PopupWindow_attachListener() {
if (document.layers) {
document.captureEvents(Event.MOUSEUP);
}
window.popupWindowOldEventListener = document.onmouseup;
if (window.popupWindowOldEventListener != null) {
document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();");
}
else {
document.onmouseup = PopupWindow_hidePopupWindows;
}
}
// CONSTRUCTOR for the PopupWindow object
// Pass it a DIV name to use a DHTML popup, otherwise will default to window popup
function PopupWindow() {
if (!window.popupWindowIndex) { window.popupWindowIndex = 0; }
if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); }
if (!window.listenerAttached) {
window.listenerAttached = true;
PopupWindow_attachListener();
}
this.index = popupWindowIndex++;
popupWindowObjects[this.index] = this;
this.divName = null;
this.popupWindow = null;
this.width=0;
this.height=0;
this.populated = false;
this.visible = false;
this.autoHideEnabled = false;
this.contents = "";
this.url="";
this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no";
if (arguments.length>0) {
this.type="DIV";
this.divName = arguments[0];
}
else {
this.type="WINDOW";
}
this.use_gebi = false;
this.use_css = false;
this.use_layers = false;
if (document.getElementById) { this.use_gebi = true; }
else if (document.all) { this.use_css = true; }
else if (document.layers) { this.use_layers = true; }
else { this.type = "WINDOW"; }
this.offsetX = 0;
this.offsetY = 0;
// Method mappings
this.getXYPosition = PopupWindow_getXYPosition;
this.populate = PopupWindow_populate;
this.setUrl = PopupWindow_setUrl;
this.setWindowProperties = PopupWindow_setWindowProperties;
this.refresh = PopupWindow_refresh;
this.showPopup = PopupWindow_showPopup;
this.hidePopup = PopupWindow_hidePopup;
this.setSize = PopupWindow_setSize;
this.isClicked = PopupWindow_isClicked;
this.autoHide = PopupWindow_autoHide;
this.hideIfNotClicked = PopupWindow_hideIfNotClicked;
}
/* SOURCE FILE: ColorPicker2.js */
/*
Last modified: 02/24/2003
DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB
form. It uses a color "swatch" to display the standard 216-color web-safe
palette. The user can then click on a color to select it.
COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js.
Only the latest DHTML-capable browsers will show the color and hex values
at the bottom as your mouse goes over them.
USAGE:
// Create a new ColorPicker object using DHTML popup
var cp = new ColorPicker();
// Create a new ColorPicker object using Window Popup
var cp = new ColorPicker('window');
// Add a link in your page to trigger the popup. For example:
<A HREF="#" onClick="cp.show('pick');return false;" NAME="pick" ID="pick">Pick</A>
// Or use the built-in "select" function to do the dirty work for you:
<A HREF="#" onClick="cp.select(document.forms[0].color,'pick');return false;" NAME="pick" ID="pick">Pick</A>
// If using DHTML popup, write out the required DIV tag near the bottom
// of your page.
<SCRIPT LANGUAGE="JavaScript">cp.writeDiv()</SCRIPT>
// Write the 'pickColor' function that will be called when the user clicks
// a color and do something with the value. This is only required if you
// want to do something other than simply populate a form field, which is
// what the 'select' function will give you.
function pickColor(color) {
field.value = color;
}
NOTES:
1) Requires the functions in AnchorPosition.js and PopupWindow.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a ColorPicker object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a ColorPicker object or
the color picker will not hide itself correctly.
*/
ColorPicker_targetInput = null;
function ColorPicker_writeDiv() {
document.writeln("<DIV ID=\"colorPickerDiv\" STYLE=\"position:absolute;visibility:hidden;\"> </DIV>");
}
function ColorPicker_show(anchorname) {
this.showPopup(anchorname);
}
function ColorPicker_pickColor(color,obj) {
obj.hidePopup();
pickColor(color);
}
// A Default "pickColor" function to accept the color passed back from popup.
// User can over-ride this with their own function.
function pickColor(color) {
if (ColorPicker_targetInput==null) {
alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!");
return;
}
ColorPicker_targetInput.value = color;
}
// This function is the easiest way to popup the window, select a color, and
// have the value populate a form field, which is what most people want to do.
function ColorPicker_select(inputobj,linkname) {
if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") {
alert("colorpicker.select: Input object passed is not a valid form input object");
window.ColorPicker_targetInput=null;
return;
}
window.ColorPicker_targetInput = inputobj;
this.show(linkname);
}
// This function runs when you move your mouse over a color block, if you have a newer browser
function ColorPicker_highlightColor(c) {
var thedoc = (arguments.length>1)?arguments[1]:window.document;
var d = thedoc.getElementById("colorPickerSelectedColor");
d.style.backgroundColor = c;
d = thedoc.getElementById("colorPickerSelectedColorValue");
d.innerHTML = c;
}
function ColorPicker() {
var windowMode = false;
// Create a new PopupWindow object
if (arguments.length==0) {
var divname = "colorPickerDiv";
}
else if (arguments[0] == "window") {
var divname = '';
windowMode = true;
}
else {
var divname = arguments[0];
}
if (divname != "") {
var cp = new PopupWindow(divname);
}
else {
var cp = new PopupWindow();
cp.setSize(225,250);
}
// Object variables
cp.currentValue = "#FFFFFF";
// Method Mappings
cp.writeDiv = ColorPicker_writeDiv;
cp.highlightColor = ColorPicker_highlightColor;
cp.show = ColorPicker_show;
cp.select = ColorPicker_select;
// Code to populate color picker window
var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099",
"#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099",
"#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099",
"#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF",
"#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F",
"#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000",
"#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399",
"#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399",
"#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399",
"#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF",
"#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F",
"#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00",
"#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699",
"#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699",
"#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699",
"#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F",
"#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F",
"#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F",
"#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999",
"#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999",
"#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999",
"#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF",
"#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F",
"#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000",
"#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99",
"#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99",
"#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99",
"#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF",
"#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F",
"#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00",
"#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99",
"#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99",
"#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99",
"#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F",
"#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F",
"#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F",
"#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666",
"#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000",
"#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000",
"#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999",
"#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF",
"#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66",
"#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00",
"#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000",
"#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099",
"#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF",
"#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF",
"#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC",
"#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000",
"#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900",
"#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33",
"#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF",
"#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF",
"#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F",
"#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F",
"#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F",
"#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000");
var total = colors.length;
var width = 72;
var cp_contents = "";
var windowRef = (windowMode)?"window.opener.":"";
if (windowMode) {
cp_contents += "<html><head><title>Select Color</title></head>";
cp_contents += "<body marginwidth=0 marginheight=0 leftmargin=0 topmargin=0><span style='text-align: center;'>";
}
cp_contents += "<table style='border: none;' cellspacing=0 cellpadding=0>";
var use_highlight = (document.getElementById || document.all)?true:false;
for (var i=0; i<total; i++) {
if ((i % width) == 0) { cp_contents += "<tr>"; }
if (use_highlight) { var mo = 'onMouseOver="'+windowRef+'ColorPicker_highlightColor(\''+colors[i]+'\',window.document)"'; }
else { mo = ""; }
cp_contents += '<td style="background-color: '+colors[i]+';"><a href="javascript:void()" onclick="'+windowRef+'ColorPicker_pickColor(\''+colors[i]+'\','+windowRef+'window.popupWindowObjects['+cp.index+']);return false;" '+mo+'>&nbsp;</a></td>';
if ( ((i+1)>=total) || (((i+1) % width) == 0)) {
cp_contents += "</tr>";
}
}
// If the browser supports dynamically changing TD cells, add the fancy stuff
if (document.getElementById) {
var width1 = Math.floor(width/2);
var width2 = width = width1;
cp_contents += "<tr><td colspan='"+width1+"' style='background-color: #FFF;' ID='colorPickerSelectedColor'>&nbsp;</td><td colspan='"+width2+"' style='text-align: center;' id='colorPickerSelectedColorValue'>#FFFFFF</td></tr>";
}
cp_contents += "</table>";
if (windowMode) {
cp_contents += "</span></body></html>";
}
// end populate code
// Write the contents to the popup object
cp.populate(cp_contents+"\n");
// Move the table down a bit so you can see it
cp.offsetY = 25;
cp.autoHide();
return cp;
}

2
wp-includes/js/colorpicker.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,444 @@
/**
* Handles the addition of the comment form.
*
* @since 2.7.0
* @output wp-includes/js/comment-reply.js
*
* @namespace addComment
*
* @type {Object}
*/
window.addComment = ( function( window ) {
// Avoid scope lookups on commonly used variables.
var document = window.document;
// Settings.
var config = {
commentReplyClass : 'comment-reply-link',
commentReplyTitleId : 'reply-title',
cancelReplyId : 'cancel-comment-reply-link',
commentFormId : 'commentform',
temporaryFormId : 'wp-temp-form-div',
parentIdFieldId : 'comment_parent',
postIdFieldId : 'comment_post_ID'
};
// Cross browser MutationObserver.
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
// Check browser cuts the mustard.
var cutsTheMustard = 'querySelector' in document && 'addEventListener' in window;
/*
* Check browser supports dataset.
* !! sets the variable to true if the property exists.
*/
var supportsDataset = !! document.documentElement.dataset;
// For holding the cancel element.
var cancelElement;
// For holding the comment form element.
var commentFormElement;
// The respond element.
var respondElement;
// The mutation observer.
var observer;
if ( cutsTheMustard && document.readyState !== 'loading' ) {
ready();
} else if ( cutsTheMustard ) {
window.addEventListener( 'DOMContentLoaded', ready, false );
}
/**
* Sets up object variables after the DOM is ready.
*
* @since 5.1.1
*/
function ready() {
// Initialise the events.
init();
// Set up a MutationObserver to check for comments loaded late.
observeChanges();
}
/**
* Add events to links classed .comment-reply-link.
*
* Searches the context for reply links and adds the JavaScript events
* required to move the comment form. To allow for lazy loading of
* comments this method is exposed as window.commentReply.init().
*
* @since 5.1.0
*
* @memberOf addComment
*
* @param {HTMLElement} context The parent DOM element to search for links.
*/
function init( context ) {
if ( ! cutsTheMustard ) {
return;
}
// Get required elements.
cancelElement = getElementById( config.cancelReplyId );
commentFormElement = getElementById( config.commentFormId );
// No cancel element, no replies.
if ( ! cancelElement ) {
return;
}
cancelElement.addEventListener( 'touchstart', cancelEvent );
cancelElement.addEventListener( 'click', cancelEvent );
// Submit the comment form when the user types [Ctrl] or [Cmd] + [Enter].
var submitFormHandler = function( e ) {
if ( ( e.metaKey || e.ctrlKey ) && e.keyCode === 13 ) {
commentFormElement.removeEventListener( 'keydown', submitFormHandler );
e.preventDefault();
// The submit button ID is 'submit' so we can't call commentFormElement.submit(). Click it instead.
commentFormElement.submit.click();
return false;
}
};
if ( commentFormElement ) {
commentFormElement.addEventListener( 'keydown', submitFormHandler );
}
var links = replyLinks( context );
var element;
for ( var i = 0, l = links.length; i < l; i++ ) {
element = links[i];
element.addEventListener( 'touchstart', clickEvent );
element.addEventListener( 'click', clickEvent );
}
}
/**
* Return all links classed .comment-reply-link.
*
* @since 5.1.0
*
* @param {HTMLElement} context The parent DOM element to search for links.
*
* @return {HTMLCollection|NodeList|Array}
*/
function replyLinks( context ) {
var selectorClass = config.commentReplyClass;
var allReplyLinks;
// childNodes is a handy check to ensure the context is a HTMLElement.
if ( ! context || ! context.childNodes ) {
context = document;
}
if ( document.getElementsByClassName ) {
// Fastest.
allReplyLinks = context.getElementsByClassName( selectorClass );
}
else {
// Fast.
allReplyLinks = context.querySelectorAll( '.' + selectorClass );
}
return allReplyLinks;
}
/**
* Cancel event handler.
*
* @since 5.1.0
*
* @param {Event} event The calling event.
*/
function cancelEvent( event ) {
var cancelLink = this;
var temporaryFormId = config.temporaryFormId;
var temporaryElement = getElementById( temporaryFormId );
if ( ! temporaryElement || ! respondElement ) {
// Conditions for cancel link fail.
return;
}
getElementById( config.parentIdFieldId ).value = '0';
// Move the respond form back in place of the temporary element.
var headingText = temporaryElement.textContent;
temporaryElement.parentNode.replaceChild( respondElement, temporaryElement );
cancelLink.style.display = 'none';
var replyHeadingElement = getElementById( config.commentReplyTitleId );
var replyHeadingTextNode = replyHeadingElement && replyHeadingElement.firstChild;
var replyLinkToParent = replyHeadingTextNode && replyHeadingTextNode.nextSibling;
if ( replyHeadingTextNode && replyHeadingTextNode.nodeType === Node.TEXT_NODE && headingText ) {
if ( replyLinkToParent && 'A' === replyLinkToParent.nodeName && replyLinkToParent.id !== config.cancelReplyId ) {
replyLinkToParent.style.display = '';
}
replyHeadingTextNode.textContent = headingText;
}
event.preventDefault();
}
/**
* Click event handler.
*
* @since 5.1.0
*
* @param {Event} event The calling event.
*/
function clickEvent( event ) {
var replyNode = getElementById( config.commentReplyTitleId );
var defaultReplyHeading = replyNode && replyNode.firstChild.textContent;
var replyLink = this,
commId = getDataAttribute( replyLink, 'belowelement' ),
parentId = getDataAttribute( replyLink, 'commentid' ),
respondId = getDataAttribute( replyLink, 'respondelement' ),
postId = getDataAttribute( replyLink, 'postid' ),
replyTo = getDataAttribute( replyLink, 'replyto' ) || defaultReplyHeading,
follow;
if ( ! commId || ! parentId || ! respondId || ! postId ) {
/*
* Theme or plugin defines own link via custom `wp_list_comments()` callback
* and calls `moveForm()` either directly or via a custom event hook.
*/
return;
}
/*
* Third party comments systems can hook into this function via the global scope,
* therefore the click event needs to reference the global scope.
*/
follow = window.addComment.moveForm( commId, parentId, respondId, postId, replyTo );
if ( false === follow ) {
event.preventDefault();
}
}
/**
* Creates a mutation observer to check for newly inserted comments.
*
* @since 5.1.0
*/
function observeChanges() {
if ( ! MutationObserver ) {
return;
}
var observerOptions = {
childList: true,
subtree: true
};
observer = new MutationObserver( handleChanges );
observer.observe( document.body, observerOptions );
}
/**
* Handles DOM changes, calling init() if any new nodes are added.
*
* @since 5.1.0
*
* @param {Array} mutationRecords Array of MutationRecord objects.
*/
function handleChanges( mutationRecords ) {
var i = mutationRecords.length;
while ( i-- ) {
// Call init() once if any record in this set adds nodes.
if ( mutationRecords[ i ].addedNodes.length ) {
init();
return;
}
}
}
/**
* Backward compatible getter of data-* attribute.
*
* Uses element.dataset if it exists, otherwise uses getAttribute.
*
* @since 5.1.0
*
* @param {HTMLElement} Element DOM element with the attribute.
* @param {string} Attribute the attribute to get.
*
* @return {string}
*/
function getDataAttribute( element, attribute ) {
if ( supportsDataset ) {
return element.dataset[attribute];
}
else {
return element.getAttribute( 'data-' + attribute );
}
}
/**
* Get element by ID.
*
* Local alias for document.getElementById.
*
* @since 5.1.0
*
* @param {HTMLElement} The requested element.
*/
function getElementById( elementId ) {
return document.getElementById( elementId );
}
/**
* Moves the reply form from its current position to the reply location.
*
* @since 2.7.0
*
* @memberOf addComment
*
* @param {string} addBelowId HTML ID of element the form follows.
* @param {string} commentId Database ID of comment being replied to.
* @param {string} respondId HTML ID of 'respond' element.
* @param {string} postId Database ID of the post.
* @param {string} replyTo Form heading content.
*/
function moveForm( addBelowId, commentId, respondId, postId, replyTo ) {
// Get elements based on their IDs.
var addBelowElement = getElementById( addBelowId );
respondElement = getElementById( respondId );
// Get the hidden fields.
var parentIdField = getElementById( config.parentIdFieldId );
var postIdField = getElementById( config.postIdFieldId );
var element, cssHidden, style;
var replyHeading = getElementById( config.commentReplyTitleId );
var replyHeadingTextNode = replyHeading && replyHeading.firstChild;
var replyLinkToParent = replyHeadingTextNode && replyHeadingTextNode.nextSibling;
if ( ! addBelowElement || ! respondElement || ! parentIdField ) {
// Missing key elements, fail.
return;
}
if ( 'undefined' === typeof replyTo ) {
replyTo = replyHeadingTextNode && replyHeadingTextNode.textContent;
}
addPlaceHolder( respondElement );
// Set the value of the post.
if ( postId && postIdField ) {
postIdField.value = postId;
}
parentIdField.value = commentId;
cancelElement.style.display = '';
addBelowElement.parentNode.insertBefore( respondElement, addBelowElement.nextSibling );
if ( replyHeadingTextNode && replyHeadingTextNode.nodeType === Node.TEXT_NODE ) {
if ( replyLinkToParent && 'A' === replyLinkToParent.nodeName && replyLinkToParent.id !== config.cancelReplyId ) {
replyLinkToParent.style.display = 'none';
}
replyHeadingTextNode.textContent = replyTo;
}
/*
* This is for backward compatibility with third party commenting systems
* hooking into the event using older techniques.
*/
cancelElement.onclick = function() {
return false;
};
// Focus on the first field in the comment form.
try {
for ( var i = 0; i < commentFormElement.elements.length; i++ ) {
element = commentFormElement.elements[i];
cssHidden = false;
// Get elements computed style.
if ( 'getComputedStyle' in window ) {
// Modern browsers.
style = window.getComputedStyle( element );
} else if ( document.documentElement.currentStyle ) {
// IE 8.
style = element.currentStyle;
}
/*
* For display none, do the same thing jQuery does. For visibility,
* check the element computed style since browsers are already doing
* the job for us. In fact, the visibility computed style is the actual
* computed value and already takes into account the element ancestors.
*/
if ( ( element.offsetWidth <= 0 && element.offsetHeight <= 0 ) || style.visibility === 'hidden' ) {
cssHidden = true;
}
// Skip form elements that are hidden or disabled.
if ( 'hidden' === element.type || element.disabled || cssHidden ) {
continue;
}
element.focus();
// Stop after the first focusable element.
break;
}
}
catch(e) {
}
/*
* false is returned for backward compatibility with third party commenting systems
* hooking into this function.
*/
return false;
}
/**
* Add placeholder element.
*
* Places a place holder element above the #respond element for
* the form to be returned to if needs be.
*
* @since 2.7.0
*
* @param {HTMLelement} respondElement the #respond element holding comment form.
*/
function addPlaceHolder( respondElement ) {
var temporaryFormId = config.temporaryFormId;
var temporaryElement = getElementById( temporaryFormId );
var replyElement = getElementById( config.commentReplyTitleId );
var initialHeadingText = replyElement ? replyElement.firstChild.textContent : '';
if ( temporaryElement ) {
// The element already exists, no need to recreate.
return;
}
temporaryElement = document.createElement( 'div' );
temporaryElement.id = temporaryFormId;
temporaryElement.style.display = 'none';
temporaryElement.textContent = initialHeadingText;
respondElement.parentNode.insertBefore( temporaryElement, respondElement );
}
return {
init: init,
moveForm: moveForm
};
})( window );

2
wp-includes/js/comment-reply.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
window.addComment=function(v){var I,C,h,E=v.document,b={commentReplyClass:"comment-reply-link",commentReplyTitleId:"reply-title",cancelReplyId:"cancel-comment-reply-link",commentFormId:"commentform",temporaryFormId:"wp-temp-form-div",parentIdFieldId:"comment_parent",postIdFieldId:"comment_post_ID"},e=v.MutationObserver||v.WebKitMutationObserver||v.MozMutationObserver,r="querySelector"in E&&"addEventListener"in v,n=!!E.documentElement.dataset;function t(){d(),e&&new e(o).observe(E.body,{childList:!0,subtree:!0})}function d(e){if(r&&(I=g(b.cancelReplyId),C=g(b.commentFormId),I)){I.addEventListener("touchstart",l),I.addEventListener("click",l);var t=function(e){if((e.metaKey||e.ctrlKey)&&13===e.keyCode)return C.removeEventListener("keydown",t),e.preventDefault(),C.submit.click(),!1};C&&C.addEventListener("keydown",t);for(var n,d=function(e){var t=b.commentReplyClass;e&&e.childNodes||(e=E);t=E.getElementsByClassName?e.getElementsByClassName(t):e.querySelectorAll("."+t);return t}(e),o=0,i=d.length;o<i;o++)(n=d[o]).addEventListener("touchstart",a),n.addEventListener("click",a)}}function l(e){var t,n,d=g(b.temporaryFormId);d&&h&&(g(b.parentIdFieldId).value="0",t=d.textContent,d.parentNode.replaceChild(h,d),this.style.display="none",n=(d=(n=g(b.commentReplyTitleId))&&n.firstChild)&&d.nextSibling,d&&d.nodeType===Node.TEXT_NODE&&t&&(n&&"A"===n.nodeName&&n.id!==b.cancelReplyId&&(n.style.display=""),d.textContent=t),e.preventDefault())}function a(e){var t=g(b.commentReplyTitleId),n=t&&t.firstChild.textContent,d=this,o=m(d,"belowelement"),i=m(d,"commentid"),r=m(d,"respondelement"),t=m(d,"postid"),n=m(d,"replyto")||n;o&&i&&r&&t&&!1===v.addComment.moveForm(o,i,r,t,n)&&e.preventDefault()}function o(e){for(var t=e.length;t--;)if(e[t].addedNodes.length)return void d()}function m(e,t){return n?e.dataset[t]:e.getAttribute("data-"+t)}function g(e){return E.getElementById(e)}return r&&"loading"!==E.readyState?t():r&&v.addEventListener("DOMContentLoaded",t,!1),{init:d,moveForm:function(e,t,n,d,o){var i=g(e);h=g(n);var r,l,a,m,c,s=g(b.parentIdFieldId),y=g(b.postIdFieldId),p=(c=g(b.commentReplyTitleId))&&c.firstChild,u=p&&p.nextSibling;if(i&&h&&s){void 0===o&&(o=p&&p.textContent),m=h,e=b.temporaryFormId,n=g(e),c=(c=g(b.commentReplyTitleId))?c.firstChild.textContent:"",n||((n=E.createElement("div")).id=e,n.style.display="none",n.textContent=c,m.parentNode.insertBefore(n,m)),d&&y&&(y.value=d),s.value=t,I.style.display="",i.parentNode.insertBefore(h,i.nextSibling),p&&p.nodeType===Node.TEXT_NODE&&(u&&"A"===u.nodeName&&u.id!==b.cancelReplyId&&(u.style.display="none"),p.textContent=o),I.onclick=function(){return!1};try{for(var f=0;f<C.elements.length;f++)if(r=C.elements[f],l=!1,"getComputedStyle"in v?a=v.getComputedStyle(r):E.documentElement.currentStyle&&(a=r.currentStyle),(r.offsetWidth<=0&&r.offsetHeight<=0||"hidden"===a.visibility)&&(l=!0),"hidden"!==r.type&&!r.disabled&&!l){r.focus();break}}catch(e){}return!1}}}}(window);

View file

@ -0,0 +1,165 @@
.imgCrop_wrap {
/* width: 500px; @done_in_js */
/* height: 375px; @done_in_js */
position: relative;
cursor: crosshair;
}
/* an extra classname is applied for Opera < 9.0 to fix its lack of opacity support */
.imgCrop_wrap.opera8 .imgCrop_overlay,
.imgCrop_wrap.opera8 .imgCrop_clickArea {
background-color: transparent;
}
/* fix for IE displaying all boxes at line-height by default, although they are still 1 pixel high until we combine them with the pointless span */
.imgCrop_wrap,
.imgCrop_wrap * {
font-size: 0;
}
.imgCrop_overlay {
background-color: #000;
opacity: 0.5;
filter:alpha(opacity=50);
position: absolute;
width: 100%;
height: 100%;
}
.imgCrop_selArea {
position: absolute;
/* @done_in_js
top: 20px;
left: 20px;
width: 200px;
height: 200px;
background: transparent url(castle.jpg) no-repeat -210px -110px;
*/
cursor: move;
z-index: 2;
}
/* clickArea is all a fix for IE 5.5 & 6 to allow the user to click on the given area */
.imgCrop_clickArea {
width: 100%;
height: 100%;
background-color: #FFF;
opacity: 0.01;
filter:alpha(opacity=01);
}
.imgCrop_marqueeHoriz {
position: absolute;
width: 100%;
height: 1px;
background: transparent url(marqueeHoriz.gif) repeat-x 0 0;
z-index: 3;
}
.imgCrop_marqueeVert {
position: absolute;
height: 100%;
width: 1px;
background: transparent url(marqueeVert.gif) repeat-y 0 0;
z-index: 3;
}
.imgCrop_marqueeNorth { top: 0; left: 0; }
.imgCrop_marqueeEast { top: 0; right: 0; }
.imgCrop_marqueeSouth { bottom: 0px; left: 0; }
.imgCrop_marqueeWest { top: 0; left: 0; }
.imgCrop_handle {
position: absolute;
border: 1px solid #333;
width: 6px;
height: 6px;
background: #FFF;
opacity: 0.5;
filter:alpha(opacity=50);
z-index: 4;
}
/* fix IE 5 box model */
* html .imgCrop_handle {
width: 8px;
height: 8px;
wid\th: 6px;
hei\ght: 6px;
}
.imgCrop_handleN {
top: -3px;
left: 0;
/* margin-left: 49%; @done_in_js */
cursor: n-resize;
}
.imgCrop_handleNE {
top: -3px;
right: -3px;
cursor: ne-resize;
}
.imgCrop_handleE {
top: 0;
right: -3px;
/* margin-top: 49%; @done_in_js */
cursor: e-resize;
}
.imgCrop_handleSE {
right: -3px;
bottom: -3px;
cursor: se-resize;
}
.imgCrop_handleS {
right: 0;
bottom: -3px;
/* margin-right: 49%; @done_in_js */
cursor: s-resize;
}
.imgCrop_handleSW {
left: -3px;
bottom: -3px;
cursor: sw-resize;
}
.imgCrop_handleW {
top: 0;
left: -3px;
/* margin-top: 49%; @done_in_js */
cursor: e-resize;
}
.imgCrop_handleNW {
top: -3px;
left: -3px;
cursor: nw-resize;
}
/**
* Create an area to click & drag around on as the default browser behaviour is to let you drag the image
*/
.imgCrop_dragArea {
width: 100%;
height: 100%;
z-index: 200;
position: absolute;
top: 0;
left: 0;
}
.imgCrop_previewWrap {
/* width: 200px; @done_in_js */
/* height: 200px; @done_in_js */
overflow: hidden;
position: relative;
}
.imgCrop_previewWrap img {
position: absolute;
}

View file

@ -0,0 +1,516 @@
/**
* Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://www.opensource.org/licenses/bsd-license.php
*
* See scriptaculous.js for full scriptaculous licence
*/
var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{});
if(this.options.minWidth>0&&this.options.minHeight>0){
this.options.ratioDim.x=this.options.minWidth;
this.options.ratioDim.y=this.options.minHeight;
}
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){return 1;
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
if(this.isIE){
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
}else{
this.overlay=Builder.node("div",{"class":_f+"overlay"});
var _12=[this.overlay];
}
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"});
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_13.length;i++){
Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
if(!this.isIE){
Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"});
Element.hide($(this.overlay));
Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"});
}else{
Element.setStyle($(this.north),{height:0});
Element.setStyle($(this.east),{width:0,height:0});
Element.setStyle($(this.south),{height:0});
Element.setStyle($(this.west),{width:0,height:0});
}
Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"});
Element.hide($(this.selArea));
var _15=Position.positionedOffset(this.imgWrap);
this.wrapOffsets={"top":_15[1],"left":_15[0]};
var _16={x1:0,y1:0,x2:0,y2:0};
this.setAreaCoords(_16);
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){
_16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_16.x2=_16.x1+this.options.ratioDim.x;
_16.y2=_16.y1+this.options.ratioDim.y;
Element.show(this.selArea);
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_17.length;i++){
Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1b){
this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true);
this.drawArea();
},cloneCoords:function(_1c){
return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2};
},setAreaCoords:function(_1d,_1e,_1f,_20,_21){
var _22=typeof _1e!="undefined"?_1e:false;
var _23=typeof _1f!="undefined"?_1f:false;
if(_1e){
var _24=_1d.x2-_1d.x1;
var _25=_1d.y2-_1d.y1;
if(_1d.x1<0){
_1d.x1=0;
_1d.x2=_24;
}
if(_1d.y1<0){
_1d.y1=0;
_1d.y2=_25;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
_1d.x1=this.imgW-_24;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
_1d.y1=this.imgH-_25;
}
}else{
if(_1d.x1<0){
_1d.x1=0;
}
if(_1d.y1<0){
_1d.y1=0;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
}
if(typeof (_20)!="undefined"){
if(this.ratioX>0){
this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21);
}else{
if(_23){
this.applyRatio(_1d,{x:1,y:1},_20,_21);
}
}
var _26={a1:_1d.x1,a2:_1d.x2};
var _27={a1:_1d.y1,a2:_1d.y2};
var _28=this.options.minWidth;
var _29=this.options.minHeight;
if((_28==0||_29==0)&&_23){
if(_28>0){
_29=_28;
}else{
if(_29>0){
_28=_29;
}
}
}
this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW});
this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH});
_1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2};
}
}
this.areaCoords=_1d;
},applyMinDimension:function(_2a,_2b,_2c,_2d){
if((_2a.a2-_2a.a1)<_2b){
if(_2c==1){
_2a.a2=_2a.a1+_2b;
}else{
_2a.a1=_2a.a2-_2b;
}
if(_2a.a1<_2d.min){
_2a.a1=_2d.min;
_2a.a2=_2b;
}else{
if(_2a.a2>_2d.max){
_2a.a1=_2d.max-_2b;
_2a.a2=_2d.max;
}
}
}
},applyRatio:function(_2e,_2f,_30,_31){
var _32;
if(_31=="N"||_31=="S"){
_32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW});
_2e.x1=_32.b1;
_2e.y1=_32.a1;
_2e.x2=_32.b2;
_2e.y2=_32.a2;
}else{
_32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH});
_2e.x1=_32.a1;
_2e.y1=_32.b1;
_2e.x2=_32.a2;
_2e.y2=_32.b2;
}
},applyRatioToAxis:function(_33,_34,_35,_36){
var _37=Object.extend(_33,{});
var _38=_37.a2-_37.a1;
var _3a=Math.floor(_38*_34.b/_34.a);
var _3b;
var _3c;
var _3d=null;
if(_35.b==1){
_3b=_37.b1+_3a;
if(_3b>_36.max){
_3b=_36.max;
_3d=_3b-_37.b1;
}
_37.b2=_3b;
}else{
_3b=_37.b2-_3a;
if(_3b<_36.min){
_3b=_36.min;
_3d=_3b+_37.b2;
}
_37.b1=_3b;
}
if(_3d!=null){
_3c=Math.floor(_3d*_34.a/_34.b);
if(_35.a==1){
_37.a2=_37.a1+_3c;
}else{
_37.a1=_37.a1=_37.a2-_3c;
}
}
return _37;
},drawArea:function(){
if(!this.isIE){
Element.show($(this.overlay));
}
var _3e=this.calcW();
var _3f=this.calcH();
var _40=this.areaCoords.x2;
var _41=this.areaCoords.y2;
var _42=this.selArea.style;
_42.left=this.areaCoords.x1+"px";
_42.top=this.areaCoords.y1+"px";
_42.width=_3e+"px";
_42.height=_3f+"px";
var _43=Math.ceil((_3e-6)/2)+"px";
var _44=Math.ceil((_3f-6)/2)+"px";
this.handleN.style.left=_43;
this.handleE.style.top=_44;
this.handleS.style.left=_43;
this.handleW.style.top=_44;
if(this.isIE){
this.north.style.height=this.areaCoords.y1+"px";
var _45=this.east.style;
_45.top=this.areaCoords.y1+"px";
_45.height=_3f+"px";
_45.left=_40+"px";
_45.width=(this.img.width-_40)+"px";
var _46=this.south.style;
_46.top=_41+"px";
_46.height=(this.img.height-_41)+"px";
var _47=this.west.style;
_47.top=this.areaCoords.y1+"px";
_47.height=_3f+"px";
_47.width=this.areaCoords.x1+"px";
}else{
_42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px";
}
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4a=["SE","S","SW"];
for(i=0;i<_4a.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
Element.show(this.selArea);
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y});
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top};
},onDrag:function(e){
var _4f=null;
if(this.dragging||this.resizing){
var _50=this.getCurPos(e);
var _51=this.cloneCoords(this.areaCoords);
var _52={x:1,y:1};
}
if(this.dragging){
if(_50.x<this.clickCoords.x){
_52.x=-1;
}
if(_50.y<this.clickCoords.y){
_52.y=-1;
}
this.transformCoords(_50.x,this.clickCoords.x,_51,"x");
this.transformCoords(_50.y,this.clickCoords.y,_51,"y");
}else{
if(this.resizing){
_4f=this.resizeHandle;
if(_4f.match(/E/)){
this.transformCoords(_50.x,this.startCoords.x1,_51,"x");
if(_50.x<this.startCoords.x1){
_52.x=-1;
}
}else{
if(_4f.match(/W/)){
this.transformCoords(_50.x,this.startCoords.x2,_51,"x");
if(_50.x<this.startCoords.x2){
_52.x=-1;
}
}
}
if(_4f.match(/N/)){
this.transformCoords(_50.y,this.startCoords.y2,_51,"y");
if(_50.y<this.startCoords.y2){
_52.y=-1;
}
}else{
if(_4f.match(/S/)){
this.transformCoords(_50.y,this.startCoords.y1,_51,"y");
if(_50.y<this.startCoords.y1){
_52.y=-1;
}
}
}
}
}
if(this.dragging||this.resizing){
this.setAreaCoords(_51,false,e.shiftKey,_52,_4f);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_53,_54,_55,_56){
var _57=new Array();
if(_53<_54){
_57[0]=_53;
_57[1]=_54;
}else{
_57[0]=_54;
_57[1]=_53;
}
if(_56=="x"){
_55.x1=_57[0];
_55.x2=_57[1];
}else{
_55.y1=_57[0];
_55.y2=_57[1];
}
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.options.displayOnInit=true;
this.hasPreviewImg=true;
Element.addClassName(this.previewWrap,"imgCrop_previewWrap");
Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _58=this.calcW();
var _59=this.calcH();
var _5a={x:this.imgW/_58,y:this.imgH/_59};
var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight};
var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"};
var _5d=this.previewImg.style;
_5d.width=_5c.w;
_5d.height=_5c.h;
_5d.left=_5c.x;
_5d.top=_5c.y;
}
}});

Binary file not shown.

After

Width:  |  Height:  |  Size: 277 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 293 B

View file

@ -0,0 +1,993 @@
/**
* @output wp-includes/js/customize-base.js
*/
/** @namespace wp */
window.wp = window.wp || {};
(function( exports, $ ){
var api = {}, ctor, inherits,
slice = Array.prototype.slice;
// Shared empty constructor function to aid in prototype-chain creation.
ctor = function() {};
/**
* Helper function to correctly set up the prototype chain, for subclasses.
* Similar to `goog.inherits`, but uses a hash of prototype properties and
* class properties to be extended.
*
* @param object parent Parent class constructor to inherit from.
* @param object protoProps Properties to apply to the prototype for use as class instance properties.
* @param object staticProps Properties to apply directly to the class constructor.
* @return child The subclassed constructor.
*/
inherits = function( parent, protoProps, staticProps ) {
var child;
/*
* The constructor function for the new subclass is either defined by you
* (the "constructor" property in your `extend` definition), or defaulted
* by us to simply call `super()`.
*/
if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) {
child = protoProps.constructor;
} else {
child = function() {
/*
* Storing the result `super()` before returning the value
* prevents a bug in Opera where, if the constructor returns
* a function, Opera will reject the return value in favor of
* the original object. This causes all sorts of trouble.
*/
var result = parent.apply( this, arguments );
return result;
};
}
// Inherit class (static) properties from parent.
$.extend( child, parent );
// Set the prototype chain to inherit from `parent`,
// without calling `parent`'s constructor function.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if ( protoProps ) {
$.extend( child.prototype, protoProps );
}
// Add static properties to the constructor function, if supplied.
if ( staticProps ) {
$.extend( child, staticProps );
}
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
};
/**
* Base class for object inheritance.
*/
api.Class = function( applicator, argsArray, options ) {
var magic, args = arguments;
if ( applicator && argsArray && api.Class.applicator === applicator ) {
args = argsArray;
$.extend( this, options || {} );
}
magic = this;
/*
* If the class has a method called "instance",
* the return value from the class' constructor will be a function that
* calls the "instance" method.
*
* It is also an object that has properties and methods inside it.
*/
if ( this.instance ) {
magic = function() {
return magic.instance.apply( magic, arguments );
};
$.extend( magic, this );
}
magic.initialize.apply( magic, args );
return magic;
};
/**
* Creates a subclass of the class.
*
* @param object protoProps Properties to apply to the prototype.
* @param object staticProps Properties to apply directly to the class.
* @return child The subclass.
*/
api.Class.extend = function( protoProps, staticProps ) {
var child = inherits( this, protoProps, staticProps );
child.extend = this.extend;
return child;
};
api.Class.applicator = {};
/**
* Initialize a class instance.
*
* Override this function in a subclass as needed.
*/
api.Class.prototype.initialize = function() {};
/*
* Checks whether a given instance extended a constructor.
*
* The magic surrounding the instance parameter causes the instanceof
* keyword to return inaccurate results; it defaults to the function's
* prototype instead of the constructor chain. Hence this function.
*/
api.Class.prototype.extended = function( constructor ) {
var proto = this;
while ( typeof proto.constructor !== 'undefined' ) {
if ( proto.constructor === constructor ) {
return true;
}
if ( typeof proto.constructor.__super__ === 'undefined' ) {
return false;
}
proto = proto.constructor.__super__;
}
return false;
};
/**
* An events manager object, offering the ability to bind to and trigger events.
*
* Used as a mixin.
*/
api.Events = {
trigger: function( id ) {
if ( this.topics && this.topics[ id ] ) {
this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
}
return this;
},
bind: function( id ) {
this.topics = this.topics || {};
this.topics[ id ] = this.topics[ id ] || $.Callbacks();
this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
return this;
},
unbind: function( id ) {
if ( this.topics && this.topics[ id ] ) {
this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
}
return this;
}
};
/**
* Observable values that support two-way binding.
*
* @memberOf wp.customize
* @alias wp.customize.Value
*
* @constructor
*/
api.Value = api.Class.extend(/** @lends wp.customize.Value.prototype */{
/**
* @param {mixed} initial The initial value.
* @param {Object} options
*/
initialize: function( initial, options ) {
this._value = initial; // @todo Potentially change this to a this.set() call.
this.callbacks = $.Callbacks();
this._dirty = false;
$.extend( this, options || {} );
this.set = this.set.bind( this );
},
/*
* Magic. Returns a function that will become the instance.
* Set to null to prevent the instance from extending a function.
*/
instance: function() {
return arguments.length ? this.set.apply( this, arguments ) : this.get();
},
/**
* Get the value.
*
* @return {mixed}
*/
get: function() {
return this._value;
},
/**
* Set the value and trigger all bound callbacks.
*
* @param {Object} to New value.
*/
set: function( to ) {
var from = this._value;
to = this._setter.apply( this, arguments );
to = this.validate( to );
// Bail if the sanitized value is null or unchanged.
if ( null === to || _.isEqual( from, to ) ) {
return this;
}
this._value = to;
this._dirty = true;
this.callbacks.fireWith( this, [ to, from ] );
return this;
},
_setter: function( to ) {
return to;
},
setter: function( callback ) {
var from = this.get();
this._setter = callback;
// Temporarily clear value so setter can decide if it's valid.
this._value = null;
this.set( from );
return this;
},
resetSetter: function() {
this._setter = this.constructor.prototype._setter;
this.set( this.get() );
return this;
},
validate: function( value ) {
return value;
},
/**
* Bind a function to be invoked whenever the value changes.
*
* @param {...Function} A function, or multiple functions, to add to the callback stack.
*/
bind: function() {
this.callbacks.add.apply( this.callbacks, arguments );
return this;
},
/**
* Unbind a previously bound function.
*
* @param {...Function} A function, or multiple functions, to remove from the callback stack.
*/
unbind: function() {
this.callbacks.remove.apply( this.callbacks, arguments );
return this;
},
link: function() { // values*
var set = this.set;
$.each( arguments, function() {
this.bind( set );
});
return this;
},
unlink: function() { // values*
var set = this.set;
$.each( arguments, function() {
this.unbind( set );
});
return this;
},
sync: function() { // values*
var that = this;
$.each( arguments, function() {
that.link( this );
this.link( that );
});
return this;
},
unsync: function() { // values*
var that = this;
$.each( arguments, function() {
that.unlink( this );
this.unlink( that );
});
return this;
}
});
/**
* A collection of observable values.
*
* @memberOf wp.customize
* @alias wp.customize.Values
*
* @constructor
* @augments wp.customize.Class
* @mixes wp.customize.Events
*/
api.Values = api.Class.extend(/** @lends wp.customize.Values.prototype */{
/**
* The default constructor for items of the collection.
*
* @type {object}
*/
defaultConstructor: api.Value,
initialize: function( options ) {
$.extend( this, options || {} );
this._value = {};
this._deferreds = {};
},
/**
* Get the instance of an item from the collection if only ID is specified.
*
* If more than one argument is supplied, all are expected to be IDs and
* the last to be a function callback that will be invoked when the requested
* items are available.
*
* @see {api.Values.when}
*
* @param {string} id ID of the item.
* @param {...} Zero or more IDs of items to wait for and a callback
* function to invoke when they're available. Optional.
* @return {mixed} The item instance if only one ID was supplied.
* A Deferred Promise object if a callback function is supplied.
*/
instance: function( id ) {
if ( arguments.length === 1 ) {
return this.value( id );
}
return this.when.apply( this, arguments );
},
/**
* Get the instance of an item.
*
* @param {string} id The ID of the item.
* @return {[type]} [description]
*/
value: function( id ) {
return this._value[ id ];
},
/**
* Whether the collection has an item with the given ID.
*
* @param {string} id The ID of the item to look for.
* @return {boolean}
*/
has: function( id ) {
return typeof this._value[ id ] !== 'undefined';
},
/**
* Add an item to the collection.
*
* @param {string|wp.customize.Class} item - The item instance to add, or the ID for the instance to add. When an ID string is supplied, then itemObject must be provided.
* @param {wp.customize.Class} [itemObject] - The item instance when the first argument is a ID string.
* @return {wp.customize.Class} The new item's instance, or an existing instance if already added.
*/
add: function( item, itemObject ) {
var collection = this, id, instance;
if ( 'string' === typeof item ) {
id = item;
instance = itemObject;
} else {
if ( 'string' !== typeof item.id ) {
throw new Error( 'Unknown key' );
}
id = item.id;
instance = item;
}
if ( collection.has( id ) ) {
return collection.value( id );
}
collection._value[ id ] = instance;
instance.parent = collection;
// Propagate a 'change' event on an item up to the collection.
if ( instance.extended( api.Value ) ) {
instance.bind( collection._change );
}
collection.trigger( 'add', instance );
// If a deferred object exists for this item,
// resolve it.
if ( collection._deferreds[ id ] ) {
collection._deferreds[ id ].resolve();
}
return collection._value[ id ];
},
/**
* Create a new item of the collection using the collection's default constructor
* and store it in the collection.
*
* @param {string} id The ID of the item.
* @param {mixed} value Any extra arguments are passed into the item's initialize method.
* @return {mixed} The new item's instance.
*/
create: function( id ) {
return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
},
/**
* Iterate over all items in the collection invoking the provided callback.
*
* @param {Function} callback Function to invoke.
* @param {Object} context Object context to invoke the function with. Optional.
*/
each: function( callback, context ) {
context = typeof context === 'undefined' ? this : context;
$.each( this._value, function( key, obj ) {
callback.call( context, obj, key );
});
},
/**
* Remove an item from the collection.
*
* @param {string} id The ID of the item to remove.
*/
remove: function( id ) {
var value = this.value( id );
if ( value ) {
// Trigger event right before the element is removed from the collection.
this.trigger( 'remove', value );
if ( value.extended( api.Value ) ) {
value.unbind( this._change );
}
delete value.parent;
}
delete this._value[ id ];
delete this._deferreds[ id ];
// Trigger removed event after the item has been eliminated from the collection.
if ( value ) {
this.trigger( 'removed', value );
}
},
/**
* Runs a callback once all requested values exist.
*
* when( ids*, [callback] );
*
* For example:
* when( id1, id2, id3, function( value1, value2, value3 ) {} );
*
* @return $.Deferred.promise();
*/
when: function() {
var self = this,
ids = slice.call( arguments ),
dfd = $.Deferred();
// If the last argument is a callback, bind it to .done().
if ( typeof ids[ ids.length - 1 ] === 'function' ) {
dfd.done( ids.pop() );
}
/*
* Create a stack of deferred objects for each item that is not
* yet available, and invoke the supplied callback when they are.
*/
$.when.apply( $, $.map( ids, function( id ) {
if ( self.has( id ) ) {
return;
}
/*
* The requested item is not available yet, create a deferred
* object to resolve when it becomes available.
*/
return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
})).done( function() {
var values = $.map( ids, function( id ) {
return self( id );
});
// If a value is missing, we've used at least one expired deferred.
// Call Values.when again to generate a new deferred.
if ( values.length !== ids.length ) {
// ids.push( callback );
self.when.apply( self, ids ).done( function() {
dfd.resolveWith( self, values );
});
return;
}
dfd.resolveWith( self, values );
});
return dfd.promise();
},
/**
* A helper function to propagate a 'change' event from an item
* to the collection itself.
*/
_change: function() {
this.parent.trigger( 'change', this );
}
});
// Create a global events bus on the Customizer.
$.extend( api.Values.prototype, api.Events );
/**
* Cast a string to a jQuery collection if it isn't already.
*
* @param {string|jQuery collection} element
*/
api.ensure = function( element ) {
return typeof element === 'string' ? $( element ) : element;
};
/**
* An observable value that syncs with an element.
*
* Handles inputs, selects, and textareas by default.
*
* @memberOf wp.customize
* @alias wp.customize.Element
*
* @constructor
* @augments wp.customize.Value
* @augments wp.customize.Class
*/
api.Element = api.Value.extend(/** @lends wp.customize.Element */{
initialize: function( element, options ) {
var self = this,
synchronizer = api.Element.synchronizer.html,
type, update, refresh;
this.element = api.ensure( element );
this.events = '';
if ( this.element.is( 'input, select, textarea' ) ) {
type = this.element.prop( 'type' );
this.events += ' change input';
synchronizer = api.Element.synchronizer.val;
if ( this.element.is( 'input' ) && api.Element.synchronizer[ type ] ) {
synchronizer = api.Element.synchronizer[ type ];
}
}
api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
this._value = this.get();
update = this.update;
refresh = this.refresh;
this.update = function( to ) {
if ( to !== refresh.call( self ) ) {
update.apply( this, arguments );
}
};
this.refresh = function() {
self.set( refresh.call( self ) );
};
this.bind( this.update );
this.element.on( this.events, this.refresh );
},
find: function( selector ) {
return $( selector, this.element );
},
refresh: function() {},
update: function() {}
});
api.Element.synchronizer = {};
$.each( [ 'html', 'val' ], function( index, method ) {
api.Element.synchronizer[ method ] = {
update: function( to ) {
this.element[ method ]( to );
},
refresh: function() {
return this.element[ method ]();
}
};
});
api.Element.synchronizer.checkbox = {
update: function( to ) {
this.element.prop( 'checked', to );
},
refresh: function() {
return this.element.prop( 'checked' );
}
};
api.Element.synchronizer.radio = {
update: function( to ) {
this.element.filter( function() {
return this.value === to;
}).prop( 'checked', true );
},
refresh: function() {
return this.element.filter( ':checked' ).val();
}
};
$.support.postMessage = !! window.postMessage;
/**
* A communicator for sending data from one window to another over postMessage.
*
* @memberOf wp.customize
* @alias wp.customize.Messenger
*
* @constructor
* @augments wp.customize.Class
* @mixes wp.customize.Events
*/
api.Messenger = api.Class.extend(/** @lends wp.customize.Messenger.prototype */{
/**
* Create a new Value.
*
* @param {string} key Unique identifier.
* @param {mixed} initial Initial value.
* @param {mixed} options Options hash. Optional.
* @return {Value} Class instance of the Value.
*/
add: function( key, initial, options ) {
return this[ key ] = new api.Value( initial, options );
},
/**
* Initialize Messenger.
*
* @param {Object} params - Parameters to configure the messenger.
* {string} params.url - The URL to communicate with.
* {window} params.targetWindow - The window instance to communicate with. Default window.parent.
* {string} params.channel - If provided, will send the channel with each message and only accept messages a matching channel.
* @param {Object} options - Extend any instance parameter or method with this object.
*/
initialize: function( params, options ) {
// Target the parent frame by default, but only if a parent frame exists.
var defaultTarget = window.parent === window ? null : window.parent;
$.extend( this, options || {} );
this.add( 'channel', params.channel );
this.add( 'url', params.url || '' );
this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
var urlParser = document.createElement( 'a' );
urlParser.href = to;
// Port stripping needed by IE since it adds to host but not to event.origin.
return urlParser.protocol + '//' + urlParser.host.replace( /:(80|443)$/, '' );
});
// First add with no value.
this.add( 'targetWindow', null );
// This avoids SecurityErrors when setting a window object in x-origin iframe'd scenarios.
this.targetWindow.set = function( to ) {
var from = this._value;
to = this._setter.apply( this, arguments );
to = this.validate( to );
if ( null === to || from === to ) {
return this;
}
this._value = to;
this._dirty = true;
this.callbacks.fireWith( this, [ to, from ] );
return this;
};
// Now set it.
this.targetWindow( params.targetWindow || defaultTarget );
/*
* Since we want jQuery to treat the receive function as unique
* to this instance, we give the function a new guid.
*
* This will prevent every Messenger's receive function from being
* unbound when calling $.off( 'message', this.receive );
*/
this.receive = this.receive.bind( this );
this.receive.guid = $.guid++;
$( window ).on( 'message', this.receive );
},
destroy: function() {
$( window ).off( 'message', this.receive );
},
/**
* Receive data from the other window.
*
* @param {jQuery.Event} event Event with embedded data.
*/
receive: function( event ) {
var message;
event = event.originalEvent;
if ( ! this.targetWindow || ! this.targetWindow() ) {
return;
}
// Check to make sure the origin is valid.
if ( this.origin() && event.origin !== this.origin() ) {
return;
}
// Ensure we have a string that's JSON.parse-able.
if ( typeof event.data !== 'string' || event.data[0] !== '{' ) {
return;
}
message = JSON.parse( event.data );
// Check required message properties.
if ( ! message || ! message.id || typeof message.data === 'undefined' ) {
return;
}
// Check if channel names match.
if ( ( message.channel || this.channel() ) && this.channel() !== message.channel ) {
return;
}
this.trigger( message.id, message.data );
},
/**
* Send data to the other window.
*
* @param {string} id The event name.
* @param {Object} data Data.
*/
send: function( id, data ) {
var message;
data = typeof data === 'undefined' ? null : data;
if ( ! this.url() || ! this.targetWindow() ) {
return;
}
message = { id: id, data: data };
if ( this.channel() ) {
message.channel = this.channel();
}
this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
}
});
// Add the Events mixin to api.Messenger.
$.extend( api.Messenger.prototype, api.Events );
/**
* Notification.
*
* @class
* @augments wp.customize.Class
* @since 4.6.0
*
* @memberOf wp.customize
* @alias wp.customize.Notification
*
* @param {string} code - The error code.
* @param {object} params - Params.
* @param {string} params.message=null - The error message.
* @param {string} [params.type=error] - The notification type.
* @param {boolean} [params.fromServer=false] - Whether the notification was server-sent.
* @param {string} [params.setting=null] - The setting ID that the notification is related to.
* @param {*} [params.data=null] - Any additional data.
*/
api.Notification = api.Class.extend(/** @lends wp.customize.Notification.prototype */{
/**
* Template function for rendering the notification.
*
* This will be populated with template option or else it will be populated with template from the ID.
*
* @since 4.9.0
* @var {Function}
*/
template: null,
/**
* ID for the template to render the notification.
*
* @since 4.9.0
* @var {string}
*/
templateId: 'customize-notification',
/**
* Additional class names to add to the notification container.
*
* @since 4.9.0
* @var {string}
*/
containerClasses: '',
/**
* Initialize notification.
*
* @since 4.9.0
*
* @param {string} code - Notification code.
* @param {Object} params - Notification parameters.
* @param {string} params.message - Message.
* @param {string} [params.type=error] - Type.
* @param {string} [params.setting] - Related setting ID.
* @param {Function} [params.template] - Function for rendering template. If not provided, this will come from templateId.
* @param {string} [params.templateId] - ID for template to render the notification.
* @param {string} [params.containerClasses] - Additional class names to add to the notification container.
* @param {boolean} [params.dismissible] - Whether the notification can be dismissed.
*/
initialize: function( code, params ) {
var _params;
this.code = code;
_params = _.extend(
{
message: null,
type: 'error',
fromServer: false,
data: null,
setting: null,
template: null,
dismissible: false,
containerClasses: ''
},
params
);
delete _params.code;
_.extend( this, _params );
},
/**
* Render the notification.
*
* @since 4.9.0
*
* @return {jQuery} Notification container element.
*/
render: function() {
var notification = this, container, data;
if ( ! notification.template ) {
notification.template = wp.template( notification.templateId );
}
data = _.extend( {}, notification, {
alt: notification.parent && notification.parent.alt
} );
container = $( notification.template( data ) );
if ( notification.dismissible ) {
container.find( '.notice-dismiss' ).on( 'click keydown', function( event ) {
if ( 'keydown' === event.type && 13 !== event.which ) {
return;
}
if ( notification.parent ) {
notification.parent.remove( notification.code );
} else {
container.remove();
}
});
}
return container;
}
});
// The main API object is also a collection of all customizer settings.
api = $.extend( new api.Values(), api );
/**
* Get all customize settings.
*
* @alias wp.customize.get
*
* @return {Object}
*/
api.get = function() {
var result = {};
this.each( function( obj, key ) {
result[ key ] = obj.get();
});
return result;
};
/**
* Utility function namespace
*
* @namespace wp.customize.utils
*/
api.utils = {};
/**
* Parse query string.
*
* @since 4.7.0
* @access public
*
* @alias wp.customize.utils.parseQueryString
*
* @param {string} queryString Query string.
* @return {Object} Parsed query string.
*/
api.utils.parseQueryString = function parseQueryString( queryString ) {
var queryParams = {};
_.each( queryString.split( '&' ), function( pair ) {
var parts, key, value;
parts = pair.split( '=', 2 );
if ( ! parts[0] ) {
return;
}
key = decodeURIComponent( parts[0].replace( /\+/g, ' ' ) );
key = key.replace( / /g, '_' ); // What PHP does.
if ( _.isUndefined( parts[1] ) ) {
value = null;
} else {
value = decodeURIComponent( parts[1].replace( /\+/g, ' ' ) );
}
queryParams[ key ] = value;
} );
return queryParams;
};
/**
* Expose the API publicly on window.wp.customize
*
* @namespace wp.customize
*/
exports.customize = api;
})( wp, jQuery );

2
wp-includes/js/customize-base.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,291 @@
/**
* @output wp-includes/js/customize-loader.js
*/
/* global _wpCustomizeLoaderSettings */
/**
* Expose a public API that allows the customizer to be
* loaded on any page.
*
* @namespace wp
*/
window.wp = window.wp || {};
(function( exports, $ ){
var api = wp.customize,
Loader;
$.extend( $.support, {
history: !! ( window.history && history.pushState ),
hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7)
});
/**
* Allows the Customizer to be overlayed on any page.
*
* By default, any element in the body with the load-customize class will open
* an iframe overlay with the URL specified.
*
* e.g. <a class="load-customize" href="<?php echo wp_customize_url(); ?>">Open Customizer</a>
*
* @memberOf wp.customize
*
* @class
* @augments wp.customize.Events
*/
Loader = $.extend( {}, api.Events,/** @lends wp.customize.Loader.prototype */{
/**
* Setup the Loader; triggered on document#ready.
*/
initialize: function() {
this.body = $( document.body );
// Ensure the loader is supported.
// Check for settings, postMessage support, and whether we require CORS support.
if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) {
return;
}
this.window = $( window );
this.element = $( '<div id="customize-container" />' ).appendTo( this.body );
// Bind events for opening and closing the overlay.
this.bind( 'open', this.overlay.show );
this.bind( 'close', this.overlay.hide );
// Any element in the body with the `load-customize` class opens
// the Customizer.
$('#wpbody').on( 'click', '.load-customize', function( event ) {
event.preventDefault();
// Store a reference to the link that opened the Customizer.
Loader.link = $(this);
// Load the theme.
Loader.open( Loader.link.attr('href') );
});
// Add navigation listeners.
if ( $.support.history ) {
this.window.on( 'popstate', Loader.popstate );
}
if ( $.support.hashchange ) {
this.window.on( 'hashchange', Loader.hashchange );
this.window.triggerHandler( 'hashchange' );
}
},
popstate: function( e ) {
var state = e.originalEvent.state;
if ( state && state.customize ) {
Loader.open( state.customize );
} else if ( Loader.active ) {
Loader.close();
}
},
hashchange: function() {
var hash = window.location.toString().split('#')[1];
if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) ) {
Loader.open( Loader.settings.url + '?' + hash );
}
if ( ! hash && ! $.support.history ) {
Loader.close();
}
},
beforeunload: function () {
if ( ! Loader.saved() ) {
return Loader.settings.l10n.saveAlert;
}
},
/**
* Open the Customizer overlay for a specific URL.
*
* @param string src URL to load in the Customizer.
*/
open: function( src ) {
if ( this.active ) {
return;
}
// Load the full page on mobile devices.
if ( Loader.settings.browser.mobile ) {
return window.location = src;
}
// Store the document title prior to opening the Live Preview.
this.originalDocumentTitle = document.title;
this.active = true;
this.body.addClass('customize-loading');
/*
* Track the dirtiness state (whether the drafted changes have been published)
* of the Customizer in the iframe. This is used to decide whether to display
* an AYS alert if the user tries to close the window before saving changes.
*/
this.saved = new api.Value( true );
this.iframe = $( '<iframe />', { 'src': src, 'title': Loader.settings.l10n.mainIframeTitle } ).appendTo( this.element );
this.iframe.one( 'load', this.loaded );
// Create a postMessage connection with the iframe.
this.messenger = new api.Messenger({
url: src,
channel: 'loader',
targetWindow: this.iframe[0].contentWindow
});
// Expose the changeset UUID on the parent window's URL so that the customized state can survive a refresh.
if ( history.replaceState ) {
this.messenger.bind( 'changeset-uuid', function( changesetUuid ) {
var urlParser = document.createElement( 'a' );
urlParser.href = location.href;
urlParser.search = $.param( _.extend(
api.utils.parseQueryString( urlParser.search.substr( 1 ) ),
{ changeset_uuid: changesetUuid }
) );
history.replaceState( { customize: urlParser.href }, '', urlParser.href );
} );
}
// Wait for the connection from the iframe before sending any postMessage events.
this.messenger.bind( 'ready', function() {
Loader.messenger.send( 'back' );
});
this.messenger.bind( 'close', function() {
if ( $.support.history ) {
history.back();
} else if ( $.support.hashchange ) {
window.location.hash = '';
} else {
Loader.close();
}
});
// Prompt AYS dialog when navigating away.
$( window ).on( 'beforeunload', this.beforeunload );
this.messenger.bind( 'saved', function () {
Loader.saved( true );
} );
this.messenger.bind( 'change', function () {
Loader.saved( false );
} );
this.messenger.bind( 'title', function( newTitle ){
window.document.title = newTitle;
});
this.pushState( src );
this.trigger( 'open' );
},
pushState: function ( src ) {
var hash = src.split( '?' )[1];
// Ensure we don't call pushState if the user hit the forward button.
if ( $.support.history && window.location.href !== src ) {
history.pushState( { customize: src }, '', src );
} else if ( ! $.support.history && $.support.hashchange && hash ) {
window.location.hash = 'wp_customize=on&' + hash;
}
this.trigger( 'open' );
},
/**
* Callback after the Customizer has been opened.
*/
opened: function() {
Loader.body.addClass( 'customize-active full-overlay-active' ).attr( 'aria-busy', 'true' );
},
/**
* Close the Customizer overlay.
*/
close: function() {
var self = this, onConfirmClose;
if ( ! self.active ) {
return;
}
onConfirmClose = function( confirmed ) {
if ( confirmed ) {
self.active = false;
self.trigger( 'close' );
// Restore document title prior to opening the Live Preview.
if ( self.originalDocumentTitle ) {
document.title = self.originalDocumentTitle;
}
} else {
// Go forward since Customizer is exited by history.back().
history.forward();
}
self.messenger.unbind( 'confirmed-close', onConfirmClose );
};
self.messenger.bind( 'confirmed-close', onConfirmClose );
Loader.messenger.send( 'confirm-close' );
},
/**
* Callback after the Customizer has been closed.
*/
closed: function() {
Loader.iframe.remove();
Loader.messenger.destroy();
Loader.iframe = null;
Loader.messenger = null;
Loader.saved = null;
Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' );
$( window ).off( 'beforeunload', Loader.beforeunload );
/*
* Return focus to the link that opened the Customizer overlay after
* the body element visibility is restored.
*/
if ( Loader.link ) {
Loader.link.focus();
}
},
/**
* Callback for the `load` event on the Customizer iframe.
*/
loaded: function() {
Loader.body.removeClass( 'customize-loading' ).attr( 'aria-busy', 'false' );
},
/**
* Overlay hide/show utility methods.
*/
overlay: {
show: function() {
this.element.fadeIn( 200, Loader.opened );
},
hide: function() {
this.element.fadeOut( 200, Loader.closed );
}
}
});
// Bootstrap the Loader on document#ready.
$( function() {
Loader.settings = _wpCustomizeLoaderSettings;
Loader.initialize();
});
// Expose the API publicly on window.wp.customize.Loader.
api.Loader = Loader;
})( wp, jQuery );

View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
window.wp=window.wp||{},function(i){var n,o=wp.customize;i.extend(i.support,{history:!(!window.history||!history.pushState),hashchange:"onhashchange"in window&&(void 0===document.documentMode||7<document.documentMode)}),n=i.extend({},o.Events,{initialize:function(){this.body=i(document.body),n.settings&&i.support.postMessage&&(i.support.cors||!n.settings.isCrossDomain)&&(this.window=i(window),this.element=i('<div id="customize-container" />').appendTo(this.body),this.bind("open",this.overlay.show),this.bind("close",this.overlay.hide),i("#wpbody").on("click",".load-customize",function(e){e.preventDefault(),n.link=i(this),n.open(n.link.attr("href"))}),i.support.history&&this.window.on("popstate",n.popstate),i.support.hashchange&&(this.window.on("hashchange",n.hashchange),this.window.triggerHandler("hashchange")))},popstate:function(e){e=e.originalEvent.state;e&&e.customize?n.open(e.customize):n.active&&n.close()},hashchange:function(){var e=window.location.toString().split("#")[1];e&&0===e.indexOf("wp_customize=on")&&n.open(n.settings.url+"?"+e),e||i.support.history||n.close()},beforeunload:function(){if(!n.saved())return n.settings.l10n.saveAlert},open:function(e){if(!this.active){if(n.settings.browser.mobile)return window.location=e;this.originalDocumentTitle=document.title,this.active=!0,this.body.addClass("customize-loading"),this.saved=new o.Value(!0),this.iframe=i("<iframe />",{src:e,title:n.settings.l10n.mainIframeTitle}).appendTo(this.element),this.iframe.one("load",this.loaded),this.messenger=new o.Messenger({url:e,channel:"loader",targetWindow:this.iframe[0].contentWindow}),history.replaceState&&this.messenger.bind("changeset-uuid",function(e){var t=document.createElement("a");t.href=location.href,t.search=i.param(_.extend(o.utils.parseQueryString(t.search.substr(1)),{changeset_uuid:e})),history.replaceState({customize:t.href},"",t.href)}),this.messenger.bind("ready",function(){n.messenger.send("back")}),this.messenger.bind("close",function(){i.support.history?history.back():i.support.hashchange?window.location.hash="":n.close()}),i(window).on("beforeunload",this.beforeunload),this.messenger.bind("saved",function(){n.saved(!0)}),this.messenger.bind("change",function(){n.saved(!1)}),this.messenger.bind("title",function(e){window.document.title=e}),this.pushState(e),this.trigger("open")}},pushState:function(e){var t=e.split("?")[1];i.support.history&&window.location.href!==e?history.pushState({customize:e},"",e):!i.support.history&&i.support.hashchange&&t&&(window.location.hash="wp_customize=on&"+t),this.trigger("open")},opened:function(){n.body.addClass("customize-active full-overlay-active").attr("aria-busy","true")},close:function(){var t,i=this;i.active&&(t=function(e){e?(i.active=!1,i.trigger("close"),i.originalDocumentTitle&&(document.title=i.originalDocumentTitle)):history.forward(),i.messenger.unbind("confirmed-close",t)},i.messenger.bind("confirmed-close",t),n.messenger.send("confirm-close"))},closed:function(){n.iframe.remove(),n.messenger.destroy(),n.iframe=null,n.messenger=null,n.saved=null,n.body.removeClass("customize-active full-overlay-active").removeClass("customize-loading"),i(window).off("beforeunload",n.beforeunload),n.link&&n.link.focus()},loaded:function(){n.body.removeClass("customize-loading").attr("aria-busy","false")},overlay:{show:function(){this.element.fadeIn(200,n.opened)},hide:function(){this.element.fadeOut(200,n.closed)}}}),i(function(){n.settings=_wpCustomizeLoaderSettings,n.initialize()}),o.Loader=n}((wp,jQuery));

View file

@ -0,0 +1,281 @@
/**
* @output wp-includes/js/customize-models.js
*/
/* global _wpCustomizeHeader */
(function( $, wp ) {
var api = wp.customize;
/** @namespace wp.customize.HeaderTool */
api.HeaderTool = {};
/**
* wp.customize.HeaderTool.ImageModel
*
* A header image. This is where saves via the Customizer API are
* abstracted away, plus our own Ajax calls to add images to and remove
* images from the user's recently uploaded images setting on the server.
* These calls are made regardless of whether the user actually saves new
* Customizer settings.
*
* @memberOf wp.customize.HeaderTool
* @alias wp.customize.HeaderTool.ImageModel
*
* @constructor
* @augments Backbone.Model
*/
api.HeaderTool.ImageModel = Backbone.Model.extend(/** @lends wp.customize.HeaderTool.ImageModel.prototype */{
defaults: function() {
return {
header: {
attachment_id: 0,
url: '',
timestamp: _.now(),
thumbnail_url: ''
},
choice: '',
selected: false,
random: false
};
},
initialize: function() {
this.on('hide', this.hide, this);
},
hide: function() {
this.set('choice', '');
api('header_image').set('remove-header');
api('header_image_data').set('remove-header');
},
destroy: function() {
var data = this.get('header'),
curr = api.HeaderTool.currentHeader.get('header').attachment_id;
// If the image we're removing is also the current header,
// unset the latter.
if (curr && data.attachment_id === curr) {
api.HeaderTool.currentHeader.trigger('hide');
}
wp.ajax.post( 'custom-header-remove', {
nonce: _wpCustomizeHeader.nonces.remove,
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
attachment_id: data.attachment_id
});
this.trigger('destroy', this, this.collection);
},
save: function() {
if (this.get('random')) {
api('header_image').set(this.get('header').random);
api('header_image_data').set(this.get('header').random);
} else {
if (this.get('header').defaultName) {
api('header_image').set(this.get('header').url);
api('header_image_data').set(this.get('header').defaultName);
} else {
api('header_image').set(this.get('header').url);
api('header_image_data').set(this.get('header'));
}
}
api.HeaderTool.combinedList.trigger('control:setImage', this);
},
importImage: function() {
var data = this.get('header');
if (data.attachment_id === undefined) {
return;
}
wp.ajax.post( 'custom-header-add', {
nonce: _wpCustomizeHeader.nonces.add,
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
attachment_id: data.attachment_id
} );
},
shouldBeCropped: function() {
if (this.get('themeFlexWidth') === true &&
this.get('themeFlexHeight') === true) {
return false;
}
if (this.get('themeFlexWidth') === true &&
this.get('themeHeight') === this.get('imageHeight')) {
return false;
}
if (this.get('themeFlexHeight') === true &&
this.get('themeWidth') === this.get('imageWidth')) {
return false;
}
if (this.get('themeWidth') === this.get('imageWidth') &&
this.get('themeHeight') === this.get('imageHeight')) {
return false;
}
if (this.get('imageWidth') <= this.get('themeWidth')) {
return false;
}
return true;
}
});
/**
* wp.customize.HeaderTool.ChoiceList
*
* @memberOf wp.customize.HeaderTool
* @alias wp.customize.HeaderTool.ChoiceList
*
* @constructor
* @augments Backbone.Collection
*/
api.HeaderTool.ChoiceList = Backbone.Collection.extend({
model: api.HeaderTool.ImageModel,
// Ordered from most recently used to least.
comparator: function(model) {
return -model.get('header').timestamp;
},
initialize: function() {
var current = api.HeaderTool.currentHeader.get('choice').replace(/^https?:\/\//, ''),
isRandom = this.isRandomChoice(api.get().header_image);
// Overridable by an extending class.
if (!this.type) {
this.type = 'uploaded';
}
// Overridable by an extending class.
if (typeof this.data === 'undefined') {
this.data = _wpCustomizeHeader.uploads;
}
if (isRandom) {
// So that when adding data we don't hide regular images.
current = api.get().header_image;
}
this.on('control:setImage', this.setImage, this);
this.on('control:removeImage', this.removeImage, this);
this.on('add', this.maybeRemoveOldCrop, this);
this.on('add', this.maybeAddRandomChoice, this);
_.each(this.data, function(elt, index) {
if (!elt.attachment_id) {
elt.defaultName = index;
}
if (typeof elt.timestamp === 'undefined') {
elt.timestamp = 0;
}
this.add({
header: elt,
choice: elt.url.split('/').pop(),
selected: current === elt.url.replace(/^https?:\/\//, '')
}, { silent: true });
}, this);
if (this.size() > 0) {
this.addRandomChoice(current);
}
},
maybeRemoveOldCrop: function( model ) {
var newID = model.get( 'header' ).attachment_id || false,
oldCrop;
// Bail early if we don't have a new attachment ID.
if ( ! newID ) {
return;
}
oldCrop = this.find( function( item ) {
return ( item.cid !== model.cid && item.get( 'header' ).attachment_id === newID );
} );
// If we found an old crop, remove it from the collection.
if ( oldCrop ) {
this.remove( oldCrop );
}
},
maybeAddRandomChoice: function() {
if (this.size() === 1) {
this.addRandomChoice();
}
},
addRandomChoice: function(initialChoice) {
var isRandomSameType = RegExp(this.type).test(initialChoice),
randomChoice = 'random-' + this.type + '-image';
this.add({
header: {
timestamp: 0,
random: randomChoice,
width: 245,
height: 41
},
choice: randomChoice,
random: true,
selected: isRandomSameType
});
},
isRandomChoice: function(choice) {
return (/^random-(uploaded|default)-image$/).test(choice);
},
shouldHideTitle: function() {
return this.size() < 2;
},
setImage: function(model) {
this.each(function(m) {
m.set('selected', false);
});
if (model) {
model.set('selected', true);
}
},
removeImage: function() {
this.each(function(m) {
m.set('selected', false);
});
}
});
/**
* wp.customize.HeaderTool.DefaultsList
*
* @memberOf wp.customize.HeaderTool
* @alias wp.customize.HeaderTool.DefaultsList
*
* @constructor
* @augments wp.customize.HeaderTool.ChoiceList
* @augments Backbone.Collection
*/
api.HeaderTool.DefaultsList = api.HeaderTool.ChoiceList.extend({
initialize: function() {
this.type = 'default';
this.data = _wpCustomizeHeader.defaults;
api.HeaderTool.ChoiceList.prototype.initialize.apply(this);
}
});
})( jQuery, window.wp );

View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
!function(e,i){var a=i.customize;a.HeaderTool={},a.HeaderTool.ImageModel=Backbone.Model.extend({defaults:function(){return{header:{attachment_id:0,url:"",timestamp:_.now(),thumbnail_url:""},choice:"",selected:!1,random:!1}},initialize:function(){this.on("hide",this.hide,this)},hide:function(){this.set("choice",""),a("header_image").set("remove-header"),a("header_image_data").set("remove-header")},destroy:function(){var e=this.get("header"),t=a.HeaderTool.currentHeader.get("header").attachment_id;t&&e.attachment_id===t&&a.HeaderTool.currentHeader.trigger("hide"),i.ajax.post("custom-header-remove",{nonce:_wpCustomizeHeader.nonces.remove,wp_customize:"on",theme:a.settings.theme.stylesheet,attachment_id:e.attachment_id}),this.trigger("destroy",this,this.collection)},save:function(){this.get("random")?(a("header_image").set(this.get("header").random),a("header_image_data").set(this.get("header").random)):this.get("header").defaultName?(a("header_image").set(this.get("header").url),a("header_image_data").set(this.get("header").defaultName)):(a("header_image").set(this.get("header").url),a("header_image_data").set(this.get("header"))),a.HeaderTool.combinedList.trigger("control:setImage",this)},importImage:function(){var e=this.get("header");void 0!==e.attachment_id&&i.ajax.post("custom-header-add",{nonce:_wpCustomizeHeader.nonces.add,wp_customize:"on",theme:a.settings.theme.stylesheet,attachment_id:e.attachment_id})},shouldBeCropped:function(){return(!0!==this.get("themeFlexWidth")||!0!==this.get("themeFlexHeight"))&&((!0!==this.get("themeFlexWidth")||this.get("themeHeight")!==this.get("imageHeight"))&&((!0!==this.get("themeFlexHeight")||this.get("themeWidth")!==this.get("imageWidth"))&&((this.get("themeWidth")!==this.get("imageWidth")||this.get("themeHeight")!==this.get("imageHeight"))&&!(this.get("imageWidth")<=this.get("themeWidth")))))}}),a.HeaderTool.ChoiceList=Backbone.Collection.extend({model:a.HeaderTool.ImageModel,comparator:function(e){return-e.get("header").timestamp},initialize:function(){var i=a.HeaderTool.currentHeader.get("choice").replace(/^https?:\/\//,""),e=this.isRandomChoice(a.get().header_image);this.type||(this.type="uploaded"),void 0===this.data&&(this.data=_wpCustomizeHeader.uploads),e&&(i=a.get().header_image),this.on("control:setImage",this.setImage,this),this.on("control:removeImage",this.removeImage,this),this.on("add",this.maybeRemoveOldCrop,this),this.on("add",this.maybeAddRandomChoice,this),_.each(this.data,function(e,t){e.attachment_id||(e.defaultName=t),void 0===e.timestamp&&(e.timestamp=0),this.add({header:e,choice:e.url.split("/").pop(),selected:i===e.url.replace(/^https?:\/\//,"")},{silent:!0})},this),0<this.size()&&this.addRandomChoice(i)},maybeRemoveOldCrop:function(t){var e,i=t.get("header").attachment_id||!1;i&&(e=this.find(function(e){return e.cid!==t.cid&&e.get("header").attachment_id===i}))&&this.remove(e)},maybeAddRandomChoice:function(){1===this.size()&&this.addRandomChoice()},addRandomChoice:function(e){var t=RegExp(this.type).test(e),i="random-"+this.type+"-image";this.add({header:{timestamp:0,random:i,width:245,height:41},choice:i,random:!0,selected:t})},isRandomChoice:function(e){return/^random-(uploaded|default)-image$/.test(e)},shouldHideTitle:function(){return this.size()<2},setImage:function(e){this.each(function(e){e.set("selected",!1)}),e&&e.set("selected",!0)},removeImage:function(){this.each(function(e){e.set("selected",!1)})}}),a.HeaderTool.DefaultsList=a.HeaderTool.ChoiceList.extend({initialize:function(){this.type="default",this.data=_wpCustomizeHeader.defaults,a.HeaderTool.ChoiceList.prototype.initialize.apply(this)}})}(jQuery,window.wp);

View file

@ -0,0 +1,446 @@
/**
* @output wp-includes/js/customize-preview-nav-menus.js
*/
/* global _wpCustomizePreviewNavMenusExports */
/** @namespace wp.customize.navMenusPreview */
wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function( $, _, wp, api ) {
'use strict';
var self = {
data: {
navMenuInstanceArgs: {}
}
};
if ( 'undefined' !== typeof _wpCustomizePreviewNavMenusExports ) {
_.extend( self.data, _wpCustomizePreviewNavMenusExports );
}
/**
* Initialize nav menus preview.
*/
self.init = function() {
var self = this, synced = false;
/*
* Keep track of whether we synced to determine whether or not bindSettingListener
* should also initially fire the listener. This initial firing needs to wait until
* after all of the settings have been synced from the pane in order to prevent
* an infinite selective fallback-refresh. Note that this sync handler will be
* added after the sync handler in customize-preview.js, so it will be triggered
* after all of the settings are added.
*/
api.preview.bind( 'sync', function() {
synced = true;
} );
if ( api.selectiveRefresh ) {
// Listen for changes to settings related to nav menus.
api.each( function( setting ) {
self.bindSettingListener( setting );
} );
api.bind( 'add', function( setting ) {
/*
* Handle case where an invalid nav menu item (one for which its associated object has been deleted)
* is synced from the controls into the preview. Since invalid nav menu items are filtered out from
* being exported to the frontend by the _is_valid_nav_menu_item filter in wp_get_nav_menu_items(),
* the customizer controls will have a nav_menu_item setting where the preview will have none, and
* this can trigger an infinite fallback refresh when the nav menu item lacks any valid items.
*/
if ( setting.get() && ! setting.get()._invalid ) {
self.bindSettingListener( setting, { fire: synced } );
}
} );
api.bind( 'remove', function( setting ) {
self.unbindSettingListener( setting );
} );
/*
* Ensure that wp_nav_menu() instances nested inside of other partials
* will be recognized as being present on the page.
*/
api.selectiveRefresh.bind( 'render-partials-response', function( response ) {
if ( response.nav_menu_instance_args ) {
_.extend( self.data.navMenuInstanceArgs, response.nav_menu_instance_args );
}
} );
}
api.preview.bind( 'active', function() {
self.highlightControls();
} );
};
if ( api.selectiveRefresh ) {
/**
* Partial representing an invocation of wp_nav_menu().
*
* @memberOf wp.customize.navMenusPreview
* @alias wp.customize.navMenusPreview.NavMenuInstancePartial
*
* @class
* @augments wp.customize.selectiveRefresh.Partial
* @since 4.5.0
*/
self.NavMenuInstancePartial = api.selectiveRefresh.Partial.extend(/** @lends wp.customize.navMenusPreview.NavMenuInstancePartial.prototype */{
/**
* Constructor.
*
* @since 4.5.0
* @param {string} id - Partial ID.
* @param {Object} options
* @param {Object} options.params
* @param {Object} options.params.navMenuArgs
* @param {string} options.params.navMenuArgs.args_hmac
* @param {string} [options.params.navMenuArgs.theme_location]
* @param {number} [options.params.navMenuArgs.menu]
* @param {Object} [options.constructingContainerContext]
*/
initialize: function( id, options ) {
var partial = this, matches, argsHmac;
matches = id.match( /^nav_menu_instance\[([0-9a-f]{32})]$/ );
if ( ! matches ) {
throw new Error( 'Illegal id for nav_menu_instance partial. The key corresponds with the args HMAC.' );
}
argsHmac = matches[1];
options = options || {};
options.params = _.extend(
{
selector: '[data-customize-partial-id="' + id + '"]',
navMenuArgs: options.constructingContainerContext || {},
containerInclusive: true
},
options.params || {}
);
api.selectiveRefresh.Partial.prototype.initialize.call( partial, id, options );
if ( ! _.isObject( partial.params.navMenuArgs ) ) {
throw new Error( 'Missing navMenuArgs' );
}
if ( partial.params.navMenuArgs.args_hmac !== argsHmac ) {
throw new Error( 'args_hmac mismatch with id' );
}
},
/**
* Return whether the setting is related to this partial.
*
* @since 4.5.0
* @param {wp.customize.Value|string} setting - Object or ID.
* @param {number|Object|false|null} newValue - New value, or null if the setting was just removed.
* @param {number|Object|false|null} oldValue - Old value, or null if the setting was just added.
* @return {boolean}
*/
isRelatedSetting: function( setting, newValue, oldValue ) {
var partial = this, navMenuLocationSetting, navMenuId, isNavMenuItemSetting, _newValue, _oldValue, urlParser;
if ( _.isString( setting ) ) {
setting = api( setting );
}
/*
* Prevent nav_menu_item changes only containing type_label differences triggering a refresh.
* These settings in the preview do not include type_label property, and so if one of these
* nav_menu_item settings is dirty, after a refresh the nav menu instance would do a selective
* refresh immediately because the setting from the pane would have the type_label whereas
* the setting in the preview would not, thus triggering a change event. The following
* condition short-circuits this unnecessary selective refresh and also prevents an infinite
* loop in the case where a nav_menu_instance partial had done a fallback refresh.
* @todo Nav menu item settings should not include a type_label property to begin with.
*/
isNavMenuItemSetting = /^nav_menu_item\[/.test( setting.id );
if ( isNavMenuItemSetting && _.isObject( newValue ) && _.isObject( oldValue ) ) {
_newValue = _.clone( newValue );
_oldValue = _.clone( oldValue );
delete _newValue.type_label;
delete _oldValue.type_label;
// Normalize URL scheme when parent frame is HTTPS to prevent selective refresh upon initial page load.
if ( 'https' === api.preview.scheme.get() ) {
urlParser = document.createElement( 'a' );
urlParser.href = _newValue.url;
urlParser.protocol = 'https:';
_newValue.url = urlParser.href;
urlParser.href = _oldValue.url;
urlParser.protocol = 'https:';
_oldValue.url = urlParser.href;
}
// Prevent original_title differences from causing refreshes if title is present.
if ( newValue.title ) {
delete _oldValue.original_title;
delete _newValue.original_title;
}
if ( _.isEqual( _oldValue, _newValue ) ) {
return false;
}
}
if ( partial.params.navMenuArgs.theme_location ) {
if ( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' === setting.id ) {
return true;
}
navMenuLocationSetting = api( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' );
}
navMenuId = partial.params.navMenuArgs.menu;
if ( ! navMenuId && navMenuLocationSetting ) {
navMenuId = navMenuLocationSetting();
}
if ( ! navMenuId ) {
return false;
}
return (
( 'nav_menu[' + navMenuId + ']' === setting.id ) ||
( isNavMenuItemSetting && (
( newValue && newValue.nav_menu_term_id === navMenuId ) ||
( oldValue && oldValue.nav_menu_term_id === navMenuId )
) )
);
},
/**
* Make sure that partial fallback behavior is invoked if there is no associated menu.
*
* @since 4.5.0
*
* @return {Promise}
*/
refresh: function() {
var partial = this, menuId, deferred = $.Deferred();
// Make sure the fallback behavior is invoked when the partial is no longer associated with a menu.
if ( _.isNumber( partial.params.navMenuArgs.menu ) ) {
menuId = partial.params.navMenuArgs.menu;
} else if ( partial.params.navMenuArgs.theme_location && api.has( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' ) ) {
menuId = api( 'nav_menu_locations[' + partial.params.navMenuArgs.theme_location + ']' ).get();
}
if ( ! menuId ) {
partial.fallback();
deferred.reject();
return deferred.promise();
}
return api.selectiveRefresh.Partial.prototype.refresh.call( partial );
},
/**
* Render content.
*
* @inheritdoc
* @param {wp.customize.selectiveRefresh.Placement} placement
*/
renderContent: function( placement ) {
var partial = this, previousContainer = placement.container;
// Do fallback behavior to refresh preview if menu is now empty.
if ( '' === placement.addedContent ) {
placement.partial.fallback();
}
if ( api.selectiveRefresh.Partial.prototype.renderContent.call( partial, placement ) ) {
// Trigger deprecated event.
$( document ).trigger( 'customize-preview-menu-refreshed', [ {
instanceNumber: null, // @deprecated
wpNavArgs: placement.context, // @deprecated
wpNavMenuArgs: placement.context,
oldContainer: previousContainer,
newContainer: placement.container
} ] );
}
}
});
api.selectiveRefresh.partialConstructor.nav_menu_instance = self.NavMenuInstancePartial;
/**
* Request full refresh if there are nav menu instances that lack partials which also match the supplied args.
*
* @param {Object} navMenuInstanceArgs
*/
self.handleUnplacedNavMenuInstances = function( navMenuInstanceArgs ) {
var unplacedNavMenuInstances;
unplacedNavMenuInstances = _.filter( _.values( self.data.navMenuInstanceArgs ), function( args ) {
return ! api.selectiveRefresh.partial.has( 'nav_menu_instance[' + args.args_hmac + ']' );
} );
if ( _.findWhere( unplacedNavMenuInstances, navMenuInstanceArgs ) ) {
api.selectiveRefresh.requestFullRefresh();
return true;
}
return false;
};
/**
* Add change listener for a nav_menu[], nav_menu_item[], or nav_menu_locations[] setting.
*
* @since 4.5.0
*
* @param {wp.customize.Value} setting
* @param {Object} [options]
* @param {boolean} options.fire Whether to invoke the callback after binding.
* This is used when a dynamic setting is added.
* @return {boolean} Whether the setting was bound.
*/
self.bindSettingListener = function( setting, options ) {
var matches;
options = options || {};
matches = setting.id.match( /^nav_menu\[(-?\d+)]$/ );
if ( matches ) {
setting._navMenuId = parseInt( matches[1], 10 );
setting.bind( this.onChangeNavMenuSetting );
if ( options.fire ) {
this.onChangeNavMenuSetting.call( setting, setting(), false );
}
return true;
}
matches = setting.id.match( /^nav_menu_item\[(-?\d+)]$/ );
if ( matches ) {
setting._navMenuItemId = parseInt( matches[1], 10 );
setting.bind( this.onChangeNavMenuItemSetting );
if ( options.fire ) {
this.onChangeNavMenuItemSetting.call( setting, setting(), false );
}
return true;
}
matches = setting.id.match( /^nav_menu_locations\[(.+?)]/ );
if ( matches ) {
setting._navMenuThemeLocation = matches[1];
setting.bind( this.onChangeNavMenuLocationsSetting );
if ( options.fire ) {
this.onChangeNavMenuLocationsSetting.call( setting, setting(), false );
}
return true;
}
return false;
};
/**
* Remove change listeners for nav_menu[], nav_menu_item[], or nav_menu_locations[] setting.
*
* @since 4.5.0
*
* @param {wp.customize.Value} setting
*/
self.unbindSettingListener = function( setting ) {
setting.unbind( this.onChangeNavMenuSetting );
setting.unbind( this.onChangeNavMenuItemSetting );
setting.unbind( this.onChangeNavMenuLocationsSetting );
};
/**
* Handle change for nav_menu[] setting for nav menu instances lacking partials.
*
* @since 4.5.0
*
* @this {wp.customize.Value}
*/
self.onChangeNavMenuSetting = function() {
var setting = this;
self.handleUnplacedNavMenuInstances( {
menu: setting._navMenuId
} );
// Ensure all nav menu instances with a theme_location assigned to this menu are handled.
api.each( function( otherSetting ) {
if ( ! otherSetting._navMenuThemeLocation ) {
return;
}
if ( setting._navMenuId === otherSetting() ) {
self.handleUnplacedNavMenuInstances( {
theme_location: otherSetting._navMenuThemeLocation
} );
}
} );
};
/**
* Handle change for nav_menu_item[] setting for nav menu instances lacking partials.
*
* @since 4.5.0
*
* @param {Object} newItem New value for nav_menu_item[] setting.
* @param {Object} oldItem Old value for nav_menu_item[] setting.
* @this {wp.customize.Value}
*/
self.onChangeNavMenuItemSetting = function( newItem, oldItem ) {
var item = newItem || oldItem, navMenuSetting;
navMenuSetting = api( 'nav_menu[' + String( item.nav_menu_term_id ) + ']' );
if ( navMenuSetting ) {
self.onChangeNavMenuSetting.call( navMenuSetting );
}
};
/**
* Handle change for nav_menu_locations[] setting for nav menu instances lacking partials.
*
* @since 4.5.0
*
* @this {wp.customize.Value}
*/
self.onChangeNavMenuLocationsSetting = function() {
var setting = this, hasNavMenuInstance;
self.handleUnplacedNavMenuInstances( {
theme_location: setting._navMenuThemeLocation
} );
// If there are no wp_nav_menu() instances that refer to the theme location, do full refresh.
hasNavMenuInstance = !! _.findWhere( _.values( self.data.navMenuInstanceArgs ), {
theme_location: setting._navMenuThemeLocation
} );
if ( ! hasNavMenuInstance ) {
api.selectiveRefresh.requestFullRefresh();
}
};
}
/**
* Connect nav menu items with their corresponding controls in the pane.
*
* Setup shift-click on nav menu items which are more granular than the nav menu partial itself.
* Also this applies even if a nav menu is not partial-refreshable.
*
* @since 4.5.0
*/
self.highlightControls = function() {
var selector = '.menu-item';
// Skip adding highlights if not in the customizer preview iframe.
if ( ! api.settings.channel ) {
return;
}
// Focus on the menu item control when shift+clicking the menu item.
$( document ).on( 'click', selector, function( e ) {
var navMenuItemParts;
if ( ! e.shiftKey ) {
return;
}
navMenuItemParts = $( this ).attr( 'class' ).match( /(?:^|\s)menu-item-(-?\d+)(?:\s|$)/ );
if ( navMenuItemParts ) {
e.preventDefault();
e.stopPropagation(); // Make sure a sub-nav menu item will get focused instead of parent items.
api.preview.send( 'focus-nav-menu-item-control', parseInt( navMenuItemParts[1], 10 ) );
}
});
};
api.bind( 'preview-ready', function() {
self.init();
} );
return self;
}( jQuery, _, wp, wp.customize ) );

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,773 @@
/**
* @output wp-includes/js/customize-preview-widgets.js
*/
/* global _wpWidgetCustomizerPreviewSettings */
/**
* Handles the initialization, refreshing and rendering of widget partials and sidebar widgets.
*
* @since 4.5.0
*
* @namespace wp.customize.widgetsPreview
*
* @param {jQuery} $ The jQuery object.
* @param {Object} _ The utilities library.
* @param {Object} wp Current WordPress environment instance.
* @param {Object} api Information from the API.
*
* @return {Object} Widget-related variables.
*/
wp.customize.widgetsPreview = wp.customize.WidgetCustomizerPreview = (function( $, _, wp, api ) {
var self;
self = {
renderedSidebars: {},
renderedWidgets: {},
registeredSidebars: [],
registeredWidgets: {},
widgetSelectors: [],
preview: null,
l10n: {
widgetTooltip: ''
},
selectiveRefreshableWidgets: {}
};
/**
* Initializes the widgets preview.
*
* @since 4.5.0
*
* @memberOf wp.customize.widgetsPreview
*
* @return {void}
*/
self.init = function() {
var self = this;
self.preview = api.preview;
if ( ! _.isEmpty( self.selectiveRefreshableWidgets ) ) {
self.addPartials();
}
self.buildWidgetSelectors();
self.highlightControls();
self.preview.bind( 'highlight-widget', self.highlightWidget );
api.preview.bind( 'active', function() {
self.highlightControls();
} );
/*
* Refresh a partial when the controls pane requests it. This is used currently just by the
* Gallery widget so that when an attachment's caption is updated in the media modal,
* the widget in the preview will then be refreshed to show the change. Normally doing this
* would not be necessary because all of the state should be contained inside the changeset,
* as everything done in the Customizer should not make a change to the site unless the
* changeset itself is published. Attachments are a current exception to this rule.
* For a proposal to include attachments in the customized state, see #37887.
*/
api.preview.bind( 'refresh-widget-partial', function( widgetId ) {
var partialId = 'widget[' + widgetId + ']';
if ( api.selectiveRefresh.partial.has( partialId ) ) {
api.selectiveRefresh.partial( partialId ).refresh();
} else if ( self.renderedWidgets[ widgetId ] ) {
api.preview.send( 'refresh' ); // Fallback in case theme does not support 'customize-selective-refresh-widgets'.
}
} );
};
self.WidgetPartial = api.selectiveRefresh.Partial.extend(/** @lends wp.customize.widgetsPreview.WidgetPartial.prototype */{
/**
* Represents a partial widget instance.
*
* @since 4.5.0
*
* @constructs
* @augments wp.customize.selectiveRefresh.Partial
*
* @alias wp.customize.widgetsPreview.WidgetPartial
* @memberOf wp.customize.widgetsPreview
*
* @param {string} id The partial's ID.
* @param {Object} options Options used to initialize the partial's
* instance.
* @param {Object} options.params The options parameters.
*/
initialize: function( id, options ) {
var partial = this, matches;
matches = id.match( /^widget\[(.+)]$/ );
if ( ! matches ) {
throw new Error( 'Illegal id for widget partial.' );
}
partial.widgetId = matches[1];
partial.widgetIdParts = self.parseWidgetId( partial.widgetId );
options = options || {};
options.params = _.extend(
{
settings: [ self.getWidgetSettingId( partial.widgetId ) ],
containerInclusive: true
},
options.params || {}
);
api.selectiveRefresh.Partial.prototype.initialize.call( partial, id, options );
},
/**
* Refreshes the widget partial.
*
* @since 4.5.0
*
* @return {Promise|void} Either a promise postponing the refresh, or void.
*/
refresh: function() {
var partial = this, refreshDeferred;
if ( ! self.selectiveRefreshableWidgets[ partial.widgetIdParts.idBase ] ) {
refreshDeferred = $.Deferred();
refreshDeferred.reject();
partial.fallback();
return refreshDeferred.promise();
} else {
return api.selectiveRefresh.Partial.prototype.refresh.call( partial );
}
},
/**
* Sends the widget-updated message to the parent so the spinner will get
* removed from the widget control.
*
* @inheritDoc
* @param {wp.customize.selectiveRefresh.Placement} placement The placement
* function.
*
* @return {void}
*/
renderContent: function( placement ) {
var partial = this;
if ( api.selectiveRefresh.Partial.prototype.renderContent.call( partial, placement ) ) {
api.preview.send( 'widget-updated', partial.widgetId );
api.selectiveRefresh.trigger( 'widget-updated', partial );
}
}
});
self.SidebarPartial = api.selectiveRefresh.Partial.extend(/** @lends wp.customize.widgetsPreview.SidebarPartial.prototype */{
/**
* Represents a partial widget area.
*
* @since 4.5.0
*
* @class
* @augments wp.customize.selectiveRefresh.Partial
*
* @memberOf wp.customize.widgetsPreview
* @alias wp.customize.widgetsPreview.SidebarPartial
*
* @param {string} id The partial's ID.
* @param {Object} options Options used to initialize the partial's instance.
* @param {Object} options.params The options parameters.
*/
initialize: function( id, options ) {
var partial = this, matches;
matches = id.match( /^sidebar\[(.+)]$/ );
if ( ! matches ) {
throw new Error( 'Illegal id for sidebar partial.' );
}
partial.sidebarId = matches[1];
options = options || {};
options.params = _.extend(
{
settings: [ 'sidebars_widgets[' + partial.sidebarId + ']' ]
},
options.params || {}
);
api.selectiveRefresh.Partial.prototype.initialize.call( partial, id, options );
if ( ! partial.params.sidebarArgs ) {
throw new Error( 'The sidebarArgs param was not provided.' );
}
if ( partial.params.settings.length > 1 ) {
throw new Error( 'Expected SidebarPartial to only have one associated setting' );
}
},
/**
* Sets up the partial.
*
* @since 4.5.0
*
* @return {void}
*/
ready: function() {
var sidebarPartial = this;
// Watch for changes to the sidebar_widgets setting.
_.each( sidebarPartial.settings(), function( settingId ) {
api( settingId ).bind( _.bind( sidebarPartial.handleSettingChange, sidebarPartial ) );
} );
// Trigger an event for this sidebar being updated whenever a widget inside is rendered.
api.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
var isAssignedWidgetPartial = (
placement.partial.extended( self.WidgetPartial ) &&
( -1 !== _.indexOf( sidebarPartial.getWidgetIds(), placement.partial.widgetId ) )
);
if ( isAssignedWidgetPartial ) {
api.selectiveRefresh.trigger( 'sidebar-updated', sidebarPartial );
}
} );
// Make sure that a widget partial has a container in the DOM prior to a refresh.
api.bind( 'change', function( widgetSetting ) {
var widgetId, parsedId;
parsedId = self.parseWidgetSettingId( widgetSetting.id );
if ( ! parsedId ) {
return;
}
widgetId = parsedId.idBase;
if ( parsedId.number ) {
widgetId += '-' + String( parsedId.number );
}
if ( -1 !== _.indexOf( sidebarPartial.getWidgetIds(), widgetId ) ) {
sidebarPartial.ensureWidgetPlacementContainers( widgetId );
}
} );
},
/**
* Gets the before/after boundary nodes for all instances of this sidebar
* (usually one).
*
* Note that TreeWalker is not implemented in IE8.
*
* @since 4.5.0
*
* @return {Array.<{before: Comment, after: Comment, instanceNumber: number}>}
* An array with an object for each sidebar instance, containing the
* node before and after the sidebar instance and its instance number.
*/
findDynamicSidebarBoundaryNodes: function() {
var partial = this, regExp, boundaryNodes = {}, recursiveCommentTraversal;
regExp = /^(dynamic_sidebar_before|dynamic_sidebar_after):(.+):(\d+)$/;
recursiveCommentTraversal = function( childNodes ) {
_.each( childNodes, function( node ) {
var matches;
if ( 8 === node.nodeType ) {
matches = node.nodeValue.match( regExp );
if ( ! matches || matches[2] !== partial.sidebarId ) {
return;
}
if ( _.isUndefined( boundaryNodes[ matches[3] ] ) ) {
boundaryNodes[ matches[3] ] = {
before: null,
after: null,
instanceNumber: parseInt( matches[3], 10 )
};
}
if ( 'dynamic_sidebar_before' === matches[1] ) {
boundaryNodes[ matches[3] ].before = node;
} else {
boundaryNodes[ matches[3] ].after = node;
}
} else if ( 1 === node.nodeType ) {
recursiveCommentTraversal( node.childNodes );
}
} );
};
recursiveCommentTraversal( document.body.childNodes );
return _.values( boundaryNodes );
},
/**
* Gets the placements for this partial.
*
* @since 4.5.0
*
* @return {Array} An array containing placement objects for each of the
* dynamic sidebar boundary nodes.
*/
placements: function() {
var partial = this;
return _.map( partial.findDynamicSidebarBoundaryNodes(), function( boundaryNodes ) {
return new api.selectiveRefresh.Placement( {
partial: partial,
container: null,
startNode: boundaryNodes.before,
endNode: boundaryNodes.after,
context: {
instanceNumber: boundaryNodes.instanceNumber
}
} );
} );
},
/**
* Get the list of widget IDs associated with this widget area.
*
* @since 4.5.0
*
* @throws {Error} If there's no settingId.
* @throws {Error} If the setting doesn't exist in the API.
* @throws {Error} If the API doesn't pass an array of widget IDs.
*
* @return {Array} A shallow copy of the array containing widget IDs.
*/
getWidgetIds: function() {
var sidebarPartial = this, settingId, widgetIds;
settingId = sidebarPartial.settings()[0];
if ( ! settingId ) {
throw new Error( 'Missing associated setting.' );
}
if ( ! api.has( settingId ) ) {
throw new Error( 'Setting does not exist.' );
}
widgetIds = api( settingId ).get();
if ( ! _.isArray( widgetIds ) ) {
throw new Error( 'Expected setting to be array of widget IDs' );
}
return widgetIds.slice( 0 );
},
/**
* Reflows widgets in the sidebar, ensuring they have the proper position in the
* DOM.
*
* @since 4.5.0
*
* @return {Array.<wp.customize.selectiveRefresh.Placement>} List of placements
* that were reflowed.
*/
reflowWidgets: function() {
var sidebarPartial = this, sidebarPlacements, widgetIds, widgetPartials, sortedSidebarContainers = [];
widgetIds = sidebarPartial.getWidgetIds();
sidebarPlacements = sidebarPartial.placements();
widgetPartials = {};
_.each( widgetIds, function( widgetId ) {
var widgetPartial = api.selectiveRefresh.partial( 'widget[' + widgetId + ']' );
if ( widgetPartial ) {
widgetPartials[ widgetId ] = widgetPartial;
}
} );
_.each( sidebarPlacements, function( sidebarPlacement ) {
var sidebarWidgets = [], needsSort = false, thisPosition, lastPosition = -1;
// Gather list of widget partial containers in this sidebar, and determine if a sort is needed.
_.each( widgetPartials, function( widgetPartial ) {
_.each( widgetPartial.placements(), function( widgetPlacement ) {
if ( sidebarPlacement.context.instanceNumber === widgetPlacement.context.sidebar_instance_number ) {
thisPosition = widgetPlacement.container.index();
sidebarWidgets.push( {
partial: widgetPartial,
placement: widgetPlacement,
position: thisPosition
} );
if ( thisPosition < lastPosition ) {
needsSort = true;
}
lastPosition = thisPosition;
}
} );
} );
if ( needsSort ) {
_.each( sidebarWidgets, function( sidebarWidget ) {
sidebarPlacement.endNode.parentNode.insertBefore(
sidebarWidget.placement.container[0],
sidebarPlacement.endNode
);
// @todo Rename partial-placement-moved?
api.selectiveRefresh.trigger( 'partial-content-moved', sidebarWidget.placement );
} );
sortedSidebarContainers.push( sidebarPlacement );
}
} );
if ( sortedSidebarContainers.length > 0 ) {
api.selectiveRefresh.trigger( 'sidebar-updated', sidebarPartial );
}
return sortedSidebarContainers;
},
/**
* Makes sure there is a widget instance container in this sidebar for the given
* widget ID.
*
* @since 4.5.0
*
* @param {string} widgetId The widget ID.
*
* @return {wp.customize.selectiveRefresh.Partial} The widget instance partial.
*/
ensureWidgetPlacementContainers: function( widgetId ) {
var sidebarPartial = this, widgetPartial, wasInserted = false, partialId = 'widget[' + widgetId + ']';
widgetPartial = api.selectiveRefresh.partial( partialId );
if ( ! widgetPartial ) {
widgetPartial = new self.WidgetPartial( partialId, {
params: {}
} );
}
// Make sure that there is a container element for the widget in the sidebar, if at least a placeholder.
_.each( sidebarPartial.placements(), function( sidebarPlacement ) {
var foundWidgetPlacement, widgetContainerElement;
foundWidgetPlacement = _.find( widgetPartial.placements(), function( widgetPlacement ) {
return ( widgetPlacement.context.sidebar_instance_number === sidebarPlacement.context.instanceNumber );
} );
if ( foundWidgetPlacement ) {
return;
}
widgetContainerElement = $(
sidebarPartial.params.sidebarArgs.before_widget.replace( /%1\$s/g, widgetId ).replace( /%2\$s/g, 'widget' ) +
sidebarPartial.params.sidebarArgs.after_widget
);
// Handle rare case where before_widget and after_widget are empty.
if ( ! widgetContainerElement[0] ) {
return;
}
widgetContainerElement.attr( 'data-customize-partial-id', widgetPartial.id );
widgetContainerElement.attr( 'data-customize-partial-type', 'widget' );
widgetContainerElement.attr( 'data-customize-widget-id', widgetId );
/*
* Make sure the widget container element has the customize-container context data.
* The sidebar_instance_number is used to disambiguate multiple instances of the
* same sidebar are rendered onto the template, and so the same widget is embedded
* multiple times.
*/
widgetContainerElement.data( 'customize-partial-placement-context', {
'sidebar_id': sidebarPartial.sidebarId,
'sidebar_instance_number': sidebarPlacement.context.instanceNumber
} );
sidebarPlacement.endNode.parentNode.insertBefore( widgetContainerElement[0], sidebarPlacement.endNode );
wasInserted = true;
} );
api.selectiveRefresh.partial.add( widgetPartial );
if ( wasInserted ) {
sidebarPartial.reflowWidgets();
}
return widgetPartial;
},
/**
* Handles changes to the sidebars_widgets[] setting.
*
* @since 4.5.0
*
* @param {Array} newWidgetIds New widget IDs.
* @param {Array} oldWidgetIds Old widget IDs.
*
* @return {void}
*/
handleSettingChange: function( newWidgetIds, oldWidgetIds ) {
var sidebarPartial = this, needsRefresh, widgetsRemoved, widgetsAdded, addedWidgetPartials = [];
needsRefresh = (
( oldWidgetIds.length > 0 && 0 === newWidgetIds.length ) ||
( newWidgetIds.length > 0 && 0 === oldWidgetIds.length )
);
if ( needsRefresh ) {
sidebarPartial.fallback();
return;
}
// Handle removal of widgets.
widgetsRemoved = _.difference( oldWidgetIds, newWidgetIds );
_.each( widgetsRemoved, function( removedWidgetId ) {
var widgetPartial = api.selectiveRefresh.partial( 'widget[' + removedWidgetId + ']' );
if ( widgetPartial ) {
_.each( widgetPartial.placements(), function( placement ) {
var isRemoved = (
placement.context.sidebar_id === sidebarPartial.sidebarId ||
( placement.context.sidebar_args && placement.context.sidebar_args.id === sidebarPartial.sidebarId )
);
if ( isRemoved ) {
placement.container.remove();
}
} );
}
delete self.renderedWidgets[ removedWidgetId ];
} );
// Handle insertion of widgets.
widgetsAdded = _.difference( newWidgetIds, oldWidgetIds );
_.each( widgetsAdded, function( addedWidgetId ) {
var widgetPartial = sidebarPartial.ensureWidgetPlacementContainers( addedWidgetId );
addedWidgetPartials.push( widgetPartial );
self.renderedWidgets[ addedWidgetId ] = true;
} );
_.each( addedWidgetPartials, function( widgetPartial ) {
widgetPartial.refresh();
} );
api.selectiveRefresh.trigger( 'sidebar-updated', sidebarPartial );
},
/**
* Refreshes the sidebar partial.
*
* Note that the meat is handled in handleSettingChange because it has the
* context of which widgets were removed.
*
* @since 4.5.0
*
* @return {Promise} A promise postponing the refresh.
*/
refresh: function() {
var partial = this, deferred = $.Deferred();
deferred.fail( function() {
partial.fallback();
} );
if ( 0 === partial.placements().length ) {
deferred.reject();
} else {
_.each( partial.reflowWidgets(), function( sidebarPlacement ) {
api.selectiveRefresh.trigger( 'partial-content-rendered', sidebarPlacement );
} );
deferred.resolve();
}
return deferred.promise();
}
});
api.selectiveRefresh.partialConstructor.sidebar = self.SidebarPartial;
api.selectiveRefresh.partialConstructor.widget = self.WidgetPartial;
/**
* Adds partials for the registered widget areas (sidebars).
*
* @since 4.5.0
*
* @return {void}
*/
self.addPartials = function() {
_.each( self.registeredSidebars, function( registeredSidebar ) {
var partial, partialId = 'sidebar[' + registeredSidebar.id + ']';
partial = api.selectiveRefresh.partial( partialId );
if ( ! partial ) {
partial = new self.SidebarPartial( partialId, {
params: {
sidebarArgs: registeredSidebar
}
} );
api.selectiveRefresh.partial.add( partial );
}
} );
};
/**
* Calculates the selector for the sidebar's widgets based on the registered
* sidebar's info.
*
* @memberOf wp.customize.widgetsPreview
*
* @since 3.9.0
*
* @return {void}
*/
self.buildWidgetSelectors = function() {
var self = this;
$.each( self.registeredSidebars, function( i, sidebar ) {
var widgetTpl = [
sidebar.before_widget,
sidebar.before_title,
sidebar.after_title,
sidebar.after_widget
].join( '' ),
emptyWidget,
widgetSelector,
widgetClasses;
emptyWidget = $( widgetTpl );
widgetSelector = emptyWidget.prop( 'tagName' ) || '';
widgetClasses = emptyWidget.prop( 'className' ) || '';
// Prevent a rare case when before_widget, before_title, after_title and after_widget is empty.
if ( ! widgetClasses ) {
return;
}
// Remove class names that incorporate the string formatting placeholders %1$s and %2$s.
widgetClasses = widgetClasses.replace( /\S*%[12]\$s\S*/g, '' );
widgetClasses = widgetClasses.replace( /^\s+|\s+$/g, '' );
if ( widgetClasses ) {
widgetSelector += '.' + widgetClasses.split( /\s+/ ).join( '.' );
}
self.widgetSelectors.push( widgetSelector );
});
};
/**
* Highlights the widget on widget updates or widget control mouse overs.
*
* @memberOf wp.customize.widgetsPreview
*
* @since 3.9.0
* @param {string} widgetId ID of the widget.
*
* @return {void}
*/
self.highlightWidget = function( widgetId ) {
var $body = $( document.body ),
$widget = $( '#' + widgetId );
$body.find( '.widget-customizer-highlighted-widget' ).removeClass( 'widget-customizer-highlighted-widget' );
$widget.addClass( 'widget-customizer-highlighted-widget' );
setTimeout( function() {
$widget.removeClass( 'widget-customizer-highlighted-widget' );
}, 500 );
};
/**
* Shows a title and highlights widgets on hover. On shift+clicking focuses the
* widget control.
*
* @memberOf wp.customize.widgetsPreview
*
* @since 3.9.0
*
* @return {void}
*/
self.highlightControls = function() {
var self = this,
selector = this.widgetSelectors.join( ',' );
// Skip adding highlights if not in the customizer preview iframe.
if ( ! api.settings.channel ) {
return;
}
$( selector ).attr( 'title', this.l10n.widgetTooltip );
// Highlights widget when entering the widget editor.
$( document ).on( 'mouseenter', selector, function() {
self.preview.send( 'highlight-widget-control', $( this ).prop( 'id' ) );
});
// Open expand the widget control when shift+clicking the widget element.
$( document ).on( 'click', selector, function( e ) {
if ( ! e.shiftKey ) {
return;
}
e.preventDefault();
self.preview.send( 'focus-widget-control', $( this ).prop( 'id' ) );
});
};
/**
* Parses a widget ID.
*
* @memberOf wp.customize.widgetsPreview
*
* @since 4.5.0
*
* @param {string} widgetId The widget ID.
*
* @return {{idBase: string, number: number|null}} An object containing the idBase
* and number of the parsed widget ID.
*/
self.parseWidgetId = function( widgetId ) {
var matches, parsed = {
idBase: '',
number: null
};
matches = widgetId.match( /^(.+)-(\d+)$/ );
if ( matches ) {
parsed.idBase = matches[1];
parsed.number = parseInt( matches[2], 10 );
} else {
parsed.idBase = widgetId; // Likely an old single widget.
}
return parsed;
};
/**
* Parses a widget setting ID.
*
* @memberOf wp.customize.widgetsPreview
*
* @since 4.5.0
*
* @param {string} settingId Widget setting ID.
*
* @return {{idBase: string, number: number|null}|null} Either an object containing the idBase
* and number of the parsed widget setting ID,
* or null.
*/
self.parseWidgetSettingId = function( settingId ) {
var matches, parsed = {
idBase: '',
number: null
};
matches = settingId.match( /^widget_([^\[]+?)(?:\[(\d+)])?$/ );
if ( ! matches ) {
return null;
}
parsed.idBase = matches[1];
if ( matches[2] ) {
parsed.number = parseInt( matches[2], 10 );
}
return parsed;
};
/**
* Converts a widget ID into a Customizer setting ID.
*
* @memberOf wp.customize.widgetsPreview
*
* @since 4.5.0
*
* @param {string} widgetId The widget ID.
*
* @return {string} The setting ID.
*/
self.getWidgetSettingId = function( widgetId ) {
var parsed = this.parseWidgetId( widgetId ), settingId;
settingId = 'widget_' + parsed.idBase;
if ( parsed.number ) {
settingId += '[' + String( parsed.number ) + ']';
}
return settingId;
};
api.bind( 'preview-ready', function() {
$.extend( self, _wpWidgetCustomizerPreviewSettings );
self.init();
});
return self;
})( jQuery, _, wp, wp.customize );

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,899 @@
/*
* Script run inside a Customizer preview frame.
*
* @output wp-includes/js/customize-preview.js
*/
(function( exports, $ ){
var api = wp.customize,
debounce,
currentHistoryState = {};
/*
* Capture the state that is passed into history.replaceState() and history.pushState()
* and also which is returned in the popstate event so that when the changeset_uuid
* gets updated when transitioning to a new changeset there the current state will
* be supplied in the call to history.replaceState().
*/
( function( history ) {
var injectUrlWithState;
if ( ! history.replaceState ) {
return;
}
/**
* Amend the supplied URL with the customized state.
*
* @since 4.7.0
* @access private
*
* @param {string} url URL.
* @return {string} URL with customized state.
*/
injectUrlWithState = function( url ) {
var urlParser, oldQueryParams, newQueryParams;
urlParser = document.createElement( 'a' );
urlParser.href = url;
oldQueryParams = api.utils.parseQueryString( location.search.substr( 1 ) );
newQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
newQueryParams.customize_changeset_uuid = oldQueryParams.customize_changeset_uuid;
if ( oldQueryParams.customize_autosaved ) {
newQueryParams.customize_autosaved = 'on';
}
if ( oldQueryParams.customize_theme ) {
newQueryParams.customize_theme = oldQueryParams.customize_theme;
}
if ( oldQueryParams.customize_messenger_channel ) {
newQueryParams.customize_messenger_channel = oldQueryParams.customize_messenger_channel;
}
urlParser.search = $.param( newQueryParams );
return urlParser.href;
};
history.replaceState = ( function( nativeReplaceState ) {
return function historyReplaceState( data, title, url ) {
currentHistoryState = data;
return nativeReplaceState.call( history, data, title, 'string' === typeof url && url.length > 0 ? injectUrlWithState( url ) : url );
};
} )( history.replaceState );
history.pushState = ( function( nativePushState ) {
return function historyPushState( data, title, url ) {
currentHistoryState = data;
return nativePushState.call( history, data, title, 'string' === typeof url && url.length > 0 ? injectUrlWithState( url ) : url );
};
} )( history.pushState );
window.addEventListener( 'popstate', function( event ) {
currentHistoryState = event.state;
} );
}( history ) );
/**
* Returns a debounced version of the function.
*
* @todo Require Underscore.js for this file and retire this.
*/
debounce = function( fn, delay, context ) {
var timeout;
return function() {
var args = arguments;
context = context || this;
clearTimeout( timeout );
timeout = setTimeout( function() {
timeout = null;
fn.apply( context, args );
}, delay );
};
};
/**
* @memberOf wp.customize
* @alias wp.customize.Preview
*
* @constructor
* @augments wp.customize.Messenger
* @augments wp.customize.Class
* @mixes wp.customize.Events
*/
api.Preview = api.Messenger.extend(/** @lends wp.customize.Preview.prototype */{
/**
* @param {Object} params - Parameters to configure the messenger.
* @param {Object} options - Extend any instance parameter or method with this object.
*/
initialize: function( params, options ) {
var preview = this, urlParser = document.createElement( 'a' );
api.Messenger.prototype.initialize.call( preview, params, options );
urlParser.href = preview.origin();
preview.add( 'scheme', urlParser.protocol.replace( /:$/, '' ) );
preview.body = $( document.body );
preview.window = $( window );
if ( api.settings.channel ) {
// If in an iframe, then intercept the link clicks and form submissions.
preview.body.on( 'click.preview', 'a', function( event ) {
preview.handleLinkClick( event );
} );
preview.body.on( 'submit.preview', 'form', function( event ) {
preview.handleFormSubmit( event );
} );
preview.window.on( 'scroll.preview', debounce( function() {
preview.send( 'scroll', preview.window.scrollTop() );
}, 200 ) );
preview.bind( 'scroll', function( distance ) {
preview.window.scrollTop( distance );
});
}
},
/**
* Handle link clicks in preview.
*
* @since 4.7.0
* @access public
*
* @param {jQuery.Event} event Event.
*/
handleLinkClick: function( event ) {
var preview = this, link, isInternalJumpLink;
link = $( event.target ).closest( 'a' );
// No-op if the anchor is not a link.
if ( _.isUndefined( link.attr( 'href' ) ) ) {
return;
}
// Allow internal jump links and JS links to behave normally without preventing default.
isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
if ( isInternalJumpLink || ! /^https?:$/.test( link.prop( 'protocol' ) ) ) {
return;
}
// If the link is not previewable, prevent the browser from navigating to it.
if ( ! api.isLinkPreviewable( link[0] ) ) {
wp.a11y.speak( api.settings.l10n.linkUnpreviewable );
event.preventDefault();
return;
}
// Prevent initiating navigating from click and instead rely on sending url message to pane.
event.preventDefault();
/*
* Note the shift key is checked so shift+click on widgets or
* nav menu items can just result on focusing on the corresponding
* control instead of also navigating to the URL linked to.
*/
if ( event.shiftKey ) {
return;
}
// Note: It's not relevant to send scroll because sending url message will have the same effect.
preview.send( 'url', link.prop( 'href' ) );
},
/**
* Handle form submit.
*
* @since 4.7.0
* @access public
*
* @param {jQuery.Event} event Event.
*/
handleFormSubmit: function( event ) {
var preview = this, urlParser, form;
urlParser = document.createElement( 'a' );
form = $( event.target );
urlParser.href = form.prop( 'action' );
// If the link is not previewable, prevent the browser from navigating to it.
if ( 'GET' !== form.prop( 'method' ).toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
wp.a11y.speak( api.settings.l10n.formUnpreviewable );
event.preventDefault();
return;
}
/*
* If the default wasn't prevented already (in which case the form
* submission is already being handled by JS), and if it has a GET
* request method, then take the serialized form data and add it as
* a query string to the action URL and send this in a url message
* to the customizer pane so that it will be loaded. If the form's
* action points to a non-previewable URL, the customizer pane's
* previewUrl setter will reject it so that the form submission is
* a no-op, which is the same behavior as when clicking a link to an
* external site in the preview.
*/
if ( ! event.isDefaultPrevented() ) {
if ( urlParser.search.length > 1 ) {
urlParser.search += '&';
}
urlParser.search += form.serialize();
preview.send( 'url', urlParser.href );
}
// Prevent default since navigation should be done via sending url message or via JS submit handler.
event.preventDefault();
}
});
/**
* Inject the changeset UUID into links in the document.
*
* @since 4.7.0
* @access protected
* @access private
*
* @return {void}
*/
api.addLinkPreviewing = function addLinkPreviewing() {
var linkSelectors = 'a[href], area[href]';
// Inject links into initial document.
$( document.body ).find( linkSelectors ).each( function() {
api.prepareLinkPreview( this );
} );
// Inject links for new elements added to the page.
if ( 'undefined' !== typeof MutationObserver ) {
api.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( linkSelectors ).each( function() {
api.prepareLinkPreview( this );
} );
} );
} );
api.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
} else {
// If mutation observers aren't available, fallback to just-in-time injection.
$( document.documentElement ).on( 'click focus mouseover', linkSelectors, function() {
api.prepareLinkPreview( this );
} );
}
};
/**
* Should the supplied link is previewable.
*
* @since 4.7.0
* @access public
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {string} element.search Query string.
* @param {string} element.pathname Path.
* @param {string} element.host Host.
* @param {Object} [options]
* @param {Object} [options.allowAdminAjax=false] Allow admin-ajax.php requests.
* @return {boolean} Is appropriate for changeset link.
*/
api.isLinkPreviewable = function isLinkPreviewable( element, options ) {
var matchesAllowedUrl, parsedAllowedUrl, args, elementHost;
args = _.extend( {}, { allowAdminAjax: false }, options || {} );
if ( 'javascript:' === element.protocol ) { // jshint ignore:line
return true;
}
// Only web URLs can be previewed.
if ( 'https:' !== element.protocol && 'http:' !== element.protocol ) {
return false;
}
elementHost = element.host.replace( /:(80|443)$/, '' );
parsedAllowedUrl = document.createElement( 'a' );
matchesAllowedUrl = ! _.isUndefined( _.find( api.settings.url.allowed, function( allowedUrl ) {
parsedAllowedUrl.href = allowedUrl;
return parsedAllowedUrl.protocol === element.protocol && parsedAllowedUrl.host.replace( /:(80|443)$/, '' ) === elementHost && 0 === element.pathname.indexOf( parsedAllowedUrl.pathname.replace( /\/$/, '' ) );
} ) );
if ( ! matchesAllowedUrl ) {
return false;
}
// Skip wp login and signup pages.
if ( /\/wp-(login|signup)\.php$/.test( element.pathname ) ) {
return false;
}
// Allow links to admin ajax as faux frontend URLs.
if ( /\/wp-admin\/admin-ajax\.php$/.test( element.pathname ) ) {
return args.allowAdminAjax;
}
// Disallow links to admin, includes, and content.
if ( /\/wp-(admin|includes|content)(\/|$)/.test( element.pathname ) ) {
return false;
}
return true;
};
/**
* Inject the customize_changeset_uuid query param into links on the frontend.
*
* @since 4.7.0
* @access protected
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {string} element.search Query string.
* @param {string} element.host Host.
* @param {string} element.protocol Protocol.
* @return {void}
*/
api.prepareLinkPreview = function prepareLinkPreview( element ) {
var queryParams, $element = $( element );
// Skip elements with no href attribute. Check first to avoid more expensive checks down the road.
if ( ! element.hasAttribute( 'href' ) ) {
return;
}
// Skip links in admin bar.
if ( $element.closest( '#wpadminbar' ).length ) {
return;
}
// Ignore links with href="#", href="#id", or non-HTTP protocols (e.g. javascript: and mailto:).
if ( '#' === $element.attr( 'href' ).substr( 0, 1 ) || ! /^https?:$/.test( element.protocol ) ) {
return;
}
// Make sure links in preview use HTTPS if parent frame uses HTTPS.
if ( api.settings.channel && 'https' === api.preview.scheme.get() && 'http:' === element.protocol && -1 !== api.settings.url.allowedHosts.indexOf( element.host ) ) {
element.protocol = 'https:';
}
// Ignore links with class wp-playlist-caption.
if ( $element.hasClass( 'wp-playlist-caption' ) ) {
return;
}
if ( ! api.isLinkPreviewable( element ) ) {
// Style link as unpreviewable only if previewing in iframe; if previewing on frontend, links will be allowed to work normally.
if ( api.settings.channel ) {
$element.addClass( 'customize-unpreviewable' );
}
return;
}
$element.removeClass( 'customize-unpreviewable' );
queryParams = api.utils.parseQueryString( element.search.substring( 1 ) );
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( api.settings.changeset.autosaved ) {
queryParams.customize_autosaved = 'on';
}
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.channel ) {
queryParams.customize_messenger_channel = api.settings.channel;
}
element.search = $.param( queryParams );
};
/**
* Inject the changeset UUID into Ajax requests.
*
* @since 4.7.0
* @access protected
*
* @return {void}
*/
api.addRequestPreviewing = function addRequestPreviewing() {
/**
* Rewrite Ajax requests to inject customizer state.
*
* @param {Object} options Options.
* @param {string} options.type Type.
* @param {string} options.url URL.
* @param {Object} originalOptions Original options.
* @param {XMLHttpRequest} xhr XHR.
* @return {void}
*/
var prefilterAjax = function( options, originalOptions, xhr ) {
var urlParser, queryParams, requestMethod, dirtyValues = {};
urlParser = document.createElement( 'a' );
urlParser.href = options.url;
// Abort if the request is not for this site.
if ( ! api.isLinkPreviewable( urlParser, { allowAdminAjax: true } ) ) {
return;
}
queryParams = api.utils.parseQueryString( urlParser.search.substring( 1 ) );
// Note that _dirty flag will be cleared with changeset updates.
api.each( function( setting ) {
if ( setting._dirty ) {
dirtyValues[ setting.id ] = setting.get();
}
} );
if ( ! _.isEmpty( dirtyValues ) ) {
requestMethod = options.type.toUpperCase();
// Override underlying request method to ensure unsaved changes to changeset can be included (force Backbone.emulateHTTP).
if ( 'POST' !== requestMethod ) {
xhr.setRequestHeader( 'X-HTTP-Method-Override', requestMethod );
queryParams._method = requestMethod;
options.type = 'POST';
}
// Amend the post data with the customized values.
if ( options.data ) {
options.data += '&';
} else {
options.data = '';
}
options.data += $.param( {
customized: JSON.stringify( dirtyValues )
} );
}
// Include customized state query params in URL.
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( api.settings.changeset.autosaved ) {
queryParams.customize_autosaved = 'on';
}
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
// Ensure preview nonce is included with every customized request, to allow post data to be read.
queryParams.customize_preview_nonce = api.settings.nonce.preview;
urlParser.search = $.param( queryParams );
options.url = urlParser.href;
};
$.ajaxPrefilter( prefilterAjax );
};
/**
* Inject changeset UUID into forms, allowing preview to persist through submissions.
*
* @since 4.7.0
* @access protected
*
* @return {void}
*/
api.addFormPreviewing = function addFormPreviewing() {
// Inject inputs for forms in initial document.
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
// Inject inputs for new forms added to the page.
if ( 'undefined' !== typeof MutationObserver ) {
api.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
} );
} );
api.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
}
};
/**
* Inject changeset into form inputs.
*
* @since 4.7.0
* @access protected
*
* @param {HTMLFormElement} form Form.
* @return {void}
*/
api.prepareFormPreview = function prepareFormPreview( form ) {
var urlParser, stateParams = {};
if ( ! form.action ) {
form.action = location.href;
}
urlParser = document.createElement( 'a' );
urlParser.href = form.action;
// Make sure forms in preview use HTTPS if parent frame uses HTTPS.
if ( api.settings.channel && 'https' === api.preview.scheme.get() && 'http:' === urlParser.protocol && -1 !== api.settings.url.allowedHosts.indexOf( urlParser.host ) ) {
urlParser.protocol = 'https:';
form.action = urlParser.href;
}
if ( 'GET' !== form.method.toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
// Style form as unpreviewable only if previewing in iframe; if previewing on frontend, all forms will be allowed to work normally.
if ( api.settings.channel ) {
$( form ).addClass( 'customize-unpreviewable' );
}
return;
}
$( form ).removeClass( 'customize-unpreviewable' );
stateParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( api.settings.changeset.autosaved ) {
stateParams.customize_autosaved = 'on';
}
if ( ! api.settings.theme.active ) {
stateParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.channel ) {
stateParams.customize_messenger_channel = api.settings.channel;
}
_.each( stateParams, function( value, name ) {
var input = $( form ).find( 'input[name="' + name + '"]' );
if ( input.length ) {
input.val( value );
} else {
$( form ).prepend( $( '<input>', {
type: 'hidden',
name: name,
value: value
} ) );
}
} );
// Prevent links from breaking out of preview iframe.
if ( api.settings.channel ) {
form.target = '_self';
}
};
/**
* Watch current URL and send keep-alive (heartbeat) messages to the parent.
*
* Keep the customizer pane notified that the preview is still alive
* and that the user hasn't navigated to a non-customized URL.
*
* @since 4.7.0
* @access protected
*/
api.keepAliveCurrentUrl = ( function() {
var previousPathName = location.pathname,
previousQueryString = location.search.substr( 1 ),
previousQueryParams = null,
stateQueryParams = [ 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel', 'customize_autosaved' ];
return function keepAliveCurrentUrl() {
var urlParser, currentQueryParams;
// Short-circuit with keep-alive if previous URL is identical (as is normal case).
if ( previousQueryString === location.search.substr( 1 ) && previousPathName === location.pathname ) {
api.preview.send( 'keep-alive' );
return;
}
urlParser = document.createElement( 'a' );
if ( null === previousQueryParams ) {
urlParser.search = previousQueryString;
previousQueryParams = api.utils.parseQueryString( previousQueryString );
_.each( stateQueryParams, function( name ) {
delete previousQueryParams[ name ];
} );
}
// Determine if current URL minus customized state params and URL hash.
urlParser.href = location.href;
currentQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
_.each( stateQueryParams, function( name ) {
delete currentQueryParams[ name ];
} );
if ( previousPathName !== location.pathname || ! _.isEqual( previousQueryParams, currentQueryParams ) ) {
urlParser.search = $.param( currentQueryParams );
urlParser.hash = '';
api.settings.url.self = urlParser.href;
api.preview.send( 'ready', {
currentUrl: api.settings.url.self,
activePanels: api.settings.activePanels,
activeSections: api.settings.activeSections,
activeControls: api.settings.activeControls,
settingValidities: api.settings.settingValidities
} );
} else {
api.preview.send( 'keep-alive' );
}
previousQueryParams = currentQueryParams;
previousQueryString = location.search.substr( 1 );
previousPathName = location.pathname;
};
} )();
api.settingPreviewHandlers = {
/**
* Preview changes to custom logo.
*
* @param {number} attachmentId Attachment ID for custom logo.
* @return {void}
*/
custom_logo: function( attachmentId ) {
$( 'body' ).toggleClass( 'wp-custom-logo', !! attachmentId );
},
/**
* Preview changes to custom css.
*
* @param {string} value Custom CSS..
* @return {void}
*/
custom_css: function( value ) {
$( '#wp-custom-css' ).text( value );
},
/**
* Preview changes to any of the background settings.
*
* @return {void}
*/
background: function() {
var css = '', settings = {};
_.each( ['color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment'], function( prop ) {
settings[ prop ] = api( 'background_' + prop );
} );
/*
* The body will support custom backgrounds if either the color or image are set.
*
* See get_body_class() in /wp-includes/post-template.php
*/
$( document.body ).toggleClass( 'custom-background', !! ( settings.color() || settings.image() ) );
if ( settings.color() ) {
css += 'background-color: ' + settings.color() + ';';
}
if ( settings.image() ) {
css += 'background-image: url("' + settings.image() + '");';
css += 'background-size: ' + settings.size() + ';';
css += 'background-position: ' + settings.position_x() + ' ' + settings.position_y() + ';';
css += 'background-repeat: ' + settings.repeat() + ';';
css += 'background-attachment: ' + settings.attachment() + ';';
}
$( '#custom-background-css' ).text( 'body.custom-background { ' + css + ' }' );
}
};
$( function() {
var bg, setValue, handleUpdatedChangesetUuid;
api.settings = window._wpCustomizeSettings;
if ( ! api.settings ) {
return;
}
api.preview = new api.Preview({
url: window.location.href,
channel: api.settings.channel
});
api.addLinkPreviewing();
api.addRequestPreviewing();
api.addFormPreviewing();
/**
* Create/update a setting value.
*
* @param {string} id - Setting ID.
* @param {*} value - Setting value.
* @param {boolean} [createDirty] - Whether to create a setting as dirty. Defaults to false.
*/
setValue = function( id, value, createDirty ) {
var setting = api( id );
if ( setting ) {
setting.set( value );
} else {
createDirty = createDirty || false;
setting = api.create( id, value, {
id: id
} );
// Mark dynamically-created settings as dirty so they will get posted.
if ( createDirty ) {
setting._dirty = true;
}
}
};
api.preview.bind( 'settings', function( values ) {
$.each( values, setValue );
});
api.preview.trigger( 'settings', api.settings.values );
$.each( api.settings._dirty, function( i, id ) {
var setting = api( id );
if ( setting ) {
setting._dirty = true;
}
} );
api.preview.bind( 'setting', function( args ) {
var createDirty = true;
setValue.apply( null, args.concat( createDirty ) );
});
api.preview.bind( 'sync', function( events ) {
/*
* Delete any settings that already exist locally which haven't been
* modified in the controls while the preview was loading. This prevents
* situations where the JS value being synced from the pane may differ
* from the PHP-sanitized JS value in the preview which causes the
* non-sanitized JS value to clobber the PHP-sanitized value. This
* is particularly important for selective refresh partials that
* have a fallback refresh behavior since infinite refreshing would
* result.
*/
if ( events.settings && events['settings-modified-while-loading'] ) {
_.each( _.keys( events.settings ), function( syncedSettingId ) {
if ( api.has( syncedSettingId ) && ! events['settings-modified-while-loading'][ syncedSettingId ] ) {
delete events.settings[ syncedSettingId ];
}
} );
}
$.each( events, function( event, args ) {
api.preview.trigger( event, args );
});
api.preview.send( 'synced' );
});
api.preview.bind( 'active', function() {
api.preview.send( 'nonce', api.settings.nonce );
api.preview.send( 'documentTitle', document.title );
// Send scroll in case of loading via non-refresh.
api.preview.send( 'scroll', $( window ).scrollTop() );
});
/**
* Handle update to changeset UUID.
*
* @param {string} uuid - UUID.
* @return {void}
*/
handleUpdatedChangesetUuid = function( uuid ) {
api.settings.changeset.uuid = uuid;
// Update UUIDs in links and forms.
$( document.body ).find( 'a[href], area[href]' ).each( function() {
api.prepareLinkPreview( this );
} );
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
/*
* Replace the UUID in the URL. Note that the wrapped history.replaceState()
* will handle injecting the current api.settings.changeset.uuid into the URL,
* so this is merely to trigger that logic.
*/
if ( history.replaceState ) {
history.replaceState( currentHistoryState, '', location.href );
}
};
api.preview.bind( 'changeset-uuid', handleUpdatedChangesetUuid );
api.preview.bind( 'saved', function( response ) {
if ( response.next_changeset_uuid ) {
handleUpdatedChangesetUuid( response.next_changeset_uuid );
}
api.trigger( 'saved', response );
} );
// Update the URLs to reflect the fact we've started autosaving.
api.preview.bind( 'autosaving', function() {
if ( api.settings.changeset.autosaved ) {
return;
}
api.settings.changeset.autosaved = true; // Start deferring to any autosave once changeset is updated.
$( document.body ).find( 'a[href], area[href]' ).each( function() {
api.prepareLinkPreview( this );
} );
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
if ( history.replaceState ) {
history.replaceState( currentHistoryState, '', location.href );
}
} );
/*
* Clear dirty flag for settings when saved to changeset so that they
* won't be needlessly included in selective refresh or ajax requests.
*/
api.preview.bind( 'changeset-saved', function( data ) {
_.each( data.saved_changeset_values, function( value, settingId ) {
var setting = api( settingId );
if ( setting && _.isEqual( setting.get(), value ) ) {
setting._dirty = false;
}
} );
} );
api.preview.bind( 'nonce-refresh', function( nonce ) {
$.extend( api.settings.nonce, nonce );
} );
/*
* Send a message to the parent customize frame with a list of which
* containers and controls are active.
*/
api.preview.send( 'ready', {
currentUrl: api.settings.url.self,
activePanels: api.settings.activePanels,
activeSections: api.settings.activeSections,
activeControls: api.settings.activeControls,
settingValidities: api.settings.settingValidities
} );
// Send ready when URL changes via JS.
setInterval( api.keepAliveCurrentUrl, api.settings.timeouts.keepAliveSend );
// Display a loading indicator when preview is reloading, and remove on failure.
api.preview.bind( 'loading-initiated', function () {
$( 'body' ).addClass( 'wp-customizer-unloading' );
});
api.preview.bind( 'loading-failed', function () {
$( 'body' ).removeClass( 'wp-customizer-unloading' );
});
/* Custom Backgrounds */
bg = $.map( ['color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment'], function( prop ) {
return 'background_' + prop;
} );
api.when.apply( api, bg ).done( function() {
$.each( arguments, function() {
this.bind( api.settingPreviewHandlers.background );
});
});
/**
* Custom Logo
*
* Toggle the wp-custom-logo body class when a logo is added or removed.
*
* @since 4.5.0
*/
api( 'custom_logo', function ( setting ) {
api.settingPreviewHandlers.custom_logo.call( setting, setting.get() );
setting.bind( api.settingPreviewHandlers.custom_logo );
} );
api( 'custom_css[' + api.settings.theme.stylesheet + ']', function( setting ) {
setting.bind( api.settingPreviewHandlers.custom_css );
} );
api.trigger( 'preview-ready' );
});
})( wp, jQuery );

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,202 @@
/**
* @output wp-includes/js/customize-views.js
*/
(function( $, wp, _ ) {
if ( ! wp || ! wp.customize ) { return; }
var api = wp.customize;
/**
* wp.customize.HeaderTool.CurrentView
*
* Displays the currently selected header image, or a placeholder in lack
* thereof.
*
* Instantiate with model wp.customize.HeaderTool.currentHeader.
*
* @memberOf wp.customize.HeaderTool
* @alias wp.customize.HeaderTool.CurrentView
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.CurrentView = wp.Backbone.View.extend(/** @lends wp.customize.HeaderTool.CurrentView.prototype */{
template: wp.template('header-current'),
initialize: function() {
this.listenTo(this.model, 'change', this.render);
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.setButtons();
return this;
},
setButtons: function() {
var elements = $('#customize-control-header_image .actions .remove');
if (this.model.get('choice')) {
elements.show();
} else {
elements.hide();
}
}
});
/**
* wp.customize.HeaderTool.ChoiceView
*
* Represents a choosable header image, be it user-uploaded,
* theme-suggested or a special Randomize choice.
*
* Takes a wp.customize.HeaderTool.ImageModel.
*
* Manually changes model wp.customize.HeaderTool.currentHeader via the
* `select` method.
*
* @memberOf wp.customize.HeaderTool
* @alias wp.customize.HeaderTool.ChoiceView
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.ChoiceView = wp.Backbone.View.extend(/** @lends wp.customize.HeaderTool.ChoiceView.prototype */{
template: wp.template('header-choice'),
className: 'header-view',
events: {
'click .choice,.random': 'select',
'click .close': 'removeImage'
},
initialize: function() {
var properties = [
this.model.get('header').url,
this.model.get('choice')
];
this.listenTo(this.model, 'change:selected', this.toggleSelected);
if (_.contains(properties, api.get().header_image)) {
api.HeaderTool.currentHeader.set(this.extendedModel());
}
},
render: function() {
this.$el.html(this.template(this.extendedModel()));
this.toggleSelected();
return this;
},
toggleSelected: function() {
this.$el.toggleClass('selected', this.model.get('selected'));
},
extendedModel: function() {
var c = this.model.get('collection');
return _.extend(this.model.toJSON(), {
type: c.type
});
},
select: function() {
this.preventJump();
this.model.save();
api.HeaderTool.currentHeader.set(this.extendedModel());
},
preventJump: function() {
var container = $('.wp-full-overlay-sidebar-content'),
scroll = container.scrollTop();
_.defer(function() {
container.scrollTop(scroll);
});
},
removeImage: function(e) {
e.stopPropagation();
this.model.destroy();
this.remove();
}
});
/**
* wp.customize.HeaderTool.ChoiceListView
*
* A container for ChoiceViews. These choices should be of one same type:
* user-uploaded headers or theme-defined ones.
*
* Takes a wp.customize.HeaderTool.ChoiceList.
*
* @memberOf wp.customize.HeaderTool
* @alias wp.customize.HeaderTool.ChoiceListView
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.ChoiceListView = wp.Backbone.View.extend(/** @lends wp.customize.HeaderTool.ChoiceListView.prototype */{
initialize: function() {
this.listenTo(this.collection, 'add', this.addOne);
this.listenTo(this.collection, 'remove', this.render);
this.listenTo(this.collection, 'sort', this.render);
this.listenTo(this.collection, 'change', this.toggleList);
this.render();
},
render: function() {
this.$el.empty();
this.collection.each(this.addOne, this);
this.toggleList();
},
addOne: function(choice) {
var view;
choice.set({ collection: this.collection });
view = new api.HeaderTool.ChoiceView({ model: choice });
this.$el.append(view.render().el);
},
toggleList: function() {
var title = this.$el.parents().prev('.customize-control-title'),
randomButton = this.$el.find('.random').parent();
if (this.collection.shouldHideTitle()) {
title.add(randomButton).hide();
} else {
title.add(randomButton).show();
}
}
});
/**
* wp.customize.HeaderTool.CombinedList
*
* Aggregates wp.customize.HeaderTool.ChoiceList collections (or any
* Backbone object, really) and acts as a bus to feed them events.
*
* @memberOf wp.customize.HeaderTool
* @alias wp.customize.HeaderTool.CombinedList
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.CombinedList = wp.Backbone.View.extend(/** @lends wp.customize.HeaderTool.CombinedList.prototype */{
initialize: function(collections) {
this.collections = collections;
this.on('all', this.propagate, this);
},
propagate: function(event, arg) {
_.each(this.collections, function(collection) {
collection.trigger(event, arg);
});
}
});
})( jQuery, window.wp, _ );

2
wp-includes/js/customize-views.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
!function(i,e,o){var t;e&&e.customize&&((t=e.customize).HeaderTool.CurrentView=e.Backbone.View.extend({template:e.template("header-current"),initialize:function(){this.listenTo(this.model,"change",this.render),this.render()},render:function(){return this.$el.html(this.template(this.model.toJSON())),this.setButtons(),this},setButtons:function(){var e=i("#customize-control-header_image .actions .remove");this.model.get("choice")?e.show():e.hide()}}),t.HeaderTool.ChoiceView=e.Backbone.View.extend({template:e.template("header-choice"),className:"header-view",events:{"click .choice,.random":"select","click .close":"removeImage"},initialize:function(){var e=[this.model.get("header").url,this.model.get("choice")];this.listenTo(this.model,"change:selected",this.toggleSelected),o.contains(e,t.get().header_image)&&t.HeaderTool.currentHeader.set(this.extendedModel())},render:function(){return this.$el.html(this.template(this.extendedModel())),this.toggleSelected(),this},toggleSelected:function(){this.$el.toggleClass("selected",this.model.get("selected"))},extendedModel:function(){var e=this.model.get("collection");return o.extend(this.model.toJSON(),{type:e.type})},select:function(){this.preventJump(),this.model.save(),t.HeaderTool.currentHeader.set(this.extendedModel())},preventJump:function(){var e=i(".wp-full-overlay-sidebar-content"),t=e.scrollTop();o.defer(function(){e.scrollTop(t)})},removeImage:function(e){e.stopPropagation(),this.model.destroy(),this.remove()}}),t.HeaderTool.ChoiceListView=e.Backbone.View.extend({initialize:function(){this.listenTo(this.collection,"add",this.addOne),this.listenTo(this.collection,"remove",this.render),this.listenTo(this.collection,"sort",this.render),this.listenTo(this.collection,"change",this.toggleList),this.render()},render:function(){this.$el.empty(),this.collection.each(this.addOne,this),this.toggleList()},addOne:function(e){e.set({collection:this.collection}),e=new t.HeaderTool.ChoiceView({model:e}),this.$el.append(e.render().el)},toggleList:function(){var e=this.$el.parents().prev(".customize-control-title"),t=this.$el.find(".random").parent();this.collection.shouldHideTitle()?e.add(t).hide():e.add(t).show()}}),t.HeaderTool.CombinedList=e.Backbone.View.extend({initialize:function(e){this.collections=e,this.on("all",this.propagate,this)},propagate:function(t,i){o.each(this.collections,function(e){e.trigger(t,i)})}}))}(jQuery,window.wp,_);

319
wp-includes/js/dist/a11y.js vendored Normal file
View file

@ -0,0 +1,319 @@
this["wp"] = this["wp"] || {}; this["wp"]["a11y"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "jncB");
/******/ })
/************************************************************************/
/******/ ({
/***/ "Y8OO":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["domReady"]; }());
/***/ }),
/***/ "jncB":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "setup", function() { return /* binding */ setup; });
__webpack_require__.d(__webpack_exports__, "speak", function() { return /* binding */ speak; });
// EXTERNAL MODULE: external ["wp","domReady"]
var external_wp_domReady_ = __webpack_require__("Y8OO");
var external_wp_domReady_default = /*#__PURE__*/__webpack_require__.n(external_wp_domReady_);
// EXTERNAL MODULE: external ["wp","i18n"]
var external_wp_i18n_ = __webpack_require__("l3Sj");
// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/add-intro-text.js
/**
* WordPress dependencies
*/
/**
* Build the explanatory text to be placed before the aria live regions.
*
* This text is initially hidden from assistive technologies by using a `hidden`
* HTML attribute which is then removed once a message fills the aria-live regions.
*
* @return {HTMLParagraphElement} The explanatory text HTML element.
*/
function addIntroText() {
const introText = document.createElement('p');
introText.id = 'a11y-speak-intro-text';
introText.className = 'a11y-speak-intro-text';
introText.textContent = Object(external_wp_i18n_["__"])('Notifications');
introText.setAttribute('style', 'position: absolute;' + 'margin: -1px;' + 'padding: 0;' + 'height: 1px;' + 'width: 1px;' + 'overflow: hidden;' + 'clip: rect(1px, 1px, 1px, 1px);' + '-webkit-clip-path: inset(50%);' + 'clip-path: inset(50%);' + 'border: 0;' + 'word-wrap: normal !important;');
introText.setAttribute('hidden', 'hidden');
const {
body
} = document;
if (body) {
body.appendChild(introText);
}
return introText;
}
// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/add-container.js
/**
* Build the live regions markup.
*
* @param {string} [ariaLive] Value for the 'aria-live' attribute; default: 'polite'.
*
* @return {HTMLDivElement} The ARIA live region HTML element.
*/
function addContainer(ariaLive = 'polite') {
const container = document.createElement('div');
container.id = `a11y-speak-${ariaLive}`;
container.className = 'a11y-speak-region';
container.setAttribute('style', 'position: absolute;' + 'margin: -1px;' + 'padding: 0;' + 'height: 1px;' + 'width: 1px;' + 'overflow: hidden;' + 'clip: rect(1px, 1px, 1px, 1px);' + '-webkit-clip-path: inset(50%);' + 'clip-path: inset(50%);' + 'border: 0;' + 'word-wrap: normal !important;');
container.setAttribute('aria-live', ariaLive);
container.setAttribute('aria-relevant', 'additions text');
container.setAttribute('aria-atomic', 'true');
const {
body
} = document;
if (body) {
body.appendChild(container);
}
return container;
}
// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/clear.js
/**
* Clears the a11y-speak-region elements and hides the explanatory text.
*/
function clear() {
const regions = document.getElementsByClassName('a11y-speak-region');
const introText = document.getElementById('a11y-speak-intro-text');
for (let i = 0; i < regions.length; i++) {
regions[i].textContent = '';
} // Make sure the explanatory text is hidden from assistive technologies.
if (introText) {
introText.setAttribute('hidden', 'hidden');
}
}
// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/filter-message.js
let previousMessage = '';
/**
* Filter the message to be announced to the screenreader.
*
* @param {string} message The message to be announced.
*
* @return {string} The filtered message.
*/
function filterMessage(message) {
/*
* Strip HTML tags (if any) from the message string. Ideally, messages should
* be simple strings, carefully crafted for specific use with A11ySpeak.
* When re-using already existing strings this will ensure simple HTML to be
* stripped out and replaced with a space. Browsers will collapse multiple
* spaces natively.
*/
message = message.replace(/<[^<>]+>/g, ' ');
/*
* Safari + VoiceOver don't announce repeated, identical strings. We use
* a `no-break space` to force them to think identical strings are different.
*/
if (previousMessage === message) {
message += '\u00A0';
}
previousMessage = message;
return message;
}
// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Create the live regions.
*/
function setup() {
const introText = document.getElementById('a11y-speak-intro-text');
const containerAssertive = document.getElementById('a11y-speak-assertive');
const containerPolite = document.getElementById('a11y-speak-polite');
if (introText === null) {
addIntroText();
}
if (containerAssertive === null) {
addContainer('assertive');
}
if (containerPolite === null) {
addContainer('polite');
}
}
/**
* Run setup on domReady.
*/
external_wp_domReady_default()(setup);
/**
* Allows you to easily announce dynamic interface updates to screen readers using ARIA live regions.
* This module is inspired by the `speak` function in `wp-a11y.js`.
*
* @param {string} message The message to be announced by assistive technologies.
* @param {string} [ariaLive] The politeness level for aria-live; default: 'polite'.
*
* @example
* ```js
* import { speak } from '@wordpress/a11y';
*
* // For polite messages that shouldn't interrupt what screen readers are currently announcing.
* speak( 'The message you want to send to the ARIA live region' );
*
* // For assertive messages that should interrupt what screen readers are currently announcing.
* speak( 'The message you want to send to the ARIA live region', 'assertive' );
* ```
*/
function speak(message, ariaLive) {
/*
* Clear previous messages to allow repeated strings being read out and hide
* the explanatory text from assistive technologies.
*/
clear();
message = filterMessage(message);
const introText = document.getElementById('a11y-speak-intro-text');
const containerAssertive = document.getElementById('a11y-speak-assertive');
const containerPolite = document.getElementById('a11y-speak-polite');
if (containerAssertive && ariaLive === 'assertive') {
containerAssertive.textContent = message;
} else if (containerPolite) {
containerPolite.textContent = message;
}
/*
* Make the explanatory text available to assistive technologies by removing
* the 'hidden' HTML attribute.
*/
if (introText) {
introText.removeAttribute('hidden');
}
}
/***/ }),
/***/ "l3Sj":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["i18n"]; }());
/***/ })
/******/ });

2
wp-includes/js/dist/a11y.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.a11y=function(t){var e={};function n(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(i,o,function(e){return t[e]}.bind(null,o));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s="jncB")}({Y8OO:function(t,e){t.exports=window.wp.domReady},jncB:function(t,e,n){"use strict";n.r(e),n.d(e,"setup",(function(){return u})),n.d(e,"speak",(function(){return d}));var i=n("Y8OO"),o=n.n(i),r=n("l3Sj");function a(t="polite"){const e=document.createElement("div");e.id="a11y-speak-"+t,e.className="a11y-speak-region",e.setAttribute("style","position: absolute;margin: -1px;padding: 0;height: 1px;width: 1px;overflow: hidden;clip: rect(1px, 1px, 1px, 1px);-webkit-clip-path: inset(50%);clip-path: inset(50%);border: 0;word-wrap: normal !important;"),e.setAttribute("aria-live",t),e.setAttribute("aria-relevant","additions text"),e.setAttribute("aria-atomic","true");const{body:n}=document;return n&&n.appendChild(e),e}let p="";function u(){const t=document.getElementById("a11y-speak-intro-text"),e=document.getElementById("a11y-speak-assertive"),n=document.getElementById("a11y-speak-polite");null===t&&function(){const t=document.createElement("p");t.id="a11y-speak-intro-text",t.className="a11y-speak-intro-text",t.textContent=Object(r.__)("Notifications"),t.setAttribute("style","position: absolute;margin: -1px;padding: 0;height: 1px;width: 1px;overflow: hidden;clip: rect(1px, 1px, 1px, 1px);-webkit-clip-path: inset(50%);clip-path: inset(50%);border: 0;word-wrap: normal !important;"),t.setAttribute("hidden","hidden");const{body:e}=document;e&&e.appendChild(t)}(),null===e&&a("assertive"),null===n&&a("polite")}function d(t,e){!function(){const t=document.getElementsByClassName("a11y-speak-region"),e=document.getElementById("a11y-speak-intro-text");for(let e=0;e<t.length;e++)t[e].textContent="";e&&e.setAttribute("hidden","hidden")}(),t=function(t){return t=t.replace(/<[^<>]+>/g," "),p===t&&(t+=" "),p=t,t}(t);const n=document.getElementById("a11y-speak-intro-text"),i=document.getElementById("a11y-speak-assertive"),o=document.getElementById("a11y-speak-polite");i&&"assertive"===e?i.textContent=t:o&&(o.textContent=t),n&&n.removeAttribute("hidden")}o()(u)},l3Sj:function(t,e){t.exports=window.wp.i18n}});

1132
wp-includes/js/dist/annotations.js vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

838
wp-includes/js/dist/api-fetch.js vendored Normal file
View file

@ -0,0 +1,838 @@
this["wp"] = this["wp"] || {}; this["wp"]["apiFetch"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "jqrR");
/******/ })
/************************************************************************/
/******/ ({
/***/ "Mmq9":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["url"]; }());
/***/ }),
/***/ "jqrR":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: external ["wp","i18n"]
var external_wp_i18n_ = __webpack_require__("l3Sj");
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/nonce.js
/**
* @param {string} nonce
* @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
*/
function createNonceMiddleware(nonce) {
/**
* @type {import('../types').APIFetchMiddleware & { nonce: string }}
*/
const middleware = (options, next) => {
const {
headers = {}
} = options; // If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
for (const headerName in headers) {
if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
return next(options);
}
}
return next({ ...options,
headers: { ...headers,
'X-WP-Nonce': middleware.nonce
}
});
};
middleware.nonce = nonce;
return middleware;
}
/* harmony default export */ var nonce = (createNonceMiddleware);
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/namespace-endpoint.js
/**
* @type {import('../types').APIFetchMiddleware}
*/
const namespaceAndEndpointMiddleware = (options, next) => {
let path = options.path;
let namespaceTrimmed, endpointTrimmed;
if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
endpointTrimmed = options.endpoint.replace(/^\//, '');
if (endpointTrimmed) {
path = namespaceTrimmed + '/' + endpointTrimmed;
} else {
path = namespaceTrimmed;
}
}
delete options.namespace;
delete options.endpoint;
return next({ ...options,
path
});
};
/* harmony default export */ var namespace_endpoint = (namespaceAndEndpointMiddleware);
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/root-url.js
/**
* Internal dependencies
*/
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = rootURL => (options, next) => {
return namespace_endpoint(options, optionsWithPath => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
if (typeof path === 'string') {
apiRoot = rootURL;
if (-1 !== rootURL.indexOf('?')) {
path = path.replace('?', '&');
}
path = path.replace(/^\//, ''); // API root may already include query parameter prefix if site is
// configured to use plain permalinks.
if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
path = path.replace('?', '&');
}
url = apiRoot + path;
}
return next({ ...optionsWithPath,
url
});
});
};
/* harmony default export */ var root_url = (createRootURLMiddleware);
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/preloading.js
/**
* Given a path, returns a normalized path where equal query parameter values
* will be treated as identical, regardless of order they appear in the original
* text.
*
* @param {string} path Original path.
*
* @return {string} Normalized path.
*/
function getStablePath(path) {
const splitted = path.split('?');
const query = splitted[1];
const base = splitted[0];
if (!query) {
return base;
} // 'b=1&c=2&a=5'
return base + '?' + query // [ 'b=1', 'c=2', 'a=5' ]
.split('&') // [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ]
.map(entry => entry.split('=')) // [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ]
.sort((a, b) => a[0].localeCompare(b[0])) // [ 'a=5', 'b=1', 'c=2' ]
.map(pair => pair.join('=')) // 'a=5&b=1&c=2'
.join('&');
}
/**
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
function createPreloadingMiddleware(preloadedData) {
const cache = Object.keys(preloadedData).reduce((result, path) => {
result[getStablePath(path)] = preloadedData[path];
return result;
},
/** @type {Record<string, any>} */
{});
return (options, next) => {
const {
parse = true
} = options;
if (typeof options.path === 'string') {
const method = options.method || 'GET';
const path = getStablePath(options.path);
if ('GET' === method && cache[path]) {
const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only preloaded a single time
delete cache[path];
return Promise.resolve(parse ? cacheData.body : new window.Response(JSON.stringify(cacheData.body), {
status: 200,
statusText: 'OK',
headers: cacheData.headers
}));
} else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
return Promise.resolve(parse ? cache[method][path].body : cache[method][path]);
}
}
return next(options);
};
}
/* harmony default export */ var preloading = (createPreloadingMiddleware);
// EXTERNAL MODULE: external ["wp","url"]
var external_wp_url_ = __webpack_require__("Mmq9");
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/fetch-all-middleware.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Apply query arguments to both URL and Path, whichever is present.
*
* @param {import('../types').APIFetchOptions} props
* @param {Record<string, string | number>} queryArgs
* @return {import('../types').APIFetchOptions} The request with the modified query args
*/
const modifyQuery = ({
path,
url,
...options
}, queryArgs) => ({ ...options,
url: url && Object(external_wp_url_["addQueryArgs"])(url, queryArgs),
path: path && Object(external_wp_url_["addQueryArgs"])(path, queryArgs)
});
/**
* Duplicates parsing functionality from apiFetch.
*
* @param {Response} response
* @return {Promise<any>} Parsed response json.
*/
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
/**
* @param {string | null} linkHeader
* @return {{ next?: string }} The parsed link header.
*/
const parseLinkHeader = linkHeader => {
if (!linkHeader) {
return {};
}
const match = linkHeader.match(/<([^>]+)>; rel="next"/);
return match ? {
next: match[1]
} : {};
};
/**
* @param {Response} response
* @return {string | undefined} The next page URL.
*/
const getNextPageUrl = response => {
const {
next
} = parseLinkHeader(response.headers.get('link'));
return next;
};
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request contains an unbounded query.
*/
const requestContainsUnboundedQuery = options => {
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
return pathIsUnbounded || urlIsUnbounded;
};
/**
* The REST API enforces an upper limit on the per_page option. To handle large
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
* then recursively assemble a full response array from all available pages.
*
* @type {import('../types').APIFetchMiddleware}
*/
const fetchAllMiddleware = async (options, next) => {
if (options.parse === false) {
// If a consumer has opted out of parsing, do not apply middleware.
return next(options);
}
if (!requestContainsUnboundedQuery(options)) {
// If neither url nor path is requesting all items, do not apply middleware.
return next(options);
} // Retrieve requested page of results.
const response = await build_module({ ...modifyQuery(options, {
per_page: 100
}),
// Ensure headers are returned for page 1.
parse: false
});
const results = await parseResponse(response);
if (!Array.isArray(results)) {
// We have no reliable way of merging non-array results.
return results;
}
let nextPage = getNextPageUrl(response);
if (!nextPage) {
// There are no further pages to request.
return results;
} // Iteratively fetch all remaining pages until no "next" header is found.
let mergedResults =
/** @type {any[]} */
[].concat(results);
while (nextPage) {
const nextResponse = await build_module({ ...options,
// Ensure the URL for the next page is used instead of any provided path.
path: undefined,
url: nextPage,
// Ensure we still get headers so we can identify the next page.
parse: false
});
const nextResults = await parseResponse(nextResponse);
mergedResults = mergedResults.concat(nextResults);
nextPage = getNextPageUrl(nextResponse);
}
return mergedResults;
};
/* harmony default export */ var fetch_all_middleware = (fetchAllMiddleware);
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/http-v1.js
/**
* Set of HTTP methods which are eligible to be overridden.
*
* @type {Set<string>}
*/
const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
/**
* Default request method.
*
* "A request has an associated method (a method). Unless stated otherwise it
* is `GET`."
*
* @see https://fetch.spec.whatwg.org/#requests
*
* @type {string}
*/
const DEFAULT_METHOD = 'GET';
/**
* API Fetch middleware which overrides the request method for HTTP v1
* compatibility leveraging the REST API X-HTTP-Method-Override header.
*
* @type {import('../types').APIFetchMiddleware}
*/
const httpV1Middleware = (options, next) => {
const {
method = DEFAULT_METHOD
} = options;
if (OVERRIDE_METHODS.has(method.toUpperCase())) {
options = { ...options,
headers: { ...options.headers,
'X-HTTP-Method-Override': method,
'Content-Type': 'application/json'
},
method: 'POST'
};
}
return next(options);
};
/* harmony default export */ var http_v1 = (httpV1Middleware);
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/user-locale.js
/**
* WordPress dependencies
*/
/**
* @type {import('../types').APIFetchMiddleware}
*/
const userLocaleMiddleware = (options, next) => {
if (typeof options.url === 'string' && !Object(external_wp_url_["hasQueryArg"])(options.url, '_locale')) {
options.url = Object(external_wp_url_["addQueryArgs"])(options.url, {
_locale: 'user'
});
}
if (typeof options.path === 'string' && !Object(external_wp_url_["hasQueryArg"])(options.path, '_locale')) {
options.path = Object(external_wp_url_["addQueryArgs"])(options.path, {
_locale: 'user'
});
}
return next(options);
};
/* harmony default export */ var user_locale = (userLocaleMiddleware);
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/utils/response.js
/**
* WordPress dependencies
*/
/**
* Parses the apiFetch response.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any> | null | Response} Parsed response.
*/
const response_parseResponse = (response, shouldParseResponse = true) => {
if (shouldParseResponse) {
if (response.status === 204) {
return null;
}
return response.json ? response.json() : Promise.reject(response);
}
return response;
};
/**
* Calls the `json` function on the Response, throwing an error if the response
* doesn't have a json function or if parsing the json itself fails.
*
* @param {Response} response
* @return {Promise<any>} Parsed response.
*/
const parseJsonAndNormalizeError = response => {
const invalidJsonError = {
code: 'invalid_json',
message: Object(external_wp_i18n_["__"])('The response is not a valid JSON response.')
};
if (!response || !response.json) {
throw invalidJsonError;
}
return response.json().catch(() => {
throw invalidJsonError;
});
};
/**
* Parses the apiFetch response properly and normalize response errors.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any>} Parsed response.
*/
const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => {
return Promise.resolve(response_parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse));
};
/**
* Parses a response, throwing an error if parsing the response fails.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
* @return {Promise<any>} Parsed response.
*/
function parseAndThrowError(response, shouldParseResponse = true) {
if (!shouldParseResponse) {
throw response;
}
return parseJsonAndNormalizeError(response).then(error => {
const unknownError = {
code: 'unknown_error',
message: Object(external_wp_i18n_["__"])('An unknown error occurred.')
};
throw error || unknownError;
});
}
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/media-upload.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = (options, next) => {
const isMediaUploadRequest = options.path && options.path.indexOf('/wp/v2/media') !== -1 || options.url && options.url.indexOf('/wp/v2/media') !== -1;
if (!isMediaUploadRequest) {
return next(options);
}
let retries = 0;
const maxRetries = 5;
/**
* @param {string} attachmentId
* @return {Promise<any>} Processed post response.
*/
const postProcess = attachmentId => {
retries++;
return next({
path: `/wp/v2/media/${attachmentId}/post-process`,
method: 'POST',
data: {
action: 'create-image-subsizes'
},
parse: false
}).catch(() => {
if (retries < maxRetries) {
return postProcess(attachmentId);
}
next({
path: `/wp/v2/media/${attachmentId}?force=true`,
method: 'DELETE'
});
return Promise.reject();
});
};
return next({ ...options,
parse: false
}).catch(response => {
const attachmentId = response.headers.get('x-wp-upload-attachment-id');
if (response.status >= 500 && response.status < 600 && attachmentId) {
return postProcess(attachmentId).catch(() => {
if (options.parse !== false) {
return Promise.reject({
code: 'post_process',
message: Object(external_wp_i18n_["__"])('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
});
}
return Promise.reject(response);
});
}
return parseAndThrowError(response, options.parse);
}).then(response => parseResponseAndNormalizeError(response, options.parse));
};
/* harmony default export */ var media_upload = (mediaUploadMiddleware);
// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Default set of header values which should be sent with every request unless
* explicitly provided through apiFetch options.
*
* @type {Record<string, string>}
*/
const DEFAULT_HEADERS = {
// The backend uses the Accept header as a condition for considering an
// incoming request as a REST request.
//
// See: https://core.trac.wordpress.org/ticket/44534
Accept: 'application/json, */*;q=0.1'
};
/**
* Default set of fetch option values which should be sent with every request
* unless explicitly provided through apiFetch options.
*
* @type {Object}
*/
const DEFAULT_OPTIONS = {
credentials: 'include'
};
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
/**
* @type {import('./types').APIFetchMiddleware[]}
*/
const middlewares = [user_locale, namespace_endpoint, http_v1, fetch_all_middleware];
/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
function registerMiddleware(middleware) {
middlewares.unshift(middleware);
}
/**
* Checks the status of a response, throwing the Response as an error if
* it is outside the 200 range.
*
* @param {Response} response
* @return {Response} The response if the status is in the 200 range.
*/
const checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw response;
};
/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
/**
* @type {FetchHandler}
*/
const defaultFetchHandler = nextOptions => {
const {
url,
path,
data,
parse = true,
...remainingOptions
} = nextOptions;
let {
body,
headers
} = nextOptions; // Merge explicitly-provided headers with default values.
headers = { ...DEFAULT_HEADERS,
...headers
}; // The `data` property is a shorthand for sending a JSON body.
if (data) {
body = JSON.stringify(data);
headers['Content-Type'] = 'application/json';
}
const responsePromise = window.fetch( // fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed
url || path || window.location.href, { ...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers
});
return responsePromise // Return early if fetch errors. If fetch error, there is most likely no
// network connection. Unfortunately fetch just throws a TypeError and
// the message might depend on the browser.
.then(value => Promise.resolve(value).then(checkStatus).catch(response => parseAndThrowError(response, parse)).then(response => parseResponseAndNormalizeError(response, parse)), () => {
throw {
code: 'fetch_error',
message: Object(external_wp_i18n_["__"])('You are probably offline.')
};
});
};
/** @type {FetchHandler} */
let fetchHandler = defaultFetchHandler;
/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {FetchHandler} newFetchHandler The new fetch handler
*/
function setFetchHandler(newFetchHandler) {
fetchHandler = newFetchHandler;
}
/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
function apiFetch(options) {
// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
// converting `middlewares = [ m1, m2, m3 ]` into:
// ```
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
// ```
const enhancedHandler = middlewares.reduceRight((
/** @type {FetchHandler} */
next, middleware) => {
return workingOptions => middleware(workingOptions, next);
}, fetchHandler);
return enhancedHandler(options).catch(error => {
if (error.code !== 'rest_cookie_invalid_nonce') {
return Promise.reject(error);
} // If the nonce is invalid, refresh it and try again.
return window // @ts-ignore
.fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
// @ts-ignore
apiFetch.nonceMiddleware.nonce = text;
return apiFetch(options);
});
});
}
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;
apiFetch.createNonceMiddleware = nonce;
apiFetch.createPreloadingMiddleware = preloading;
apiFetch.createRootURLMiddleware = root_url;
apiFetch.fetchAllMiddleware = fetch_all_middleware;
apiFetch.mediaUploadMiddleware = media_upload;
/* harmony default export */ var build_module = __webpack_exports__["default"] = (apiFetch);
/***/ }),
/***/ "l3Sj":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["i18n"]; }());
/***/ })
/******/ })["default"];

2
wp-includes/js/dist/api-fetch.min.js vendored Normal file

File diff suppressed because one or more lines are too long

495
wp-includes/js/dist/autop.js vendored Normal file
View file

@ -0,0 +1,495 @@
this["wp"] = this["wp"] || {}; this["wp"]["autop"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "zbAn");
/******/ })
/************************************************************************/
/******/ ({
/***/ "zbAn":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autop", function() { return autop; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removep", function() { return removep; });
/**
* The regular expression for an HTML element.
*
* @type {RegExp}
*/
const htmlSplitRegex = (() => {
/* eslint-disable no-multi-spaces */
const comments = '!' + // Start of comment, after the <.
'(?:' + // Unroll the loop: Consume everything until --> is found.
'-(?!->)' + // Dash not followed by end of comment.
'[^\\-]*' + // Consume non-dashes.
')*' + // Loop possessively.
'(?:-->)?'; // End of comment. If not found, match all input.
const cdata = '!\\[CDATA\\[' + // Start of comment, after the <.
'[^\\]]*' + // Consume non-].
'(?:' + // Unroll the loop: Consume everything until ]]> is found.
'](?!]>)' + // One ] not followed by end of comment.
'[^\\]]*' + // Consume non-].
')*?' + // Loop possessively.
'(?:]]>)?'; // End of comment. If not found, match all input.
const escaped = '(?=' + // Is the element escaped?
'!--' + '|' + '!\\[CDATA\\[' + ')' + '((?=!-)' + // If yes, which type?
comments + '|' + cdata + ')';
const regex = '(' + // Capture the entire match.
'<' + // Find start of element.
'(' + // Conditional expression follows.
escaped + // Find end of escaped element.
'|' + // ... else ...
'[^>]*>?' + // Find end of normal element.
')' + ')';
return new RegExp(regex);
/* eslint-enable no-multi-spaces */
})();
/**
* Separate HTML elements and comments from the text.
*
* @param {string} input The text which has to be formatted.
* @return {string[]} The formatted text.
*/
function htmlSplit(input) {
const parts = [];
let workingInput = input;
let match;
while (match = workingInput.match(htmlSplitRegex)) {
// The `match` result, when invoked on a RegExp with the `g` flag (`/foo/g`) will not include `index`.
// If the `g` flag is omitted, `index` is included.
// `htmlSplitRegex` does not have the `g` flag so we can assert it will have an index number.
// Assert `match.index` is a number.
const index =
/** @type {number} */
match.index;
parts.push(workingInput.slice(0, index));
parts.push(match[0]);
workingInput = workingInput.slice(index + match[0].length);
}
if (workingInput.length) {
parts.push(workingInput);
}
return parts;
}
/**
* Replace characters or phrases within HTML elements only.
*
* @param {string} haystack The text which has to be formatted.
* @param {Record<string,string>} replacePairs In the form {from: 'to', }.
* @return {string} The formatted text.
*/
function replaceInHtmlTags(haystack, replacePairs) {
// Find all elements.
const textArr = htmlSplit(haystack);
let changed = false; // Extract all needles.
const needles = Object.keys(replacePairs); // Loop through delimiters (elements) only.
for (let i = 1; i < textArr.length; i += 2) {
for (let j = 0; j < needles.length; j++) {
const needle = needles[j];
if (-1 !== textArr[i].indexOf(needle)) {
textArr[i] = textArr[i].replace(new RegExp(needle, 'g'), replacePairs[needle]);
changed = true; // After one strtr() break out of the foreach loop and look at next element.
break;
}
}
}
if (changed) {
haystack = textArr.join('');
}
return haystack;
}
/**
* Replaces double line-breaks with paragraph elements.
*
* A group of regex replaces used to identify text formatted with newlines and
* replace double line-breaks with HTML paragraph tags. The remaining line-
* breaks after conversion become `<br />` tags, unless br is set to 'false'.
*
* @param {string} text The text which has to be formatted.
* @param {boolean} br Optional. If set, will convert all remaining line-
* breaks after paragraphing. Default true.
*
* @example
*```js
* import { autop } from '@wordpress/autop';
* autop( 'my text' ); // "<p>my text</p>"
* ```
*
* @return {string} Text which has been converted into paragraph tags.
*/
function autop(text, br = true) {
const preTags = [];
if (text.trim() === '') {
return '';
} // Just to make things a little easier, pad the end.
text = text + '\n';
/*
* Pre tags shouldn't be touched by autop.
* Replace pre tags with placeholders and bring them back after autop.
*/
if (text.indexOf('<pre') !== -1) {
const textParts = text.split('</pre>');
const lastText = textParts.pop();
text = '';
for (let i = 0; i < textParts.length; i++) {
const textPart = textParts[i];
const start = textPart.indexOf('<pre'); // Malformed html?
if (start === -1) {
text += textPart;
continue;
}
const name = '<pre wp-pre-tag-' + i + '></pre>';
preTags.push([name, textPart.substr(start) + '</pre>']);
text += textPart.substr(0, start) + name;
}
text += lastText;
} // Change multiple <br>s into two line breaks, which will turn into paragraphs.
text = text.replace(/<br\s*\/?>\s*<br\s*\/?>/g, '\n\n');
const allBlocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; // Add a double line break above block-level opening tags.
text = text.replace(new RegExp('(<' + allBlocks + '[\\s/>])', 'g'), '\n\n$1'); // Add a double line break below block-level closing tags.
text = text.replace(new RegExp('(</' + allBlocks + '>)', 'g'), '$1\n\n'); // Standardize newline characters to "\n".
text = text.replace(/\r\n|\r/g, '\n'); // Find newlines in all elements and add placeholders.
text = replaceInHtmlTags(text, {
'\n': ' <!-- wpnl --> '
}); // Collapse line breaks before and after <option> elements so they don't get autop'd.
if (text.indexOf('<option') !== -1) {
text = text.replace(/\s*<option/g, '<option');
text = text.replace(/<\/option>\s*/g, '</option>');
}
/*
* Collapse line breaks inside <object> elements, before <param> and <embed> elements
* so they don't get autop'd.
*/
if (text.indexOf('</object>') !== -1) {
text = text.replace(/(<object[^>]*>)\s*/g, '$1');
text = text.replace(/\s*<\/object>/g, '</object>');
text = text.replace(/\s*(<\/?(?:param|embed)[^>]*>)\s*/g, '$1');
}
/*
* Collapse line breaks inside <audio> and <video> elements,
* before and after <source> and <track> elements.
*/
if (text.indexOf('<source') !== -1 || text.indexOf('<track') !== -1) {
text = text.replace(/([<\[](?:audio|video)[^>\]]*[>\]])\s*/g, '$1');
text = text.replace(/\s*([<\[]\/(?:audio|video)[>\]])/g, '$1');
text = text.replace(/\s*(<(?:source|track)[^>]*>)\s*/g, '$1');
} // Collapse line breaks before and after <figcaption> elements.
if (text.indexOf('<figcaption') !== -1) {
text = text.replace(/\s*(<figcaption[^>]*>)/, '$1');
text = text.replace(/<\/figcaption>\s*/, '</figcaption>');
} // Remove more than two contiguous line breaks.
text = text.replace(/\n\n+/g, '\n\n'); // Split up the contents into an array of strings, separated by double line breaks.
const texts = text.split(/\n\s*\n/).filter(Boolean); // Reset text prior to rebuilding.
text = ''; // Rebuild the content as a string, wrapping every bit with a <p>.
texts.forEach(textPiece => {
text += '<p>' + textPiece.replace(/^\n*|\n*$/g, '') + '</p>\n';
}); // Under certain strange conditions it could create a P of entirely whitespace.
text = text.replace(/<p>\s*<\/p>/g, ''); // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
text = text.replace(/<p>([^<]+)<\/(div|address|form)>/g, '<p>$1</p></$2>'); // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // In some cases <li> may get wrapped in <p>, fix them.
text = text.replace(/<p>(<li.+?)<\/p>/g, '$1'); // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
text = text.replace(/<p><blockquote([^>]*)>/gi, '<blockquote$1><p>');
text = text.replace(/<\/blockquote><\/p>/g, '</p></blockquote>'); // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)', 'g'), '$1'); // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // Optionally insert line breaks.
if (br) {
// Replace newlines that shouldn't be touched with a placeholder.
text = text.replace(/<(script|style).*?<\/\\1>/g, match => match[0].replace(/\n/g, '<WPPreserveNewline />')); // Normalize <br>
text = text.replace(/<br>|<br\/>/g, '<br />'); // Replace any new line characters that aren't preceded by a <br /> with a <br />.
text = text.replace(/(<br \/>)?\s*\n/g, (a, b) => b ? a : '<br />\n'); // Replace newline placeholders with newlines.
text = text.replace(/<WPPreserveNewline \/>/g, '\n');
} // If a <br /> tag is after an opening or closing block tag, remove it.
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*<br />', 'g'), '$1'); // If a <br /> tag is before a subset of opening or closing block tags, remove it.
text = text.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)/g, '$1');
text = text.replace(/\n<\/p>$/g, '</p>'); // Replace placeholder <pre> tags with their original content.
preTags.forEach(preTag => {
const [name, original] = preTag;
text = text.replace(name, original);
}); // Restore newlines in all elements.
if (-1 !== text.indexOf('<!-- wpnl -->')) {
text = text.replace(/\s?<!-- wpnl -->\s?/g, '\n');
}
return text;
}
/**
* Replaces `<p>` tags with two line breaks. "Opposite" of autop().
*
* Replaces `<p>` tags with two line breaks except where the `<p>` has attributes.
* Unifies whitespace. Indents `<li>`, `<dt>` and `<dd>` for better readability.
*
* @param {string} html The content from the editor.
*
* @example
* ```js
* import { removep } from '@wordpress/autop';
* removep( '<p>my text</p>' ); // "my text"
* ```
*
* @return {string} The content with stripped paragraph tags.
*/
function removep(html) {
const blocklist = 'blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure';
const blocklist1 = blocklist + '|div|p';
const blocklist2 = blocklist + '|pre';
/** @type {string[]} */
const preserve = [];
let preserveLinebreaks = false;
let preserveBr = false;
if (!html) {
return '';
} // Protect script and style tags.
if (html.indexOf('<script') !== -1 || html.indexOf('<style') !== -1) {
html = html.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g, match => {
preserve.push(match);
return '<wp-preserve>';
});
} // Protect pre tags.
if (html.indexOf('<pre') !== -1) {
preserveLinebreaks = true;
html = html.replace(/<pre[^>]*>[\s\S]+?<\/pre>/g, a => {
a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp-line-break>');
a = a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-line-break>');
return a.replace(/\r?\n/g, '<wp-line-break>');
});
} // Remove line breaks but keep <br> tags inside image captions.
if (html.indexOf('[caption') !== -1) {
preserveBr = true;
html = html.replace(/\[caption[\s\S]+?\[\/caption\]/g, a => {
return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, '');
});
} // Normalize white space characters before and after block tags.
html = html.replace(new RegExp('\\s*</(' + blocklist1 + ')>\\s*', 'g'), '</$1>\n');
html = html.replace(new RegExp('\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g'), '\n<$1>'); // Mark </p> if it has any attributes.
html = html.replace(/(<p [^>]+>[\s\S]*?)<\/p>/g, '$1</p#>'); // Preserve the first <p> inside a <div>.
html = html.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n'); // Remove paragraph tags.
html = html.replace(/\s*<p>/gi, '');
html = html.replace(/\s*<\/p>\s*/gi, '\n\n'); // Normalize white space chars and remove multiple line breaks.
html = html.replace(/\n[\s\u00a0]+\n/g, '\n\n'); // Replace <br> tags with line breaks.
html = html.replace(/(\s*)<br ?\/?>\s*/gi, (_, space) => {
if (space && space.indexOf('\n') !== -1) {
return '\n\n';
}
return '\n';
}); // Fix line breaks around <div>.
html = html.replace(/\s*<div/g, '\n<div');
html = html.replace(/<\/div>\s*/g, '</div>\n'); // Fix line breaks around caption shortcodes.
html = html.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
html = html.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption'); // Pad block elements tags with a line break.
html = html.replace(new RegExp('\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
html = html.replace(new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g'), '</$1>\n'); // Indent <li>, <dt> and <dd> tags.
html = html.replace(/<((li|dt|dd)[^>]*)>/g, ' \t<$1>'); // Fix line breaks around <select> and <option>.
if (html.indexOf('<option') !== -1) {
html = html.replace(/\s*<option/g, '\n<option');
html = html.replace(/\s*<\/select>/g, '\n</select>');
} // Pad <hr> with two line breaks.
if (html.indexOf('<hr') !== -1) {
html = html.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
} // Remove line breaks in <object> tags.
if (html.indexOf('<object') !== -1) {
html = html.replace(/<object[\s\S]+?<\/object>/g, a => {
return a.replace(/[\r\n]+/g, '');
});
} // Unmark special paragraph closing tags.
html = html.replace(/<\/p#>/g, '</p>\n'); // Pad remaining <p> tags whit a line break.
html = html.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1'); // Trim.
html = html.replace(/^\s+/, '');
html = html.replace(/[\s\u00a0]+$/, '');
if (preserveLinebreaks) {
html = html.replace(/<wp-line-break>/g, '\n');
}
if (preserveBr) {
html = html.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
} // Restore preserved tags.
if (preserve.length) {
html = html.replace(/<wp-preserve>/g, () => {
return (
/** @type {string} */
preserve.shift()
);
});
}
return html;
}
/***/ })
/******/ });

2
wp-includes/js/dist/autop.min.js vendored Normal file

File diff suppressed because one or more lines are too long

185
wp-includes/js/dist/blob.js vendored Normal file
View file

@ -0,0 +1,185 @@
this["wp"] = this["wp"] || {}; this["wp"]["blob"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "ca5x");
/******/ })
/************************************************************************/
/******/ ({
/***/ "ca5x":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBlobURL", function() { return createBlobURL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBlobByURL", function() { return getBlobByURL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBlobTypeByURL", function() { return getBlobTypeByURL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeBlobURL", function() { return revokeBlobURL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBlobURL", function() { return isBlobURL; });
/**
* Browser dependencies
*/
const {
createObjectURL,
revokeObjectURL
} = window.URL;
/**
* @type {Record<string, File|undefined>}
*/
const cache = {};
/**
* Create a blob URL from a file.
*
* @param {File} file The file to create a blob URL for.
*
* @return {string} The blob URL.
*/
function createBlobURL(file) {
const url = createObjectURL(file);
cache[url] = file;
return url;
}
/**
* Retrieve a file based on a blob URL. The file must have been created by
* `createBlobURL` and not removed by `revokeBlobURL`, otherwise it will return
* `undefined`.
*
* @param {string} url The blob URL.
*
* @return {File|undefined} The file for the blob URL.
*/
function getBlobByURL(url) {
return cache[url];
}
/**
* Retrieve a blob type based on URL. The file must have been created by
* `createBlobURL` and not removed by `revokeBlobURL`, otherwise it will return
* `undefined`.
*
* @param {string} url The blob URL.
*
* @return {string|undefined} The blob type.
*/
function getBlobTypeByURL(url) {
var _getBlobByURL;
return (_getBlobByURL = getBlobByURL(url)) === null || _getBlobByURL === void 0 ? void 0 : _getBlobByURL.type.split('/')[0]; // 0: media type , 1: file extension eg ( type: 'image/jpeg' ).
}
/**
* Remove the resource and file cache from memory.
*
* @param {string} url The blob URL.
*/
function revokeBlobURL(url) {
if (cache[url]) {
revokeObjectURL(url);
}
delete cache[url];
}
/**
* Check whether a url is a blob url.
*
* @param {string} url The URL.
*
* @return {boolean} Is the url a blob url?
*/
function isBlobURL(url) {
if (!url || !url.indexOf) {
return false;
}
return url.indexOf('blob:') === 0;
}
/***/ })
/******/ });

2
wp-includes/js/dist/blob.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.blob=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s="ca5x")}({ca5x:function(e,t,n){"use strict";n.r(t),n.d(t,"createBlobURL",(function(){return i})),n.d(t,"getBlobByURL",(function(){return c})),n.d(t,"getBlobTypeByURL",(function(){return f})),n.d(t,"revokeBlobURL",(function(){return l})),n.d(t,"isBlobURL",(function(){return d}));const{createObjectURL:r,revokeObjectURL:o}=window.URL,u={};function i(e){const t=r(e);return u[t]=e,t}function c(e){return u[e]}function f(e){var t;return null===(t=c(e))||void 0===t?void 0:t.type.split("/")[0]}function l(e){u[e]&&o(e),delete u[e]}function d(e){return!(!e||!e.indexOf)&&0===e.indexOf("blob:")}}});

1992
wp-includes/js/dist/block-directory.js vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

40059
wp-includes/js/dist/block-editor.js vendored Normal file

File diff suppressed because it is too large Load diff

12
wp-includes/js/dist/block-editor.min.js vendored Normal file

File diff suppressed because one or more lines are too long

34090
wp-includes/js/dist/block-library.js vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,463 @@
this["wp"] = this["wp"] || {}; this["wp"]["blockSerializationDefaultParser"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "SiJt");
/******/ })
/************************************************************************/
/******/ ({
/***/ "SiJt":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
let document;
let offset;
let output;
let stack;
/**
* Matches block comment delimiters
*
* While most of this pattern is straightforward the attribute parsing
* incorporates a tricks to make sure we don't choke on specific input
*
* - since JavaScript has no possessive quantifier or atomic grouping
* we are emulating it with a trick
*
* we want a possessive quantifier or atomic group to prevent backtracking
* on the `}`s should we fail to match the remainder of the pattern
*
* we can emulate this with a positive lookahead and back reference
* (a++)*c === ((?=(a+))\1)*c
*
* let's examine an example:
* - /(a+)*c/.test('aaaaaaaaaaaaad') fails after over 49,000 steps
* - /(a++)*c/.test('aaaaaaaaaaaaad') fails after 85 steps
* - /(?>a+)*c/.test('aaaaaaaaaaaaad') fails after 126 steps
*
* this is because the possessive `++` and the atomic group `(?>)`
* tell the engine that all those `a`s belong together as a single group
* and so it won't split it up when stepping backwards to try and match
*
* if we use /((?=(a+))\1)*c/ then we get the same behavior as the atomic group
* or possessive and prevent the backtracking because the `a+` is matched but
* not captured. thus, we find the long string of `a`s and remember it, then
* reference it as a whole unit inside our pattern
*
* @see http://instanceof.me/post/52245507631/regex-emulate-atomic-grouping-with-lookahead
* @see http://blog.stevenlevithan.com/archives/mimic-atomic-groups
* @see https://javascript.info/regexp-infinite-backtracking-problem
*
* once browsers reliably support atomic grouping or possessive
* quantifiers natively we should remove this trick and simplify
*
* @type {RegExp}
*
* @since 3.8.0
* @since 4.6.1 added optimization to prevent backtracking on attribute parsing
*/
const tokenizer = /<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g;
function Block(blockName, attrs, innerBlocks, innerHTML, innerContent) {
return {
blockName,
attrs,
innerBlocks,
innerHTML,
innerContent
};
}
function Freeform(innerHTML) {
return Block(null, {}, [], innerHTML, [innerHTML]);
}
function Frame(block, tokenStart, tokenLength, prevOffset, leadingHtmlStart) {
return {
block,
tokenStart,
tokenLength,
prevOffset: prevOffset || tokenStart + tokenLength,
leadingHtmlStart
};
}
/**
* Parser function, that converts input HTML into a block based structure.
*
* @param {string} doc The HTML document to parse.
*
* @example
* Input post:
* ```html
* <!-- wp:columns {"columns":3} -->
* <div class="wp-block-columns has-3-columns"><!-- wp:column -->
* <div class="wp-block-column"><!-- wp:paragraph -->
* <p>Left</p>
* <!-- /wp:paragraph --></div>
* <!-- /wp:column -->
*
* <!-- wp:column -->
* <div class="wp-block-column"><!-- wp:paragraph -->
* <p><strong>Middle</strong></p>
* <!-- /wp:paragraph --></div>
* <!-- /wp:column -->
*
* <!-- wp:column -->
* <div class="wp-block-column"></div>
* <!-- /wp:column --></div>
* <!-- /wp:columns -->
* ```
*
* Parsing code:
* ```js
* import { parse } from '@wordpress/block-serialization-default-parser';
*
* parse( post ) === [
* {
* blockName: "core/columns",
* attrs: {
* columns: 3
* },
* innerBlocks: [
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [
* {
* blockName: "core/paragraph",
* attrs: null,
* innerBlocks: [],
* innerHTML: "\n<p>Left</p>\n"
* }
* ],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* },
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [
* {
* blockName: "core/paragraph",
* attrs: null,
* innerBlocks: [],
* innerHTML: "\n<p><strong>Middle</strong></p>\n"
* }
* ],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* },
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* }
* ],
* innerHTML: '\n<div class="wp-block-columns has-3-columns">\n\n\n\n</div>\n'
* }
* ];
* ```
* @return {Array} A block-based representation of the input HTML.
*/
const parse = doc => {
document = doc;
offset = 0;
output = [];
stack = [];
tokenizer.lastIndex = 0;
do {// twiddle our thumbs
} while (proceed());
return output;
};
function proceed() {
const next = nextToken();
const [tokenType, blockName, attrs, startOffset, tokenLength] = next;
const stackDepth = stack.length; // we may have some HTML soup before the next block
const leadingHtmlStart = startOffset > offset ? offset : null;
switch (tokenType) {
case 'no-more-tokens':
// if not in a block then flush output
if (0 === stackDepth) {
addFreeform();
return false;
} // Otherwise we have a problem
// This is an error
// we have options
// - treat it all as freeform text
// - assume an implicit closer (easiest when not nesting)
// for the easy case we'll assume an implicit closer
if (1 === stackDepth) {
addBlockFromStack();
return false;
} // for the nested case where it's more difficult we'll
// have to assume that multiple closers are missing
// and so we'll collapse the whole stack piecewise
while (0 < stack.length) {
addBlockFromStack();
}
return false;
case 'void-block':
// easy case is if we stumbled upon a void block
// in the top-level of the document
if (0 === stackDepth) {
if (null !== leadingHtmlStart) {
output.push(Freeform(document.substr(leadingHtmlStart, startOffset - leadingHtmlStart)));
}
output.push(Block(blockName, attrs, [], '', []));
offset = startOffset + tokenLength;
return true;
} // otherwise we found an inner block
addInnerBlock(Block(blockName, attrs, [], '', []), startOffset, tokenLength);
offset = startOffset + tokenLength;
return true;
case 'block-opener':
// track all newly-opened blocks on the stack
stack.push(Frame(Block(blockName, attrs, [], '', []), startOffset, tokenLength, startOffset + tokenLength, leadingHtmlStart));
offset = startOffset + tokenLength;
return true;
case 'block-closer':
// if we're missing an opener we're in trouble
// This is an error
if (0 === stackDepth) {
// we have options
// - assume an implicit opener
// - assume _this_ is the opener
// - give up and close out the document
addFreeform();
return false;
} // if we're not nesting then this is easy - close the block
if (1 === stackDepth) {
addBlockFromStack(startOffset);
offset = startOffset + tokenLength;
return true;
} // otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent
const stackTop = stack.pop();
const html = document.substr(stackTop.prevOffset, startOffset - stackTop.prevOffset);
stackTop.block.innerHTML += html;
stackTop.block.innerContent.push(html);
stackTop.prevOffset = startOffset + tokenLength;
addInnerBlock(stackTop.block, stackTop.tokenStart, stackTop.tokenLength, startOffset + tokenLength);
offset = startOffset + tokenLength;
return true;
default:
// This is an error
addFreeform();
return false;
}
}
/**
* Parse JSON if valid, otherwise return null
*
* Note that JSON coming from the block comment
* delimiters is constrained to be an object
* and cannot be things like `true` or `null`
*
* @param {string} input JSON input string to parse
* @return {Object|null} parsed JSON if valid
*/
function parseJSON(input) {
try {
return JSON.parse(input);
} catch (e) {
return null;
}
}
function nextToken() {
// aye the magic
// we're using a single RegExp to tokenize the block comment delimiters
// we're also using a trick here because the only difference between a
// block opener and a block closer is the leading `/` before `wp:` (and
// a closer has no attributes). we can trap them both and process the
// match back in JavaScript to see which one it was.
const matches = tokenizer.exec(document); // we have no more tokens
if (null === matches) {
return ['no-more-tokens'];
}
const startedAt = matches.index;
const [match, closerMatch, namespaceMatch, nameMatch, attrsMatch
/* internal/unused */
,, voidMatch] = matches;
const length = match.length;
const isCloser = !!closerMatch;
const isVoid = !!voidMatch;
const namespace = namespaceMatch || 'core/';
const name = namespace + nameMatch;
const hasAttrs = !!attrsMatch;
const attrs = hasAttrs ? parseJSON(attrsMatch) : {}; // This state isn't allowed
// This is an error
if (isCloser && (isVoid || hasAttrs)) {// we can ignore them since they don't hurt anything
// we may warn against this at some point or reject it
}
if (isVoid) {
return ['void-block', name, attrs, startedAt, length];
}
if (isCloser) {
return ['block-closer', name, null, startedAt, length];
}
return ['block-opener', name, attrs, startedAt, length];
}
function addFreeform(rawLength) {
const length = rawLength ? rawLength : document.length - offset;
if (0 === length) {
return;
}
output.push(Freeform(document.substr(offset, length)));
}
function addInnerBlock(block, tokenStart, tokenLength, lastOffset) {
const parent = stack[stack.length - 1];
parent.block.innerBlocks.push(block);
const html = document.substr(parent.prevOffset, tokenStart - parent.prevOffset);
if (html) {
parent.block.innerHTML += html;
parent.block.innerContent.push(html);
}
parent.block.innerContent.push(null);
parent.prevOffset = lastOffset ? lastOffset : tokenStart + tokenLength;
}
function addBlockFromStack(endOffset) {
const {
block,
leadingHtmlStart,
prevOffset,
tokenStart
} = stack.pop();
const html = endOffset ? document.substr(prevOffset, endOffset - prevOffset) : document.substr(prevOffset);
if (html) {
block.innerHTML += html;
block.innerContent.push(html);
}
if (null !== leadingHtmlStart) {
output.push(Freeform(document.substr(leadingHtmlStart, tokenStart - leadingHtmlStart)));
}
output.push(block);
}
/***/ })
/******/ });

View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.blockSerializationDefaultParser=function(n){var t={};function e(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return n[r].call(o.exports,o,o.exports,e),o.l=!0,o.exports}return e.m=n,e.c=t,e.d=function(n,t,r){e.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:r})},e.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},e.t=function(n,t){if(1&t&&(n=e(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var r=Object.create(null);if(e.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)e.d(r,o,function(t){return n[t]}.bind(null,o));return r},e.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return e.d(t,"a",t),t},e.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},e.p="",e(e.s="SiJt")}({SiJt:function(n,t,e){"use strict";let r,o,u,s;e.r(t),e.d(t,"parse",(function(){return f}));const l=/<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g;function c(n,t,e,r,o){return{blockName:n,attrs:t,innerBlocks:e,innerHTML:r,innerContent:o}}function i(n){return c(null,{},[],n,[n])}const f=n=>{r=n,o=0,u=[],s=[],l.lastIndex=0;do{}while(p());return u};function p(){const n=function(){const n=l.exec(r);if(null===n)return["no-more-tokens"];const t=n.index,[e,o,u,s,c,,i]=n,f=e.length,p=!!o,a=!!i,b=(u||"core/")+s,k=!!c,d=k?function(n){try{return JSON.parse(n)}catch(n){return null}}(c):{};if(a)return["void-block",b,d,t,f];if(p)return["block-closer",b,null,t,f];return["block-opener",b,d,t,f]}(),[t,e,f,p,d]=n,h=s.length,v=p>o?o:null;switch(t){case"no-more-tokens":if(0===h)return a(),!1;if(1===h)return k(),!1;for(;0<s.length;)k();return!1;case"void-block":return 0===h?(null!==v&&u.push(i(r.substr(v,p-v))),u.push(c(e,f,[],"",[])),o=p+d,!0):(b(c(e,f,[],"",[]),p,d),o=p+d,!0);case"block-opener":return s.push(function(n,t,e,r,o){return{block:n,tokenStart:t,tokenLength:e,prevOffset:r||t+e,leadingHtmlStart:o}}(c(e,f,[],"",[]),p,d,p+d,v)),o=p+d,!0;case"block-closer":if(0===h)return a(),!1;if(1===h)return k(p),o=p+d,!0;const n=s.pop(),t=r.substr(n.prevOffset,p-n.prevOffset);return n.block.innerHTML+=t,n.block.innerContent.push(t),n.prevOffset=p+d,b(n.block,n.tokenStart,n.tokenLength,p+d),o=p+d,!0;default:return a(),!1}}function a(n){const t=n||r.length-o;0!==t&&u.push(i(r.substr(o,t)))}function b(n,t,e,o){const u=s[s.length-1];u.block.innerBlocks.push(n);const l=r.substr(u.prevOffset,t-u.prevOffset);l&&(u.block.innerHTML+=l,u.block.innerContent.push(l)),u.block.innerContent.push(null),u.prevOffset=o||t+e}function k(n){const{block:t,leadingHtmlStart:e,prevOffset:o,tokenStart:l}=s.pop(),c=n?r.substr(o,n-o):r.substr(o);c&&(t.innerHTML+=c,t.innerContent.push(c)),null!==e&&u.push(i(r.substr(e,l-e))),u.push(t)}}});

14083
wp-includes/js/dist/blocks.js vendored Normal file

File diff suppressed because one or more lines are too long

3
wp-includes/js/dist/blocks.min.js vendored Normal file

File diff suppressed because one or more lines are too long

60026
wp-includes/js/dist/components.js vendored Normal file

File diff suppressed because it is too large Load diff

31
wp-includes/js/dist/components.min.js vendored Normal file

File diff suppressed because one or more lines are too long

4316
wp-includes/js/dist/compose.js vendored Normal file

File diff suppressed because it is too large Load diff

9
wp-includes/js/dist/compose.min.js vendored Normal file

File diff suppressed because one or more lines are too long

5376
wp-includes/js/dist/core-data.js vendored Normal file

File diff suppressed because it is too large Load diff

2
wp-includes/js/dist/core-data.min.js vendored Normal file

File diff suppressed because one or more lines are too long

2933
wp-includes/js/dist/customize-widgets.js vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

272
wp-includes/js/dist/data-controls.js vendored Normal file
View file

@ -0,0 +1,272 @@
this["wp"] = this["wp"] || {}; this["wp"]["dataControls"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "71Oy");
/******/ })
/************************************************************************/
/******/ ({
/***/ "1ZqX":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["data"]; }());
/***/ }),
/***/ "71Oy":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "apiFetch", function() { return apiFetch; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "select", function() { return select; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "syncSelect", function() { return syncSelect; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispatch", function() { return dispatch; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__unstableAwaitPromise", function() { return __unstableAwaitPromise; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "controls", function() { return controls; });
/* harmony import */ var _wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("ywyh");
/* harmony import */ var _wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _wordpress_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("1ZqX");
/* harmony import */ var _wordpress_data__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_wordpress_data__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _wordpress_deprecated__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("NMb1");
/* harmony import */ var _wordpress_deprecated__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_wordpress_deprecated__WEBPACK_IMPORTED_MODULE_2__);
/**
* WordPress dependencies
*/
/**
* Dispatches a control action for triggering an api fetch call.
*
* @param {Object} request Arguments for the fetch request.
*
* @example
* ```js
* import { apiFetch } from '@wordpress/data-controls';
*
* // Action generator using apiFetch
* export function* myAction() {
* const path = '/v2/my-api/items';
* const items = yield apiFetch( { path } );
* // do something with the items.
* }
* ```
*
* @return {Object} The control descriptor.
*/
function apiFetch(request) {
return {
type: 'API_FETCH',
request
};
}
/**
* Control for resolving a selector in a registered data store.
* Alias for the `resolveSelect` built-in control in the `@wordpress/data` package.
*
* @param {Array} args Arguments passed without change to the `@wordpress/data` control.
*/
function select(...args) {
_wordpress_deprecated__WEBPACK_IMPORTED_MODULE_2___default()('`select` control in `@wordpress/data-controls`', {
since: '5.7',
alternative: 'built-in `resolveSelect` control in `@wordpress/data`'
});
return _wordpress_data__WEBPACK_IMPORTED_MODULE_1__["controls"].resolveSelect(...args);
}
/**
* Control for calling a selector in a registered data store.
* Alias for the `select` built-in control in the `@wordpress/data` package.
*
* @param {Array} args Arguments passed without change to the `@wordpress/data` control.
*/
function syncSelect(...args) {
_wordpress_deprecated__WEBPACK_IMPORTED_MODULE_2___default()('`syncSelect` control in `@wordpress/data-controls`', {
since: '5.7',
alternative: 'built-in `select` control in `@wordpress/data`'
});
return _wordpress_data__WEBPACK_IMPORTED_MODULE_1__["controls"].select(...args);
}
/**
* Control for dispatching an action in a registered data store.
* Alias for the `dispatch` control in the `@wordpress/data` package.
*
* @param {Array} args Arguments passed without change to the `@wordpress/data` control.
*/
function dispatch(...args) {
_wordpress_deprecated__WEBPACK_IMPORTED_MODULE_2___default()('`dispatch` control in `@wordpress/data-controls`', {
since: '5.7',
alternative: 'built-in `dispatch` control in `@wordpress/data`'
});
return _wordpress_data__WEBPACK_IMPORTED_MODULE_1__["controls"].dispatch(...args);
}
/**
* Dispatches a control action for awaiting on a promise to be resolved.
*
* @param {Object} promise Promise to wait for.
*
* @example
* ```js
* import { __unstableAwaitPromise } from '@wordpress/data-controls';
*
* // Action generator using apiFetch
* export function* myAction() {
* const promise = getItemsAsync();
* const items = yield __unstableAwaitPromise( promise );
* // do something with the items.
* }
* ```
*
* @return {Object} The control descriptor.
*/
const __unstableAwaitPromise = function (promise) {
return {
type: 'AWAIT_PROMISE',
promise
};
};
/**
* The default export is what you use to register the controls with your custom
* store.
*
* @example
* ```js
* // WordPress dependencies
* import { controls } from '@wordpress/data-controls';
* import { registerStore } from '@wordpress/data';
*
* // Internal dependencies
* import reducer from './reducer';
* import * as selectors from './selectors';
* import * as actions from './actions';
* import * as resolvers from './resolvers';
*
* registerStore( 'my-custom-store', {
* reducer,
* controls,
* actions,
* selectors,
* resolvers,
* } );
* ```
* @return {Object} An object for registering the default controls with the
* store.
*/
const controls = {
AWAIT_PROMISE: ({
promise
}) => promise,
API_FETCH({
request
}) {
return _wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0___default()(request);
}
};
/***/ }),
/***/ "NMb1":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["deprecated"]; }());
/***/ }),
/***/ "ywyh":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["apiFetch"]; }());
/***/ })
/******/ });

View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.dataControls=function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s="71Oy")}({"1ZqX":function(t,e){t.exports=window.wp.data},"71Oy":function(t,e,n){"use strict";n.r(e),n.d(e,"apiFetch",(function(){return s})),n.d(e,"select",(function(){return l})),n.d(e,"syncSelect",(function(){return a})),n.d(e,"dispatch",(function(){return d})),n.d(e,"__unstableAwaitPromise",(function(){return p})),n.d(e,"controls",(function(){return f}));var r=n("ywyh"),o=n.n(r),i=n("1ZqX"),c=n("NMb1"),u=n.n(c);function s(t){return{type:"API_FETCH",request:t}}function l(...t){return u()("`select` control in `@wordpress/data-controls`",{since:"5.7",alternative:"built-in `resolveSelect` control in `@wordpress/data`"}),i.controls.resolveSelect(...t)}function a(...t){return u()("`syncSelect` control in `@wordpress/data-controls`",{since:"5.7",alternative:"built-in `select` control in `@wordpress/data`"}),i.controls.select(...t)}function d(...t){return u()("`dispatch` control in `@wordpress/data-controls`",{since:"5.7",alternative:"built-in `dispatch` control in `@wordpress/data`"}),i.controls.dispatch(...t)}const p=function(t){return{type:"AWAIT_PROMISE",promise:t}},f={AWAIT_PROMISE:({promise:t})=>t,API_FETCH:({request:t})=>o()(t)}},NMb1:function(t,e){t.exports=window.wp.deprecated},ywyh:function(t,e){t.exports=window.wp.apiFetch}});

3969
wp-includes/js/dist/data.js vendored Normal file

File diff suppressed because it is too large Load diff

2
wp-includes/js/dist/data.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1740
wp-includes/js/dist/date.js vendored Normal file

File diff suppressed because one or more lines are too long

12
wp-includes/js/dist/date.min.js vendored Normal file

File diff suppressed because one or more lines are too long

191
wp-includes/js/dist/deprecated.js vendored Normal file
View file

@ -0,0 +1,191 @@
this["wp"] = this["wp"] || {}; this["wp"]["deprecated"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "+BeG");
/******/ })
/************************************************************************/
/******/ ({
/***/ "+BeG":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logged", function() { return logged; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return deprecated; });
/* harmony import */ var _wordpress_hooks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("g56x");
/* harmony import */ var _wordpress_hooks__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_hooks__WEBPACK_IMPORTED_MODULE_0__);
/**
* WordPress dependencies
*/
/**
* Object map tracking messages which have been logged, for use in ensuring a
* message is only logged once.
*
* @type {Record<string, true | undefined>}
*/
const logged = Object.create(null);
/**
* Logs a message to notify developers about a deprecated feature.
*
* @param {string} feature Name of the deprecated feature.
* @param {Object} [options] Personalisation options
* @param {string} [options.since] Version in which the feature was deprecated.
* @param {string} [options.version] Version in which the feature will be removed.
* @param {string} [options.alternative] Feature to use instead
* @param {string} [options.plugin] Plugin name if it's a plugin feature
* @param {string} [options.link] Link to documentation
* @param {string} [options.hint] Additional message to help transition away from the deprecated feature.
*
* @example
* ```js
* import deprecated from '@wordpress/deprecated';
*
* deprecated( 'Eating meat', {
* since: '2019.01.01'
* version: '2020.01.01',
* alternative: 'vegetables',
* plugin: 'the earth',
* hint: 'You may find it beneficial to transition gradually.',
* } );
*
* // Logs: 'Eating meat is deprecated since version 2019.01.01 and will be removed from the earth in version 2020.01.01. Please use vegetables instead. Note: You may find it beneficial to transition gradually.'
* ```
*/
function deprecated(feature, options = {}) {
const {
since,
version,
alternative,
plugin,
link,
hint
} = options;
const pluginMessage = plugin ? ` from ${plugin}` : '';
const sinceMessage = since ? ` since version ${since}` : '';
const versionMessage = version ? ` and will be removed${pluginMessage} in version ${version}` : '';
const useInsteadMessage = alternative ? ` Please use ${alternative} instead.` : '';
const linkMessage = link ? ` See: ${link}` : '';
const hintMessage = hint ? ` Note: ${hint}` : '';
const message = `${feature} is deprecated${sinceMessage}${versionMessage}.${useInsteadMessage}${linkMessage}${hintMessage}`; // Skip if already logged.
if (message in logged) {
return;
}
/**
* Fires whenever a deprecated feature is encountered
*
* @param {string} feature Name of the deprecated feature.
* @param {?Object} options Personalisation options
* @param {string} options.since Version in which the feature was deprecated.
* @param {?string} options.version Version in which the feature will be removed.
* @param {?string} options.alternative Feature to use instead
* @param {?string} options.plugin Plugin name if it's a plugin feature
* @param {?string} options.link Link to documentation
* @param {?string} options.hint Additional message to help transition away from the deprecated feature.
* @param {?string} message Message sent to console.warn
*/
Object(_wordpress_hooks__WEBPACK_IMPORTED_MODULE_0__["doAction"])('deprecated', feature, options, message); // eslint-disable-next-line no-console
console.warn(message);
logged[message] = true;
}
/** @typedef {import('utility-types').NonUndefined<Parameters<typeof deprecated>[1]>} DeprecatedOptions */
/***/ }),
/***/ "g56x":
/***/ (function(module, exports) {
(function() { module.exports = window["wp"]["hooks"]; }());
/***/ })
/******/ })["default"];

2
wp-includes/js/dist/deprecated.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.deprecated=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s="+BeG")}({"+BeG":function(e,t,n){"use strict";n.r(t),n.d(t,"logged",(function(){return o})),n.d(t,"default",(function(){return i}));var r=n("g56x");const o=Object.create(null);function i(e,t={}){const{since:n,version:i,alternative:u,plugin:c,link:l,hint:f}=t,a=`${e} is deprecated${n?" since version "+n:""}${i?` and will be removed${c?" from "+c:""} in version ${i}`:""}.${u?` Please use ${u} instead.`:""}${l?" See: "+l:""}${f?" Note: "+f:""}`;a in o||(Object(r.doAction)("deprecated",e,t,a),console.warn(a),o[a]=!0)}},g56x:function(e,t){e.exports=window.wp.hooks}}).default;

144
wp-includes/js/dist/dom-ready.js vendored Normal file
View file

@ -0,0 +1,144 @@
this["wp"] = this["wp"] || {}; this["wp"]["domReady"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "2oG7");
/******/ })
/************************************************************************/
/******/ ({
/***/ "2oG7":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return domReady; });
/**
* @typedef {() => void} Callback
*
* TODO: Remove this typedef and inline `() => void` type.
*
* This typedef is used so that a descriptive type is provided in our
* automatically generated documentation.
*
* An in-line type `() => void` would be preferable, but the generated
* documentation is `null` in that case.
*
* @see https://github.com/WordPress/gutenberg/issues/18045
*/
/**
* Specify a function to execute when the DOM is fully loaded.
*
* @param {Callback} callback A function to execute after the DOM is ready.
*
* @example
* ```js
* import domReady from '@wordpress/dom-ready';
*
* domReady( function() {
* //do something after DOM loads.
* } );
* ```
*
* @return {void}
*/
function domReady(callback) {
if (typeof document === 'undefined') {
return;
}
if (document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly.
document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly.
) {
return void callback();
} // DOMContentLoaded has not fired yet, delay callback until then.
document.addEventListener('DOMContentLoaded', callback);
}
/***/ })
/******/ })["default"];

2
wp-includes/js/dist/dom-ready.min.js vendored Normal file
View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.domReady=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s="2oG7")}({"2oG7":function(e,t,n){"use strict";function r(e){"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",e):e())}n.r(t),n.d(t,"default",(function(){return r}))}}).default;

2081
wp-includes/js/dist/dom.js vendored Normal file

File diff suppressed because it is too large Load diff

2
wp-includes/js/dist/dom.min.js vendored Normal file

File diff suppressed because one or more lines are too long

19016
wp-includes/js/dist/edit-post.js vendored Normal file

File diff suppressed because it is too large Load diff

49
wp-includes/js/dist/edit-post.min.js vendored Normal file

File diff suppressed because one or more lines are too long

4805
wp-includes/js/dist/edit-widgets.js vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

11925
wp-includes/js/dist/editor.js vendored Normal file

File diff suppressed because it is too large Load diff

12
wp-includes/js/dist/editor.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1370
wp-includes/js/dist/element.js vendored Normal file

File diff suppressed because it is too large Load diff

2
wp-includes/js/dist/element.min.js vendored Normal file

File diff suppressed because one or more lines are too long

249
wp-includes/js/dist/escape-html.js vendored Normal file
View file

@ -0,0 +1,249 @@
this["wp"] = this["wp"] || {}; this["wp"]["escapeHtml"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "IsfW");
/******/ })
/************************************************************************/
/******/ ({
/***/ "IsfW":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "escapeAmpersand", function() { return /* binding */ escapeAmpersand; });
__webpack_require__.d(__webpack_exports__, "escapeQuotationMark", function() { return /* binding */ escapeQuotationMark; });
__webpack_require__.d(__webpack_exports__, "escapeLessThan", function() { return /* binding */ escapeLessThan; });
__webpack_require__.d(__webpack_exports__, "escapeAttribute", function() { return /* binding */ escapeAttribute; });
__webpack_require__.d(__webpack_exports__, "escapeHTML", function() { return /* binding */ escapeHTML; });
__webpack_require__.d(__webpack_exports__, "escapeEditableHTML", function() { return /* binding */ escapeEditableHTML; });
__webpack_require__.d(__webpack_exports__, "isValidAttributeName", function() { return /* binding */ isValidAttributeName; });
// CONCATENATED MODULE: ./node_modules/@wordpress/escape-html/build-module/escape-greater.js
/**
* Returns a string with greater-than sign replaced.
*
* Note that if a resolution for Trac#45387 comes to fruition, it is no longer
* necessary for `__unstableEscapeGreaterThan` to exist.
*
* See: https://core.trac.wordpress.org/ticket/45387
*
* @param {string} value Original string.
*
* @return {string} Escaped string.
*/
function __unstableEscapeGreaterThan(value) {
return value.replace(/>/g, '&gt;');
}
// CONCATENATED MODULE: ./node_modules/@wordpress/escape-html/build-module/index.js
/**
* Internal dependencies
*/
/**
* Regular expression matching invalid attribute names.
*
* "Attribute names must consist of one or more characters other than controls,
* U+0020 SPACE, U+0022 ("), U+0027 ('), U+003E (>), U+002F (/), U+003D (=),
* and noncharacters."
*
* @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
*
* @type {RegExp}
*/
const REGEXP_INVALID_ATTRIBUTE_NAME = /[\u007F-\u009F "'>/="\uFDD0-\uFDEF]/;
/**
* Returns a string with ampersands escaped. Note that this is an imperfect
* implementation, where only ampersands which do not appear as a pattern of
* named, decimal, or hexadecimal character references are escaped. Invalid
* named references (i.e. ambiguous ampersand) are are still permitted.
*
* @see https://w3c.github.io/html/syntax.html#character-references
* @see https://w3c.github.io/html/syntax.html#ambiguous-ampersand
* @see https://w3c.github.io/html/syntax.html#named-character-references
*
* @param {string} value Original string.
*
* @return {string} Escaped string.
*/
function escapeAmpersand(value) {
return value.replace(/&(?!([a-z0-9]+|#[0-9]+|#x[a-f0-9]+);)/gi, '&amp;');
}
/**
* Returns a string with quotation marks replaced.
*
* @param {string} value Original string.
*
* @return {string} Escaped string.
*/
function escapeQuotationMark(value) {
return value.replace(/"/g, '&quot;');
}
/**
* Returns a string with less-than sign replaced.
*
* @param {string} value Original string.
*
* @return {string} Escaped string.
*/
function escapeLessThan(value) {
return value.replace(/</g, '&lt;');
}
/**
* Returns an escaped attribute value.
*
* @see https://w3c.github.io/html/syntax.html#elements-attributes
*
* "[...] the text cannot contain an ambiguous ampersand [...] must not contain
* any literal U+0022 QUOTATION MARK characters (")"
*
* Note we also escape the greater than symbol, as this is used by wptexturize to
* split HTML strings. This is a WordPress specific fix
*
* Note that if a resolution for Trac#45387 comes to fruition, it is no longer
* necessary for `__unstableEscapeGreaterThan` to be used.
*
* See: https://core.trac.wordpress.org/ticket/45387
*
* @param {string} value Attribute value.
*
* @return {string} Escaped attribute value.
*/
function escapeAttribute(value) {
return __unstableEscapeGreaterThan(escapeQuotationMark(escapeAmpersand(value)));
}
/**
* Returns an escaped HTML element value.
*
* @see https://w3c.github.io/html/syntax.html#writing-html-documents-elements
*
* "the text must not contain the character U+003C LESS-THAN SIGN (<) or an
* ambiguous ampersand."
*
* @param {string} value Element value.
*
* @return {string} Escaped HTML element value.
*/
function escapeHTML(value) {
return escapeLessThan(escapeAmpersand(value));
}
/**
* Returns an escaped Editable HTML element value. This is different from
* `escapeHTML`, because for editable HTML, ALL ampersands must be escaped in
* order to render the content correctly on the page.
*
* @param {string} value Element value.
*
* @return {string} Escaped HTML element value.
*/
function escapeEditableHTML(value) {
return escapeLessThan(value.replace(/&/g, '&amp;'));
}
/**
* Returns true if the given attribute name is valid, or false otherwise.
*
* @param {string} name Attribute name to test.
*
* @return {boolean} Whether attribute is valid.
*/
function isValidAttributeName(name) {
return !REGEXP_INVALID_ATTRIBUTE_NAME.test(name);
}
/***/ })
/******/ });

View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.escapeHtml=function(e){var t={};function n(r){if(t[r])return t[r].exports;var u=t[r]={i:r,l:!1,exports:{}};return e[r].call(u.exports,u,u.exports,n),u.l=!0,u.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var u in e)n.d(r,u,function(t){return e[t]}.bind(null,u));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s="IsfW")}({IsfW:function(e,t,n){"use strict";n.r(t),n.d(t,"escapeAmpersand",(function(){return u})),n.d(t,"escapeQuotationMark",(function(){return o})),n.d(t,"escapeLessThan",(function(){return i})),n.d(t,"escapeAttribute",(function(){return c})),n.d(t,"escapeHTML",(function(){return f})),n.d(t,"escapeEditableHTML",(function(){return a})),n.d(t,"isValidAttributeName",(function(){return p}));const r=/[\u007F-\u009F "'>/="\uFDD0-\uFDEF]/;function u(e){return e.replace(/&(?!([a-z0-9]+|#[0-9]+|#x[a-f0-9]+);)/gi,"&amp;")}function o(e){return e.replace(/"/g,"&quot;")}function i(e){return e.replace(/</g,"&lt;")}function c(e){return function(e){return e.replace(/>/g,"&gt;")}(o(u(e)))}function f(e){return i(u(e))}function a(e){return i(e.replace(/&/g,"&amp;"))}function p(e){return!r.test(e)}}});

1667
wp-includes/js/dist/format-library.js vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

691
wp-includes/js/dist/hooks.js vendored Normal file
View file

@ -0,0 +1,691 @@
this["wp"] = this["wp"] || {}; this["wp"]["hooks"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "gEOj");
/******/ })
/************************************************************************/
/******/ ({
/***/ "gEOj":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "defaultHooks", function() { return /* binding */ defaultHooks; });
__webpack_require__.d(__webpack_exports__, "createHooks", function() { return /* reexport */ build_module_createHooks; });
__webpack_require__.d(__webpack_exports__, "addAction", function() { return /* binding */ addAction; });
__webpack_require__.d(__webpack_exports__, "addFilter", function() { return /* binding */ addFilter; });
__webpack_require__.d(__webpack_exports__, "removeAction", function() { return /* binding */ removeAction; });
__webpack_require__.d(__webpack_exports__, "removeFilter", function() { return /* binding */ removeFilter; });
__webpack_require__.d(__webpack_exports__, "hasAction", function() { return /* binding */ hasAction; });
__webpack_require__.d(__webpack_exports__, "hasFilter", function() { return /* binding */ hasFilter; });
__webpack_require__.d(__webpack_exports__, "removeAllActions", function() { return /* binding */ removeAllActions; });
__webpack_require__.d(__webpack_exports__, "removeAllFilters", function() { return /* binding */ removeAllFilters; });
__webpack_require__.d(__webpack_exports__, "doAction", function() { return /* binding */ doAction; });
__webpack_require__.d(__webpack_exports__, "applyFilters", function() { return /* binding */ applyFilters; });
__webpack_require__.d(__webpack_exports__, "currentAction", function() { return /* binding */ currentAction; });
__webpack_require__.d(__webpack_exports__, "currentFilter", function() { return /* binding */ currentFilter; });
__webpack_require__.d(__webpack_exports__, "doingAction", function() { return /* binding */ doingAction; });
__webpack_require__.d(__webpack_exports__, "doingFilter", function() { return /* binding */ doingFilter; });
__webpack_require__.d(__webpack_exports__, "didAction", function() { return /* binding */ didAction; });
__webpack_require__.d(__webpack_exports__, "didFilter", function() { return /* binding */ didFilter; });
__webpack_require__.d(__webpack_exports__, "actions", function() { return /* binding */ actions; });
__webpack_require__.d(__webpack_exports__, "filters", function() { return /* binding */ filters; });
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/validateNamespace.js
/**
* Validate a namespace string.
*
* @param {string} namespace The namespace to validate - should take the form
* `vendor/plugin/function`.
*
* @return {boolean} Whether the namespace is valid.
*/
function validateNamespace(namespace) {
if ('string' !== typeof namespace || '' === namespace) {
// eslint-disable-next-line no-console
console.error('The namespace must be a non-empty string.');
return false;
}
if (!/^[a-zA-Z][a-zA-Z0-9_.\-\/]*$/.test(namespace)) {
// eslint-disable-next-line no-console
console.error('The namespace can only contain numbers, letters, dashes, periods, underscores and slashes.');
return false;
}
return true;
}
/* harmony default export */ var build_module_validateNamespace = (validateNamespace);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/validateHookName.js
/**
* Validate a hookName string.
*
* @param {string} hookName The hook name to validate. Should be a non empty string containing
* only numbers, letters, dashes, periods and underscores. Also,
* the hook name cannot begin with `__`.
*
* @return {boolean} Whether the hook name is valid.
*/
function validateHookName(hookName) {
if ('string' !== typeof hookName || '' === hookName) {
// eslint-disable-next-line no-console
console.error('The hook name must be a non-empty string.');
return false;
}
if (/^__/.test(hookName)) {
// eslint-disable-next-line no-console
console.error('The hook name cannot begin with `__`.');
return false;
}
if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(hookName)) {
// eslint-disable-next-line no-console
console.error('The hook name can only contain numbers, letters, dashes, periods and underscores.');
return false;
}
return true;
}
/* harmony default export */ var build_module_validateHookName = (validateHookName);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createAddHook.js
/**
* Internal dependencies
*/
/**
* @callback AddHook
*
* Adds the hook to the appropriate hooks container.
*
* @param {string} hookName Name of hook to add
* @param {string} namespace The unique namespace identifying the callback in the form `vendor/plugin/function`.
* @param {import('.').Callback} callback Function to call when the hook is run
* @param {number} [priority=10] Priority of this hook
*/
/**
* Returns a function which, when invoked, will add a hook.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {AddHook} Function that adds a new hook.
*/
function createAddHook(hooks, storeKey) {
return function addHook(hookName, namespace, callback, priority = 10) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
if (!build_module_validateNamespace(namespace)) {
return;
}
if ('function' !== typeof callback) {
// eslint-disable-next-line no-console
console.error('The hook callback must be a function.');
return;
} // Validate numeric priority
if ('number' !== typeof priority) {
// eslint-disable-next-line no-console
console.error('If specified, the hook priority must be a number.');
return;
}
const handler = {
callback,
priority,
namespace
};
if (hooksStore[hookName]) {
// Find the correct insert index of the new hook.
const handlers = hooksStore[hookName].handlers;
/** @type {number} */
let i;
for (i = handlers.length; i > 0; i--) {
if (priority >= handlers[i - 1].priority) {
break;
}
}
if (i === handlers.length) {
// If append, operate via direct assignment.
handlers[i] = handler;
} else {
// Otherwise, insert before index via splice.
handlers.splice(i, 0, handler);
} // We may also be currently executing this hook. If the callback
// we're adding would come after the current callback, there's no
// problem; otherwise we need to increase the execution index of
// any other runs by 1 to account for the added element.
hooksStore.__current.forEach(hookInfo => {
if (hookInfo.name === hookName && hookInfo.currentIndex >= i) {
hookInfo.currentIndex++;
}
});
} else {
// This is the first hook of its type.
hooksStore[hookName] = {
handlers: [handler],
runs: 0
};
}
if (hookName !== 'hookAdded') {
hooks.doAction('hookAdded', hookName, namespace, callback, priority);
}
};
}
/* harmony default export */ var build_module_createAddHook = (createAddHook);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createRemoveHook.js
/**
* Internal dependencies
*/
/**
* @callback RemoveHook
* Removes the specified callback (or all callbacks) from the hook with a given hookName
* and namespace.
*
* @param {string} hookName The name of the hook to modify.
* @param {string} namespace The unique namespace identifying the callback in the
* form `vendor/plugin/function`.
*
* @return {number | undefined} The number of callbacks removed.
*/
/**
* Returns a function which, when invoked, will remove a specified hook or all
* hooks by the given name.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
* @param {boolean} [removeAll=false] Whether to remove all callbacks for a hookName,
* without regard to namespace. Used to create
* `removeAll*` functions.
*
* @return {RemoveHook} Function that removes hooks.
*/
function createRemoveHook(hooks, storeKey, removeAll = false) {
return function removeHook(hookName, namespace) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
if (!removeAll && !build_module_validateNamespace(namespace)) {
return;
} // Bail if no hooks exist by this name
if (!hooksStore[hookName]) {
return 0;
}
let handlersRemoved = 0;
if (removeAll) {
handlersRemoved = hooksStore[hookName].handlers.length;
hooksStore[hookName] = {
runs: hooksStore[hookName].runs,
handlers: []
};
} else {
// Try to find the specified callback to remove.
const handlers = hooksStore[hookName].handlers;
for (let i = handlers.length - 1; i >= 0; i--) {
if (handlers[i].namespace === namespace) {
handlers.splice(i, 1);
handlersRemoved++; // This callback may also be part of a hook that is
// currently executing. If the callback we're removing
// comes after the current callback, there's no problem;
// otherwise we need to decrease the execution index of any
// other runs by 1 to account for the removed element.
hooksStore.__current.forEach(hookInfo => {
if (hookInfo.name === hookName && hookInfo.currentIndex >= i) {
hookInfo.currentIndex--;
}
});
}
}
}
if (hookName !== 'hookRemoved') {
hooks.doAction('hookRemoved', hookName, namespace);
}
return handlersRemoved;
};
}
/* harmony default export */ var build_module_createRemoveHook = (createRemoveHook);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createHasHook.js
/**
* @callback HasHook
*
* Returns whether any handlers are attached for the given hookName and optional namespace.
*
* @param {string} hookName The name of the hook to check for.
* @param {string} [namespace] Optional. The unique namespace identifying the callback
* in the form `vendor/plugin/function`.
*
* @return {boolean} Whether there are handlers that are attached to the given hook.
*/
/**
* Returns a function which, when invoked, will return whether any handlers are
* attached to a particular hook.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {HasHook} Function that returns whether any handlers are
* attached to a particular hook and optional namespace.
*/
function createHasHook(hooks, storeKey) {
return function hasHook(hookName, namespace) {
const hooksStore = hooks[storeKey]; // Use the namespace if provided.
if ('undefined' !== typeof namespace) {
return hookName in hooksStore && hooksStore[hookName].handlers.some(hook => hook.namespace === namespace);
}
return hookName in hooksStore;
};
}
/* harmony default export */ var build_module_createHasHook = (createHasHook);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createRunHook.js
/**
* Returns a function which, when invoked, will execute all callbacks
* registered to a hook of the specified type, optionally returning the final
* value of the call chain.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
* @param {boolean} [returnFirstArg=false] Whether each hook callback is expected to
* return its first argument.
*
* @return {(hookName:string, ...args: unknown[]) => unknown} Function that runs hook callbacks.
*/
function createRunHook(hooks, storeKey, returnFirstArg = false) {
return function runHooks(hookName, ...args) {
const hooksStore = hooks[storeKey];
if (!hooksStore[hookName]) {
hooksStore[hookName] = {
handlers: [],
runs: 0
};
}
hooksStore[hookName].runs++;
const handlers = hooksStore[hookName].handlers; // The following code is stripped from production builds.
if (false) {}
if (!handlers || !handlers.length) {
return returnFirstArg ? args[0] : undefined;
}
const hookInfo = {
name: hookName,
currentIndex: 0
};
hooksStore.__current.push(hookInfo);
while (hookInfo.currentIndex < handlers.length) {
const handler = handlers[hookInfo.currentIndex];
const result = handler.callback.apply(null, args);
if (returnFirstArg) {
args[0] = result;
}
hookInfo.currentIndex++;
}
hooksStore.__current.pop();
if (returnFirstArg) {
return args[0];
}
};
}
/* harmony default export */ var build_module_createRunHook = (createRunHook);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createCurrentHook.js
/**
* Returns a function which, when invoked, will return the name of the
* currently running hook, or `null` if no hook of the given type is currently
* running.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {() => string | null} Function that returns the current hook name or null.
*/
function createCurrentHook(hooks, storeKey) {
return function currentHook() {
var _hooksStore$__current, _hooksStore$__current2;
const hooksStore = hooks[storeKey];
return (_hooksStore$__current = (_hooksStore$__current2 = hooksStore.__current[hooksStore.__current.length - 1]) === null || _hooksStore$__current2 === void 0 ? void 0 : _hooksStore$__current2.name) !== null && _hooksStore$__current !== void 0 ? _hooksStore$__current : null;
};
}
/* harmony default export */ var build_module_createCurrentHook = (createCurrentHook);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createDoingHook.js
/**
* @callback DoingHook
* Returns whether a hook is currently being executed.
*
* @param {string} [hookName] The name of the hook to check for. If
* omitted, will check for any hook being executed.
*
* @return {boolean} Whether the hook is being executed.
*/
/**
* Returns a function which, when invoked, will return whether a hook is
* currently being executed.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {DoingHook} Function that returns whether a hook is currently
* being executed.
*/
function createDoingHook(hooks, storeKey) {
return function doingHook(hookName) {
const hooksStore = hooks[storeKey]; // If the hookName was not passed, check for any current hook.
if ('undefined' === typeof hookName) {
return 'undefined' !== typeof hooksStore.__current[0];
} // Return the __current hook.
return hooksStore.__current[0] ? hookName === hooksStore.__current[0].name : false;
};
}
/* harmony default export */ var build_module_createDoingHook = (createDoingHook);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createDidHook.js
/**
* Internal dependencies
*/
/**
* @callback DidHook
*
* Returns the number of times an action has been fired.
*
* @param {string} hookName The hook name to check.
*
* @return {number | undefined} The number of times the hook has run.
*/
/**
* Returns a function which, when invoked, will return the number of times a
* hook has been called.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {DidHook} Function that returns a hook's call count.
*/
function createDidHook(hooks, storeKey) {
return function didHook(hookName) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
return hooksStore[hookName] && hooksStore[hookName].runs ? hooksStore[hookName].runs : 0;
};
}
/* harmony default export */ var build_module_createDidHook = (createDidHook);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createHooks.js
/**
* Internal dependencies
*/
/**
* Internal class for constructing hooks. Use `createHooks()` function
*
* Note, it is necessary to expose this class to make its type public.
*
* @private
*/
class createHooks_Hooks {
constructor() {
/** @type {import('.').Store} actions */
this.actions = Object.create(null);
this.actions.__current = [];
/** @type {import('.').Store} filters */
this.filters = Object.create(null);
this.filters.__current = [];
this.addAction = build_module_createAddHook(this, 'actions');
this.addFilter = build_module_createAddHook(this, 'filters');
this.removeAction = build_module_createRemoveHook(this, 'actions');
this.removeFilter = build_module_createRemoveHook(this, 'filters');
this.hasAction = build_module_createHasHook(this, 'actions');
this.hasFilter = build_module_createHasHook(this, 'filters');
this.removeAllActions = build_module_createRemoveHook(this, 'actions', true);
this.removeAllFilters = build_module_createRemoveHook(this, 'filters', true);
this.doAction = build_module_createRunHook(this, 'actions');
this.applyFilters = build_module_createRunHook(this, 'filters', true);
this.currentAction = build_module_createCurrentHook(this, 'actions');
this.currentFilter = build_module_createCurrentHook(this, 'filters');
this.doingAction = build_module_createDoingHook(this, 'actions');
this.doingFilter = build_module_createDoingHook(this, 'filters');
this.didAction = build_module_createDidHook(this, 'actions');
this.didFilter = build_module_createDidHook(this, 'filters');
}
}
/** @typedef {_Hooks} Hooks */
/**
* Returns an instance of the hooks object.
*
* @return {Hooks} A Hooks instance.
*/
function createHooks() {
return new createHooks_Hooks();
}
/* harmony default export */ var build_module_createHooks = (createHooks);
// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/index.js
/**
* Internal dependencies
*/
/** @typedef {(...args: any[])=>any} Callback */
/**
* @typedef Handler
* @property {Callback} callback The callback
* @property {string} namespace The namespace
* @property {number} priority The namespace
*/
/**
* @typedef Hook
* @property {Handler[]} handlers Array of handlers
* @property {number} runs Run counter
*/
/**
* @typedef Current
* @property {string} name Hook name
* @property {number} currentIndex The index
*/
/**
* @typedef {Record<string, Hook> & {__current: Current[]}} Store
*/
/**
* @typedef {'actions' | 'filters'} StoreKey
*/
/**
* @typedef {import('./createHooks').Hooks} Hooks
*/
const defaultHooks = build_module_createHooks();
const {
addAction,
addFilter,
removeAction,
removeFilter,
hasAction,
hasFilter,
removeAllActions,
removeAllFilters,
doAction,
applyFilters,
currentAction,
currentFilter,
doingAction,
doingFilter,
didAction,
didFilter,
actions,
filters
} = defaultHooks;
/***/ })
/******/ });

2
wp-includes/js/dist/hooks.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

158
wp-includes/js/dist/html-entities.js vendored Normal file
View file

@ -0,0 +1,158 @@
this["wp"] = this["wp"] || {}; this["wp"]["htmlEntities"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "1FHn");
/******/ })
/************************************************************************/
/******/ ({
/***/ "1FHn":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeEntities", function() { return decodeEntities; });
/** @type {HTMLTextAreaElement} */
let _decodeTextArea;
/**
* Decodes the HTML entities from a given string.
*
* @param {string} html String that contain HTML entities.
*
* @example
* ```js
* const result = decodeEntities( '&aacute;' );
* console.log( result ); // result will be "á"
* ```
*
* @return {string} The decoded string.
*/
function decodeEntities(html) {
// not a string, or no entities to decode
if ('string' !== typeof html || -1 === html.indexOf('&')) {
return html;
} // create a textarea for decoding entities, that we can reuse
if (undefined === _decodeTextArea) {
if (document.implementation && document.implementation.createHTMLDocument) {
_decodeTextArea = document.implementation.createHTMLDocument('').createElement('textarea');
} else {
_decodeTextArea = document.createElement('textarea');
}
}
_decodeTextArea.innerHTML = html;
const decoded = _decodeTextArea.textContent;
_decodeTextArea.innerHTML = '';
/**
* Cast to string, HTMLTextAreaElement should always have `string` textContent.
*
* > The `textContent` property of the `Node` interface represents the text content of the
* > node and its descendants.
* >
* > Value: A string or `null`
* >
* > * If the node is a `document` or a Doctype, `textContent` returns `null`.
* > * If the node is a CDATA section, comment, processing instruction, or text node,
* > textContent returns the text inside the node, i.e., the `Node.nodeValue`.
* > * For other node types, `textContent returns the concatenation of the textContent of
* > every child node, excluding comments and processing instructions. (This is an empty
* > string if the node has no children.)
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
*/
return (
/** @type {string} */
decoded
);
}
/***/ })
/******/ });

View file

@ -0,0 +1,2 @@
/*! This file is auto-generated */
this.wp=this.wp||{},this.wp.htmlEntities=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s="1FHn")}({"1FHn":function(e,t,n){"use strict";let r;function o(e){if("string"!=typeof e||-1===e.indexOf("&"))return e;void 0===r&&(r=document.implementation&&document.implementation.createHTMLDocument?document.implementation.createHTMLDocument("").createElement("textarea"):document.createElement("textarea")),r.innerHTML=e;const t=r.textContent;return r.innerHTML="",t}n.r(t),n.d(t,"decodeEntities",(function(){return o}))}});

1677
wp-includes/js/dist/i18n.js vendored Normal file

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more