plugin updates

This commit is contained in:
Tony Volpe
2024-11-15 13:53:04 -05:00
parent 1293d604ca
commit 0238f0c4ca
2009 changed files with 163492 additions and 89543 deletions
+68 -62
View File
@@ -52,15 +52,40 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
setup: () => (/* binding */ setup),
speak: () => (/* binding */ speak)
speak: () => (/* reexport */ speak)
});
;// CONCATENATED MODULE: external ["wp","domReady"]
const external_wp_domReady_namespaceObject = window["wp"]["domReady"];
var external_wp_domReady_default = /*#__PURE__*/__webpack_require__.n(external_wp_domReady_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/script/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: external ["wp","i18n"]
const external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/add-intro-text.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/script/add-intro-text.js
/**
* WordPress dependencies
*/
@@ -90,32 +115,7 @@ function addIntroText() {
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
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/shared/clear.js
/**
* Clears the a11y-speak-region elements and hides the explanatory text.
*/
@@ -132,7 +132,7 @@ function clear() {
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/filter-message.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/shared/filter-message.js
let previousMessage = '';
/**
@@ -163,49 +163,19 @@ function filterMessage(message) {
return message;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/index.js
/**
* WordPress dependencies
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/shared/index.js
/**
* 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'.
* @param {string} message The message to be announced by assistive technologies.
* @param {'polite'|'assertive'} [ariaLive] The politeness level for aria-live; default: 'polite'.
*
* @example
* ```js
@@ -243,6 +213,42 @@ function speak(message, ariaLive) {
}
}
;// 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);
(window.wp = window.wp || {}).a11y = __webpack_exports__;
/******/ })()
;
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{setup:()=>d,speak:()=>p});const n=window.wp.domReady;var o=e.n(n);const i=window.wp.i18n;function a(e="polite"){const t=document.createElement("div");t.id=`a11y-speak-${e}`,t.className="a11y-speak-region",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("aria-live",e),t.setAttribute("aria-relevant","additions text"),t.setAttribute("aria-atomic","true");const{body:n}=document;return n&&n.appendChild(t),t}let r="";function d(){const e=document.getElementById("a11y-speak-intro-text"),t=document.getElementById("a11y-speak-assertive"),n=document.getElementById("a11y-speak-polite");null===e&&function(){const e=document.createElement("p");e.id="a11y-speak-intro-text",e.className="a11y-speak-intro-text",e.textContent=(0,i.__)("Notifications"),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("hidden","hidden");const{body:t}=document;t&&t.appendChild(e)}(),null===t&&a("assertive"),null===n&&a("polite")}function p(e,t){!function(){const e=document.getElementsByClassName("a11y-speak-region"),t=document.getElementById("a11y-speak-intro-text");for(let t=0;t<e.length;t++)e[t].textContent="";t&&t.setAttribute("hidden","hidden")}(),e=function(e){return e=e.replace(/<[^<>]+>/g," "),r===e&&(e+=" "),r=e,e}(e);const n=document.getElementById("a11y-speak-intro-text"),o=document.getElementById("a11y-speak-assertive"),i=document.getElementById("a11y-speak-polite");o&&"assertive"===t?o.textContent=e:i&&(i.textContent=e),n&&n.removeAttribute("hidden")}o()(d),(window.wp=window.wp||{}).a11y=t})();
(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{setup:()=>p,speak:()=>d});const n=window.wp.domReady;var o=e.n(n);function i(e="polite"){const t=document.createElement("div");t.id=`a11y-speak-${e}`,t.className="a11y-speak-region",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("aria-live",e),t.setAttribute("aria-relevant","additions text"),t.setAttribute("aria-atomic","true");const{body:n}=document;return n&&n.appendChild(t),t}const a=window.wp.i18n;let r="";function d(e,t){!function(){const e=document.getElementsByClassName("a11y-speak-region"),t=document.getElementById("a11y-speak-intro-text");for(let t=0;t<e.length;t++)e[t].textContent="";t&&t.setAttribute("hidden","hidden")}(),e=function(e){return e=e.replace(/<[^<>]+>/g," "),r===e&&(e+=" "),r=e,e}(e);const n=document.getElementById("a11y-speak-intro-text"),o=document.getElementById("a11y-speak-assertive"),i=document.getElementById("a11y-speak-polite");o&&"assertive"===t?o.textContent=e:i&&(i.textContent=e),n&&n.removeAttribute("hidden")}function p(){const e=document.getElementById("a11y-speak-intro-text"),t=document.getElementById("a11y-speak-assertive"),n=document.getElementById("a11y-speak-polite");null===e&&function(){const e=document.createElement("p");e.id="a11y-speak-intro-text",e.className="a11y-speak-intro-text",e.textContent=(0,a.__)("Notifications"),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("hidden","hidden");const{body:t}=document;t&&t.appendChild(e)}(),null===t&&i("assertive"),null===n&&i("polite")}o()(p),(window.wp=window.wp||{}).a11y=t})();
+4
View File
@@ -526,6 +526,10 @@ const mediaUploadMiddleware = (options, next) => {
...options,
parse: false
}).catch(response => {
// `response` could actually be an error thrown by `defaultFetchHandler`.
if (!response.headers) {
return Promise.reject(response);
}
const attachmentId = response.headers.get('x-wp-upload-attachment-id');
if (response.status >= 500 && response.status < 600 && attachmentId) {
return postProcess(attachmentId).catch(() => {
File diff suppressed because one or more lines are too long
+13 -16
View File
@@ -41,8 +41,6 @@ __webpack_require__.r(__webpack_exports__);
/* harmony export */ });
/**
* The regular expression for an HTML element.
*
* @type {RegExp}
*/
const htmlSplitRegex = (() => {
/* eslint-disable no-multi-spaces */
@@ -97,9 +95,9 @@ const htmlSplitRegex = (() => {
/**
* Separate HTML elements and comments from the text.
*
* @param {string} input The text which has to be formatted.
* @param input The text which has to be formatted.
*
* @return {string[]} The formatted text.
* @return The formatted text.
*/
function htmlSplit(input) {
const parts = [];
@@ -110,7 +108,7 @@ function htmlSplit(input) {
// 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;
const index = match.index;
parts.push(workingInput.slice(0, index));
parts.push(match[0]);
workingInput = workingInput.slice(index + match[0].length);
@@ -124,10 +122,10 @@ function htmlSplit(input) {
/**
* 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', …}.
* @param haystack The text which has to be formatted.
* @param replacePairs In the form {from: 'to', …}.
*
* @return {string} The formatted text.
* @return The formatted text.
*/
function replaceInHtmlTags(haystack, replacePairs) {
// Find all elements.
@@ -162,9 +160,9 @@ function replaceInHtmlTags(haystack, replacePairs) {
* 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.
* @param text The text which has to be formatted.
* @param br Optional. If set, will convert all remaining line-
* breaks after paragraphing. Default true.
*
* @example
*```js
@@ -172,7 +170,7 @@ function replaceInHtmlTags(haystack, replacePairs) {
* autop( 'my text' ); // "<p>my text</p>"
* ```
*
* @return {string} Text which has been converted into paragraph tags.
* @return Text which has been converted into paragraph tags.
*/
function autop(text, br = true) {
const preTags = [];
@@ -333,7 +331,7 @@ function autop(text, br = true) {
* 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.
* @param html The content from the editor.
*
* @example
* ```js
@@ -341,13 +339,12 @@ function autop(text, br = true) {
* removep( '<p>my text</p>' ); // "my text"
* ```
*
* @return {string} The content with stripped paragraph tags.
* @return 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;
@@ -458,7 +455,7 @@ function removep(html) {
// Restore preserved tags.
if (preserve.length) {
html = html.replace(/<wp-preserve>/g, () => {
return /** @type {string} */preserve.shift();
return preserve.shift();
});
}
return html;
+13 -15
View File
@@ -43,17 +43,15 @@ __webpack_require__.r(__webpack_exports__);
/* harmony export */ isBlobURL: () => (/* binding */ isBlobURL),
/* harmony export */ revokeBlobURL: () => (/* binding */ revokeBlobURL)
/* harmony export */ });
/**
* @type {Record<string, File|undefined>}
*/
/* wp:polyfill */
const cache = {};
/**
* Create a blob URL from a file.
*
* @param {File} file The file to create a blob URL for.
* @param file The file to create a blob URL for.
*
* @return {string} The blob URL.
* @return The blob URL.
*/
function createBlobURL(file) {
const url = window.URL.createObjectURL(file);
@@ -66,9 +64,9 @@ function createBlobURL(file) {
* `createBlobURL` and not removed by `revokeBlobURL`, otherwise it will return
* `undefined`.
*
* @param {string} url The blob URL.
* @param url The blob URL.
*
* @return {File|undefined} The file for the blob URL.
* @return The file for the blob URL.
*/
function getBlobByURL(url) {
return cache[url];
@@ -79,9 +77,9 @@ function getBlobByURL(url) {
* `createBlobURL` and not removed by `revokeBlobURL`, otherwise it will return
* `undefined`.
*
* @param {string} url The blob URL.
* @param url The blob URL.
*
* @return {string|undefined} The blob type.
* @return The blob type.
*/
function getBlobTypeByURL(url) {
return getBlobByURL(url)?.type.split('/')[0]; // 0: media type , 1: file extension eg ( type: 'image/jpeg' ).
@@ -90,7 +88,7 @@ function getBlobTypeByURL(url) {
/**
* Remove the resource and file cache from memory.
*
* @param {string} url The blob URL.
* @param url The blob URL.
*/
function revokeBlobURL(url) {
if (cache[url]) {
@@ -102,9 +100,9 @@ function revokeBlobURL(url) {
/**
* Check whether a url is a blob url.
*
* @param {string|undefined} url The URL.
* @param url The URL.
*
* @return {boolean} Is the url a blob url?
* @return Is the url a blob url?
*/
function isBlobURL(url) {
if (!url || !url.indexOf) {
@@ -132,9 +130,9 @@ function isBlobURL(url) {
* downloadBlob( filename, fileContent, 'application/json' );
* ```
*
* @param {string} filename File name.
* @param {BlobPart} content File content (BufferSource | Blob | string).
* @param {string} contentType (Optional) File mime type. Default is `''`.
* @param filename File name.
* @param content File content (BufferSource | Blob | string).
* @param contentType (Optional) File mime type. Default is `''`.
*/
function downloadBlob(filename, content, contentType = '') {
if (!filename || !content) {
+90 -105
View File
@@ -292,11 +292,11 @@ function getInstalledBlockTypes(state) {
*
* @return {Array} Block type items.
*/
const getNewBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const getNewBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (0,external_wp_data_namespaceObject.createSelector)(state => {
const usedBlockTree = select(external_wp_blockEditor_namespaceObject.store).getBlocks();
const installedBlockTypes = getInstalledBlockTypes(state);
return installedBlockTypes.filter(blockType => hasBlockType(blockType, usedBlockTree));
});
}, state => [getInstalledBlockTypes(state), select(external_wp_blockEditor_namespaceObject.store).getBlocks()]));
/**
* Returns the block types that have been installed on the server but are not
@@ -306,11 +306,11 @@ const getNewBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelec
*
* @return {Array} Block type items.
*/
const getUnusedBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const getUnusedBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (0,external_wp_data_namespaceObject.createSelector)(state => {
const usedBlockTree = select(external_wp_blockEditor_namespaceObject.store).getBlocks();
const installedBlockTypes = getInstalledBlockTypes(state);
return installedBlockTypes.filter(blockType => !hasBlockType(blockType, usedBlockTree));
});
}, state => [getInstalledBlockTypes(state), select(external_wp_blockEditor_namespaceObject.store).getBlocks()]));
/**
* Returns true if a block plugin install is in progress.
@@ -720,7 +720,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
@@ -831,8 +831,8 @@ function __awaiter(thisArg, _arguments, P, generator) {
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
@@ -936,8 +936,9 @@ function __await(v) {
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
@@ -1003,16 +1004,18 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
@@ -1031,17 +1034,22 @@ function __disposeResources(env) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
while (r = env.stack.pop()) {
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
@@ -1311,6 +1319,8 @@ const external_wp_compose_namespaceObject = window["wp"]["compose"];
const external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: external ["wp","coreData"]
const external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: ./node_modules/clsx/dist/clsx.mjs
function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f)}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}/* harmony default export */ const dist_clsx = (clsx);
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
const external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/icon/index.js
@@ -1505,19 +1515,12 @@ const DownloadableBlockNotice = ({
};
/* harmony default export */ const downloadable_block_notice = (DownloadableBlockNotice);
;// CONCATENATED MODULE: external ["wp","privateApis"]
const external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/lock-unlock.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-block-list-item/index.js
/**
* WordPress dependencies
* External dependencies
*/
const {
lock,
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.', '@wordpress/block-directory');
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-block-list-item/index.js
/**
* WordPress dependencies
*/
@@ -1536,14 +1539,10 @@ const {
const {
CompositeItemV2: CompositeItem
} = unlock(external_wp_components_namespaceObject.privateApis);
// Return the appropriate block item label, given the block data and status.
function getDownloadableBlockLabel({
title,
rating,
@@ -1555,28 +1554,27 @@ function getDownloadableBlockLabel({
}) {
const stars = Math.round(rating / 0.5) * 0.5;
if (!isInstalled && hasNotice) {
/* translators: %1$s: block title */
/* translators: %s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Retry installing %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
}
if (isInstalled) {
/* translators: %1$s: block title */
/* translators: %s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Add %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
}
if (isInstalling) {
/* translators: %1$s: block title */
/* translators: %s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Installing %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
}
// No ratings yet, just use the title.
if (ratingCount < 1) {
/* translators: %1$s: block title */
/* translators: %s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Install %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
}
return (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %1$s: block title, %2$s: average rating, %3$s: total ratings count. */
return (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: 1: block title, 2: average rating, 3: total ratings count. */
(0,external_wp_i18n_namespaceObject._n)('Install %1$s. %2$s stars with %3$s review.', 'Install %1$s. %2$s stars with %3$s reviews.', ratingCount), (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title), stars, ratingCount);
}
function DownloadableBlockListItem({
composite,
item,
onClick
}) {
@@ -1612,59 +1610,58 @@ function DownloadableBlockListItem({
} else if (isInstalling) {
statusText = (0,external_wp_i18n_namespaceObject.__)('Installing…');
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(CompositeItem, {
render: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__experimentalIsFocusable: true,
type: "button",
role: "option",
className: "block-directory-downloadable-block-list-item",
isBusy: isInstalling,
const itemLabel = getDownloadableBlockLabel(item, {
hasNotice,
isInstalled,
isInstalling
});
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Tooltip, {
placement: "top",
text: itemLabel,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.Composite.Item, {
className: dist_clsx('block-directory-downloadable-block-list-item', isInstalling && 'is-installing'),
accessibleWhenDisabled: true,
disabled: isInstalling || !isInstallable,
onClick: event => {
event.preventDefault();
onClick();
},
label: getDownloadableBlockLabel(item, {
hasNotice,
isInstalled,
isInstalling
}),
showTooltip: true,
tooltipPosition: "top center"
}),
store: composite,
disabled: isInstalling || !isInstallable,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("div", {
className: "block-directory-downloadable-block-list-item__icon",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(downloadable_block_icon, {
icon: icon,
title: title
}), isInstalling ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "block-directory-downloadable-block-list-item__spinner",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Spinner, {})
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(block_ratings, {
rating: rating
})]
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("span", {
className: "block-directory-downloadable-block-list-item__details",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "block-directory-downloadable-block-list-item__title",
children: (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %1$s: block title, %2$s: author name. */
(0,external_wp_i18n_namespaceObject.__)('%1$s <span>by %2$s</span>'), (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title), author), {
span: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "block-directory-downloadable-block-list-item__author"
})
})
}), hasNotice ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(downloadable_block_notice, {
block: item
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
"aria-label": itemLabel,
type: "button",
role: "option",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("div", {
className: "block-directory-downloadable-block-list-item__icon",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(downloadable_block_icon, {
icon: icon,
title: title
}), isInstalling ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "block-directory-downloadable-block-list-item__spinner",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Spinner, {})
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(block_ratings, {
rating: rating
})]
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("span", {
className: "block-directory-downloadable-block-list-item__details",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "block-directory-downloadable-block-list-item__desc",
children: !!statusText ? statusText : (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(description)
}), isInstallable && !(isInstalled || isInstalling) && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.VisuallyHidden, {
children: (0,external_wp_i18n_namespaceObject.__)('Install block')
className: "block-directory-downloadable-block-list-item__title",
children: (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.sprintf)( /* translators: 1: block title. 2: author name. */
(0,external_wp_i18n_namespaceObject.__)('%1$s <span>by %2$s</span>'), (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title), author), {
span: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "block-directory-downloadable-block-list-item__author"
})
})
}), hasNotice ? /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(downloadable_block_notice, {
block: item
}) : /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("span", {
className: "block-directory-downloadable-block-list-item__desc",
children: !!statusText ? statusText : (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(description)
}), isInstallable && !(isInstalled || isInstalling) && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.VisuallyHidden, {
children: (0,external_wp_i18n_namespaceObject.__)('Install block')
})]
})]
})]
})]
})
});
}
/* harmony default export */ const downloadable_block_list_item = (DownloadableBlockListItem);
@@ -1684,32 +1681,24 @@ function DownloadableBlockListItem({
const {
CompositeV2: Composite,
useCompositeStoreV2: useCompositeStore
} = unlock(external_wp_components_namespaceObject.privateApis);
const noop = () => {};
function DownloadableBlocksList({
items,
onHover = noop,
onSelect
}) {
const composite = useCompositeStore();
const {
installBlockType
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
if (!items.length) {
return null;
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Composite, {
store: composite,
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Composite, {
role: "listbox",
className: "block-directory-downloadable-blocks-list",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Blocks available for install'),
children: items.map(item => {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(downloadable_block_list_item, {
composite: composite,
onClick: () => {
// Check if the block is registered (`getBlockType`
// will return an object). If so, insert the block.
@@ -2022,7 +2011,6 @@ function CompactList({
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/plugins/installed-blocks-pre-publish-panel/index.js
var _window$wp$editor;
/**
* WordPress dependencies
*/
@@ -2030,25 +2018,20 @@ var _window$wp$editor;
/**
* Internal dependencies
*/
// We shouldn't import the editor package directly
// because it would include the wp-editor in all pages loading the block-directory script.
const {
PluginPrePublishPanel
} = (_window$wp$editor = window?.wp?.editor) !== null && _window$wp$editor !== void 0 ? _window$wp$editor : {};
function InstalledBlocksPrePublishPanel() {
const newBlockTypes = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getNewBlockTypes(), []);
if (!newBlockTypes.length) {
return null;
}
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(PluginPrePublishPanel, {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_editor_namespaceObject.PluginPrePublishPanel, {
icon: block_default,
title: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %d: number of blocks (number).
@@ -2091,6 +2074,7 @@ function InstallButton({
replaceBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
onClick: () => installBlockType(block).then(success => {
if (success) {
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(block.name);
@@ -2100,7 +2084,7 @@ function InstallButton({
}
}
}),
__experimentalIsFocusable: true,
accessibleWhenDisabled: true,
disabled: isInstallingBlock,
isBusy: isInstallingBlock,
variant: "primary",
@@ -2197,6 +2181,7 @@ const ModifiedWarning = ({
messageHTML = (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('Your site doesnt include support for the %s block. You can try installing the block, convert it to a Custom HTML block, or remove it entirely.'), originalBlock.title || originalName);
actions.push( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
onClick: convertToHTML,
variant: "tertiary",
children: (0,external_wp_i18n_namespaceObject.__)('Keep as HTML')
File diff suppressed because one or more lines are too long
+12421 -9579
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+3340 -2530
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+635 -266
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+262 -305
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+10034 -12450
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+301 -250
View File
@@ -2299,6 +2299,7 @@ __webpack_require__.d(__webpack_exports__, {
useDebounce: () => (/* reexport */ useDebounce),
useDebouncedInput: () => (/* reexport */ useDebouncedInput),
useDisabled: () => (/* reexport */ useDisabled),
useEvent: () => (/* reexport */ useEvent),
useFocusOnMount: () => (/* reexport */ useFocusOnMount),
useFocusReturn: () => (/* reexport */ use_focus_return),
useFocusableIframe: () => (/* reexport */ useFocusableIframe),
@@ -2311,7 +2312,7 @@ __webpack_require__.d(__webpack_exports__, {
usePrevious: () => (/* reexport */ usePrevious),
useReducedMotion: () => (/* reexport */ use_reduced_motion),
useRefEffect: () => (/* reexport */ useRefEffect),
useResizeObserver: () => (/* reexport */ useResizeAware),
useResizeObserver: () => (/* reexport */ use_resize_observer_useResizeObserver),
useStateWithHistory: () => (/* reexport */ useStateWithHistory),
useThrottle: () => (/* reexport */ useThrottle),
useViewportMatch: () => (/* reexport */ use_viewport_match),
@@ -2337,7 +2338,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
@@ -2448,8 +2449,8 @@ function __awaiter(thisArg, _arguments, P, generator) {
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
@@ -2553,8 +2554,9 @@ function __await(v) {
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
@@ -2620,16 +2622,18 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
@@ -2648,17 +2652,22 @@ function __disposeResources(env) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
while (r = env.stack.pop()) {
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
@@ -3543,8 +3552,7 @@ function useInstanceId(object, prefix, preferredId) {
/**
* A Higher Order Component used to be provide a unique instance ID by
* component.
* A Higher Order Component used to provide a unique instance ID by component.
*/
const withInstanceId = createHigherOrderComponent(WrappedComponent => {
return props => {
@@ -3699,12 +3707,12 @@ const external_wp_dom_namespaceObject = window["wp"]["dom"];
* @return Ref callback.
*/
function useRefEffect(callback, dependencies) {
const cleanup = (0,external_wp_element_namespaceObject.useRef)();
const cleanupRef = (0,external_wp_element_namespaceObject.useRef)();
return (0,external_wp_element_namespaceObject.useCallback)(node => {
if (node) {
cleanup.current = callback(node);
} else if (cleanup.current) {
cleanup.current();
cleanupRef.current = callback(node);
} else if (cleanupRef.current) {
cleanupRef.current();
}
}, dependencies);
}
@@ -3835,7 +3843,7 @@ function useCopyOnClick(ref, text, timeout = 4000) {
});
/** @type {import('react').MutableRefObject<Clipboard | undefined>} */
const clipboard = (0,external_wp_element_namespaceObject.useRef)();
const clipboardRef = (0,external_wp_element_namespaceObject.useRef)();
const [hasCopied, setHasCopied] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
/** @type {number | undefined} */
@@ -3845,10 +3853,10 @@ function useCopyOnClick(ref, text, timeout = 4000) {
}
// Clipboard listens to click events.
clipboard.current = new (clipboard_default())(ref.current, {
clipboardRef.current = new (clipboard_default())(ref.current, {
text: () => typeof text === 'function' ? text() : text
});
clipboard.current.on('success', ({
clipboardRef.current.on('success', ({
clearSelection,
trigger
}) => {
@@ -3868,8 +3876,8 @@ function useCopyOnClick(ref, text, timeout = 4000) {
}
});
return () => {
if (clipboard.current) {
clipboard.current.destroy();
if (clipboardRef.current) {
clipboardRef.current.destroy();
}
clearTimeout(timeoutId);
};
@@ -3997,7 +4005,7 @@ function useFocusOnMount(focusOnMount = 'firstElement') {
};
/** @type {import('react').MutableRefObject<ReturnType<setTimeout> | undefined>} */
const timerId = (0,external_wp_element_namespaceObject.useRef)();
const timerIdRef = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
focusOnMountRef.current = focusOnMount;
}, [focusOnMount]);
@@ -4009,19 +4017,19 @@ function useFocusOnMount(focusOnMount = 'firstElement') {
if (node.contains((_node$ownerDocument$a = node.ownerDocument?.activeElement) !== null && _node$ownerDocument$a !== void 0 ? _node$ownerDocument$a : null)) {
return;
}
if (focusOnMountRef.current === 'firstElement') {
timerId.current = setTimeout(() => {
const firstTabbable = external_wp_dom_namespaceObject.focus.tabbable.find(node)[0];
if (firstTabbable) {
setFocus(firstTabbable);
}
}, 0);
if (focusOnMountRef.current !== 'firstElement') {
setFocus(node);
return;
}
setFocus(node);
timerIdRef.current = setTimeout(() => {
const firstTabbable = external_wp_dom_namespaceObject.focus.tabbable.find(node)[0];
if (firstTabbable) {
setFocus(firstTabbable);
}
}, 0);
return () => {
if (timerId.current) {
clearTimeout(timerId.current);
if (timerIdRef.current) {
clearTimeout(timerIdRef.current);
}
};
}, []);
@@ -4152,18 +4160,18 @@ function isFocusNormalizedButton(eventTarget) {
* wrapping element element to capture when focus moves outside that element.
*/
function useFocusOutside(onFocusOutside) {
const currentOnFocusOutside = (0,external_wp_element_namespaceObject.useRef)(onFocusOutside);
const currentOnFocusOutsideRef = (0,external_wp_element_namespaceObject.useRef)(onFocusOutside);
(0,external_wp_element_namespaceObject.useEffect)(() => {
currentOnFocusOutside.current = onFocusOutside;
currentOnFocusOutsideRef.current = onFocusOutside;
}, [onFocusOutside]);
const preventBlurCheck = (0,external_wp_element_namespaceObject.useRef)(false);
const blurCheckTimeoutId = (0,external_wp_element_namespaceObject.useRef)();
const preventBlurCheckRef = (0,external_wp_element_namespaceObject.useRef)(false);
const blurCheckTimeoutIdRef = (0,external_wp_element_namespaceObject.useRef)();
/**
* Cancel a blur check timeout.
*/
const cancelBlurCheck = (0,external_wp_element_namespaceObject.useCallback)(() => {
clearTimeout(blurCheckTimeoutId.current);
clearTimeout(blurCheckTimeoutIdRef.current);
}, []);
// Cancel blur checks on unmount.
@@ -4195,9 +4203,9 @@ function useFocusOutside(onFocusOutside) {
} = event;
const isInteractionEnd = ['mouseup', 'touchend'].includes(type);
if (isInteractionEnd) {
preventBlurCheck.current = false;
preventBlurCheckRef.current = false;
} else if (isFocusNormalizedButton(target)) {
preventBlurCheck.current = true;
preventBlurCheckRef.current = true;
}
}, []);
@@ -4214,7 +4222,7 @@ function useFocusOutside(onFocusOutside) {
event.persist();
// Skip blur check if clicking button. See `normalizeButtonFocus`.
if (preventBlurCheck.current) {
if (preventBlurCheckRef.current) {
return;
}
@@ -4229,7 +4237,7 @@ function useFocusOutside(onFocusOutside) {
if (ignoreForRelatedTarget && event.relatedTarget?.closest(ignoreForRelatedTarget)) {
return;
}
blurCheckTimeoutId.current = setTimeout(() => {
blurCheckTimeoutIdRef.current = setTimeout(() => {
// If document is not focused then focus should remain
// inside the wrapped component and therefore we cancel
// this blur event thereby leaving focus in place.
@@ -4238,8 +4246,8 @@ function useFocusOutside(onFocusOutside) {
event.preventDefault();
return;
}
if ('function' === typeof currentOnFocusOutside.current) {
currentOnFocusOutside.current(event);
if ('function' === typeof currentOnFocusOutsideRef.current) {
currentOnFocusOutsideRef.current(event);
}
}, 0);
}, []);
@@ -4326,38 +4334,38 @@ function assignRef(ref, value) {
*/
function useMergeRefs(refs) {
const element = (0,external_wp_element_namespaceObject.useRef)();
const isAttached = (0,external_wp_element_namespaceObject.useRef)(false);
const didElementChange = (0,external_wp_element_namespaceObject.useRef)(false);
const isAttachedRef = (0,external_wp_element_namespaceObject.useRef)(false);
const didElementChangeRef = (0,external_wp_element_namespaceObject.useRef)(false);
/* eslint-disable jsdoc/no-undefined-types */
/** @type {import('react').MutableRefObject<TRef[]>} */
/* eslint-enable jsdoc/no-undefined-types */
const previousRefs = (0,external_wp_element_namespaceObject.useRef)([]);
const currentRefs = (0,external_wp_element_namespaceObject.useRef)(refs);
const previousRefsRef = (0,external_wp_element_namespaceObject.useRef)([]);
const currentRefsRef = (0,external_wp_element_namespaceObject.useRef)(refs);
// Update on render before the ref callback is called, so the ref callback
// always has access to the current refs.
currentRefs.current = refs;
currentRefsRef.current = refs;
// If any of the refs change, call the previous ref with `null` and the new
// ref with the node, except when the element changes in the same cycle, in
// which case the ref callbacks will already have been called.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (didElementChange.current === false && isAttached.current === true) {
if (didElementChangeRef.current === false && isAttachedRef.current === true) {
refs.forEach((ref, index) => {
const previousRef = previousRefs.current[index];
const previousRef = previousRefsRef.current[index];
if (ref !== previousRef) {
assignRef(previousRef, null);
assignRef(ref, element.current);
}
});
}
previousRefs.current = refs;
previousRefsRef.current = refs;
}, refs);
// No dependencies, must be reset after every render so ref callbacks are
// correctly called after a ref change.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
didElementChange.current = false;
didElementChangeRef.current = false;
});
// There should be no dependencies so that `callback` is only called when
@@ -4366,12 +4374,12 @@ function useMergeRefs(refs) {
// Update the element so it can be used when calling ref callbacks on a
// dependency change.
assignRef(element, value);
didElementChange.current = true;
isAttached.current = value !== null;
didElementChangeRef.current = true;
isAttachedRef.current = value !== null;
// When an element changes, the current ref callback should be called
// with the new element and the previous one with `null`.
const refsToAssign = value ? currentRefs.current : previousRefs.current;
const refsToAssign = value ? currentRefsRef.current : previousRefsRef.current;
// Update the latest refs.
for (const ref of refsToAssign) {
@@ -4530,6 +4538,52 @@ function useDisabled({
}, [isDisabledProp]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-event/index.js
/**
* WordPress dependencies
*/
/**
* Any function.
*/
/**
* Creates a stable callback function that has access to the latest state and
* can be used within event handlers and effect callbacks. Throws when used in
* the render phase.
*
* @param callback The callback function to wrap.
*
* @example
*
* ```tsx
* function Component( props ) {
* const onClick = useEvent( props.onClick );
* useEffect( () => {
* onClick();
* // Won't trigger the effect again when props.onClick is updated.
* }, [ onClick ] );
* // Won't re-render Button when props.onClick is updated (if `Button` is
* // wrapped in `React.memo`).
* return <Button onClick={ onClick } />;
* }
* ```
*/
function useEvent(
/**
* The callback function to wrap.
*/
callback) {
const ref = (0,external_wp_element_namespaceObject.useRef)(() => {
throw new Error('Callbacks created with `useEvent` cannot be called during rendering.');
});
(0,external_wp_element_namespaceObject.useInsertionEffect)(() => {
ref.current = callback;
});
return (0,external_wp_element_namespaceObject.useCallback)((...args) => ref.current?.(...args), []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-isomorphic-layout-effect/index.js
/**
* WordPress dependencies
@@ -4664,9 +4718,9 @@ shortcuts, callback, {
// This is important for performance considerations.
target
} = {}) {
const currentCallback = (0,external_wp_element_namespaceObject.useRef)(callback);
const currentCallbackRef = (0,external_wp_element_namespaceObject.useRef)(callback);
(0,external_wp_element_namespaceObject.useEffect)(() => {
currentCallback.current = callback;
currentCallbackRef.current = callback;
}, [callback]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isDisabled) {
@@ -4696,7 +4750,7 @@ shortcuts, callback, {
// @ts-ignore `bindGlobal` is an undocumented property
mousetrap[bindFn](shortcut, ( /* eslint-disable jsdoc/valid-types */
/** @type {[e: import('mousetrap').ExtendedKeyboardEvent, combo: string]} */...args) => /* eslint-enable jsdoc/valid-types */
currentCallback.current(...args), eventName);
currentCallbackRef.current(...args), eventName);
});
return () => {
mousetrap.reset();
@@ -4907,7 +4961,7 @@ function useStateWithHistory(initialValue) {
/**
* @typedef {"huge" | "wide" | "large" | "medium" | "small" | "mobile"} WPBreakpoint
* @typedef {"xhuge" | "huge" | "wide" | "xlarge" | "large" | "medium" | "small" | "mobile"} WPBreakpoint
*/
/**
@@ -4918,8 +4972,10 @@ function useStateWithHistory(initialValue) {
* @type {Record<WPBreakpoint, number>}
*/
const BREAKPOINTS = {
xhuge: 1920,
huge: 1440,
wide: 1280,
xlarge: 1080,
large: 960,
medium: 782,
small: 600,
@@ -4978,7 +5034,51 @@ const useViewportMatch = (breakpoint, operator = '>=') => {
useViewportMatch.__experimentalWidthProvider = ViewportMatchWidthContext.Provider;
/* harmony default export */ const use_viewport_match = (useViewportMatch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-resize-observer/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-resize-observer/use-resize-observer.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// This is the current implementation of `useResizeObserver`.
//
// The legacy implementation is still supported for backwards compatibility.
// This is achieved by overloading the exported function with both signatures,
// and detecting which API is being used at runtime.
function useResizeObserver(callback, resizeObserverOptions = {}) {
const callbackEvent = useEvent(callback);
const observedElementRef = (0,external_wp_element_namespaceObject.useRef)();
const resizeObserverRef = (0,external_wp_element_namespaceObject.useRef)();
return useEvent(element => {
var _resizeObserverRef$cu;
if (element === observedElementRef.current) {
return;
}
// Set up `ResizeObserver`.
(_resizeObserverRef$cu = resizeObserverRef.current) !== null && _resizeObserverRef$cu !== void 0 ? _resizeObserverRef$cu : resizeObserverRef.current = new ResizeObserver(callbackEvent);
const {
current: resizeObserver
} = resizeObserverRef;
// Unobserve previous element.
if (observedElementRef.current) {
resizeObserver.unobserve(observedElementRef.current);
}
// Observe new element.
observedElementRef.current = element;
if (element) {
resizeObserver.observe(element, resizeObserverOptions);
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-resize-observer/legacy/index.js
/**
* External dependencies
*/
@@ -4987,62 +5087,10 @@ useViewportMatch.__experimentalWidthProvider = ViewportMatchWidthContext.Provide
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// This of course could've been more streamlined with internal state instead of
// refs, but then host hooks / components could not opt out of renders.
// This could've been exported to its own module, but the current build doesn't
// seem to work with module imports and I had no more time to spend on this...
function useResolvedElement(subscriber, refOrElement) {
const callbackRefElement = (0,external_wp_element_namespaceObject.useRef)(null);
const lastReportRef = (0,external_wp_element_namespaceObject.useRef)(null);
const cleanupRef = (0,external_wp_element_namespaceObject.useRef)();
const callSubscriber = (0,external_wp_element_namespaceObject.useCallback)(() => {
let element = null;
if (callbackRefElement.current) {
element = callbackRefElement.current;
} else if (refOrElement) {
if (refOrElement instanceof HTMLElement) {
element = refOrElement;
} else {
element = refOrElement.current;
}
}
if (lastReportRef.current && lastReportRef.current.element === element && lastReportRef.current.reporter === callSubscriber) {
return;
}
if (cleanupRef.current) {
cleanupRef.current();
// Making sure the cleanup is not called accidentally multiple times.
cleanupRef.current = null;
}
lastReportRef.current = {
reporter: callSubscriber,
element
};
// Only calling the subscriber, if there's an actual element to report.
if (element) {
cleanupRef.current = subscriber(element);
}
}, [refOrElement, subscriber]);
// On each render, we check whether a ref changed, or if we got a new raw
// element.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// With this we're *technically* supporting cases where ref objects' current value changes, but only if there's a
// render accompanying that change as well.
// To guarantee we always have the right element, one must use the ref callback provided instead, but we support
// RefObjects to make the hook API more convenient in certain cases.
callSubscriber();
}, [callSubscriber]);
return (0,external_wp_element_namespaceObject.useCallback)(element => {
callbackRefElement.current = element;
callSubscriber();
}, [callSubscriber]);
}
// Declaring my own type here instead of using the one provided by TS (available since 4.2.2), because this way I'm not
// forcing consumers to use a specific TS version.
// We're only using the first element of the size sequences, until future versions of the spec solidify on how
// exactly it'll be used for fragments in multi-column scenarios:
@@ -5069,115 +5117,65 @@ function useResolvedElement(subscriber, refOrElement) {
// even though it seems we have access to results for all box types.
// This also means that we get to keep the current api, being able to return a simple { width, height } pair,
// regardless of box option.
const extractSize = (entry, boxProp, sizeType) => {
if (!entry[boxProp]) {
if (boxProp === 'contentBoxSize') {
// The dimensions in `contentBoxSize` and `contentRect` are equivalent according to the spec.
// See the 6th step in the description for the RO algorithm:
// https://drafts.csswg.org/resize-observer/#create-and-populate-resizeobserverentry-h
// > Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
// In real browser implementations of course these objects differ, but the width/height values should be equivalent.
return entry.contentRect[sizeType === 'inlineSize' ? 'width' : 'height'];
}
return undefined;
const extractSize = entry => {
let entrySize;
if (!entry.contentBoxSize) {
// The dimensions in `contentBoxSize` and `contentRect` are equivalent according to the spec.
// See the 6th step in the description for the RO algorithm:
// https://drafts.csswg.org/resize-observer/#create-and-populate-resizeobserverentry-h
// > Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
// In real browser implementations of course these objects differ, but the width/height values should be equivalent.
entrySize = [entry.contentRect.width, entry.contentRect.height];
} else if (entry.contentBoxSize[0]) {
const contentBoxSize = entry.contentBoxSize[0];
entrySize = [contentBoxSize.inlineSize, contentBoxSize.blockSize];
} else {
// TS complains about this, because the RO entry type follows the spec and does not reflect Firefox's buggy
// behaviour of returning objects instead of arrays for `borderBoxSize` and `contentBoxSize`.
const contentBoxSize = entry.contentBoxSize;
entrySize = [contentBoxSize.inlineSize, contentBoxSize.blockSize];
}
// A couple bytes smaller than calling Array.isArray() and just as effective here.
return entry[boxProp][0] ? entry[boxProp][0][sizeType] :
// TS complains about this, because the RO entry type follows the spec and does not reflect Firefox's current
// behaviour of returning objects instead of arrays for `borderBoxSize` and `contentBoxSize`.
// @ts-ignore
entry[boxProp][sizeType];
const [width, height] = entrySize.map(d => Math.round(d));
return {
width,
height
};
};
function useResizeObserver(opts = {}) {
// Saving the callback as a ref. With this, I don't need to put onResize in the
// effect dep array, and just passing in an anonymous function without memoising
// will not reinstantiate the hook's ResizeObserver.
const onResize = opts.onResize;
const onResizeRef = (0,external_wp_element_namespaceObject.useRef)(undefined);
onResizeRef.current = onResize;
const round = opts.round || Math.round;
// Using a single instance throughout the hook's lifetime
const resizeObserverRef = (0,external_wp_element_namespaceObject.useRef)();
const [size, setSize] = (0,external_wp_element_namespaceObject.useState)({
width: undefined,
height: undefined
const RESIZE_ELEMENT_STYLES = {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
opacity: 0,
overflow: 'hidden',
zIndex: -1
};
function ResizeElement({
onResize
}) {
const resizeElementRef = useResizeObserver(entries => {
const newSize = extractSize(entries.at(-1)); // Entries are never empty.
onResize(newSize);
});
// In certain edge cases the RO might want to report a size change just after
// the component unmounted.
const didUnmount = (0,external_wp_element_namespaceObject.useRef)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
didUnmount.current = false;
return () => {
didUnmount.current = true;
};
}, []);
// Using a ref to track the previous width / height to avoid unnecessary renders.
const previous = (0,external_wp_element_namespaceObject.useRef)({
width: undefined,
height: undefined
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("div", {
ref: resizeElementRef,
style: RESIZE_ELEMENT_STYLES,
"aria-hidden": "true"
});
// This block is kinda like a useEffect, only it's called whenever a new
// element could be resolved based on the ref option. It also has a cleanup
// function.
const refCallback = useResolvedElement((0,external_wp_element_namespaceObject.useCallback)(element => {
// We only use a single Resize Observer instance, and we're instantiating it on demand, only once there's something to observe.
// This instance is also recreated when the `box` option changes, so that a new observation is fired if there was a previously observed element with a different box option.
if (!resizeObserverRef.current || resizeObserverRef.current.box !== opts.box || resizeObserverRef.current.round !== round) {
resizeObserverRef.current = {
box: opts.box,
round,
instance: new ResizeObserver(entries => {
const entry = entries[0];
let boxProp = 'borderBoxSize';
if (opts.box === 'border-box') {
boxProp = 'borderBoxSize';
} else {
boxProp = opts.box === 'device-pixel-content-box' ? 'devicePixelContentBoxSize' : 'contentBoxSize';
}
const reportedWidth = extractSize(entry, boxProp, 'inlineSize');
const reportedHeight = extractSize(entry, boxProp, 'blockSize');
const newWidth = reportedWidth ? round(reportedWidth) : undefined;
const newHeight = reportedHeight ? round(reportedHeight) : undefined;
if (previous.current.width !== newWidth || previous.current.height !== newHeight) {
const newSize = {
width: newWidth,
height: newHeight
};
previous.current.width = newWidth;
previous.current.height = newHeight;
if (onResizeRef.current) {
onResizeRef.current(newSize);
} else if (!didUnmount.current) {
setSize(newSize);
}
}
})
};
}
resizeObserverRef.current.instance.observe(element, {
box: opts.box
});
return () => {
if (resizeObserverRef.current) {
resizeObserverRef.current.instance.unobserve(element);
}
};
}, [opts.box, round]), opts.ref);
return (0,external_wp_element_namespaceObject.useMemo)(() => ({
ref: refCallback,
width: size.width,
height: size.height
}), [refCallback, size ? size.width : null, size ? size.height : null]);
}
function sizeEquals(a, b) {
return a.width === b.width && a.height === b.height;
}
const NULL_SIZE = {
width: null,
height: null
};
/**
* Hook which allows to listen the resize event of any target element when it changes sizes.
* _Note: `useResizeObserver` will report `null` until after first render.
* Hook which allows to listen to the resize event of any target element when it changes size.
* _Note: `useResizeObserver` will report `null` sizes until after first render.
*
* @example
*
@@ -5194,34 +5192,85 @@ function useResizeObserver(opts = {}) {
* };
* ```
*/
function useResizeAware() {
const {
ref,
width,
height
} = useResizeObserver();
const sizes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return {
width: width !== null && width !== void 0 ? width : null,
height: height !== null && height !== void 0 ? height : null
};
}, [width, height]);
const resizeListener = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("div", {
style: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
opacity: 0,
overflow: 'hidden',
zIndex: -1
},
"aria-hidden": "true",
ref: ref
function useLegacyResizeObserver() {
const [size, setSize] = (0,external_wp_element_namespaceObject.useState)(NULL_SIZE);
// Using a ref to track the previous width / height to avoid unnecessary renders.
const previousSizeRef = (0,external_wp_element_namespaceObject.useRef)(NULL_SIZE);
const handleResize = (0,external_wp_element_namespaceObject.useCallback)(newSize => {
if (!sizeEquals(previousSizeRef.current, newSize)) {
previousSizeRef.current = newSize;
setSize(newSize);
}
}, []);
const resizeElement = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ResizeElement, {
onResize: handleResize
});
return [resizeListener, sizes];
return [resizeElement, size];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-resize-observer/index.js
/**
* Internal dependencies
*/
/**
* External dependencies
*/
/**
* Sets up a [`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API)
* for an HTML or SVG element.
*
* Pass the returned setter as a callback ref to the React element you want
* to observe, or use it in layout effects for advanced use cases.
*
* @example
*
* ```tsx
* const setElement = useResizeObserver(
* ( resizeObserverEntries ) => console.log( resizeObserverEntries ),
* { box: 'border-box' }
* );
* <div ref={ setElement } />;
*
* // The setter can be used in other ways, for example:
* useLayoutEffect( () => {
* setElement( document.querySelector( `data-element-id="${ elementId }"` ) );
* }, [ elementId ] );
* ```
*
* @param callback The `ResizeObserver` callback - [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/ResizeObserver#callback).
* @param options Options passed to `ResizeObserver.observe` when called - [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/observe#options). Changes will be ignored.
*/
/**
* **This is a legacy API and should not be used.**
*
* @deprecated Use the other `useResizeObserver` API instead: `const ref = useResizeObserver( ( entries ) => { ... } )`.
*
* Hook which allows to listen to the resize event of any target element when it changes size.
* _Note: `useResizeObserver` will report `null` sizes until after first render.
*
* @example
*
* ```js
* const App = () => {
* const [ resizeListener, sizes ] = useResizeObserver();
*
* return (
* <div>
* { resizeListener }
* Your content here
* </div>
* );
* };
* ```
*/
function use_resize_observer_useResizeObserver(callback, options = {}) {
return callback ? useResizeObserver(callback, options) : useLegacyResizeObserver();
}
;// CONCATENATED MODULE: external ["wp","priorityQueue"]
@@ -5627,6 +5676,7 @@ function useDropZone({
// zone.
// Note: This is not entirely reliable in Safari due to this bug
// https://bugs.webkit.org/show_bug.cgi?id=66547
if (isElementInZone(event.relatedTarget)) {
return;
}
@@ -5948,6 +5998,7 @@ function useObservableValue(map, name) {
})();
File diff suppressed because one or more lines are too long
+141 -54
View File
@@ -65,6 +65,30 @@ const plus = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(exter
});
/* harmony default export */ const library_plus = (plus);
;// CONCATENATED MODULE: external ["wp","url"]
const external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: external ["wp","coreData"]
const external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: external ["wp","data"]
const external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","element"]
const external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","notices"]
const external_wp_notices_namespaceObject = window["wp"]["notices"];
;// CONCATENATED MODULE: external ["wp","router"]
const external_wp_router_namespaceObject = window["wp"]["router"];
;// CONCATENATED MODULE: external ["wp","privateApis"]
const external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/lock-unlock.js
/**
* WordPress dependencies
*/
const {
lock,
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.', '@wordpress/core-commands');
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/admin-navigation-commands.js
/**
* WordPress dependencies
@@ -72,6 +96,71 @@ const plus = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(exter
/**
* Internal dependencies
*/
const {
useHistory
} = unlock(external_wp_router_namespaceObject.privateApis);
function useAddNewPageCommand() {
const isSiteEditor = (0,external_wp_url_namespaceObject.getPath)(window.location.href)?.includes('site-editor.php');
const history = useHistory();
const isBlockBasedTheme = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_coreData_namespaceObject.store).getCurrentTheme()?.is_block_theme;
}, []);
const {
saveEntityRecord
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_coreData_namespaceObject.store);
const {
createErrorNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const createPageEntity = (0,external_wp_element_namespaceObject.useCallback)(async ({
close
}) => {
try {
const page = await saveEntityRecord('postType', 'page', {
status: 'draft'
}, {
throwOnError: true
});
if (page?.id) {
history.push({
postId: page.id,
postType: 'page',
canvas: 'edit'
});
}
} catch (error) {
const errorMessage = error.message && error.code !== 'unknown_error' ? error.message : (0,external_wp_i18n_namespaceObject.__)('An error occurred while creating the item.');
createErrorNotice(errorMessage, {
type: 'snackbar'
});
} finally {
close();
}
}, [createErrorNotice, history, saveEntityRecord]);
const commands = (0,external_wp_element_namespaceObject.useMemo)(() => {
const addNewPage = isSiteEditor && isBlockBasedTheme ? createPageEntity : () => document.location.href = 'post-new.php?post_type=page';
return [{
name: 'core/add-new-page',
label: (0,external_wp_i18n_namespaceObject.__)('Add new page'),
icon: library_plus,
callback: addNewPage
}];
}, [createPageEntity, isSiteEditor, isBlockBasedTheme]);
return {
isLoading: false,
commands
};
}
function useAdminNavigationCommands() {
(0,external_wp_commands_namespaceObject.useCommand)({
name: 'core/add-new-post',
@@ -81,22 +170,12 @@ function useAdminNavigationCommands() {
document.location.href = 'post-new.php';
}
});
(0,external_wp_commands_namespaceObject.useCommand)({
(0,external_wp_commands_namespaceObject.useCommandLoader)({
name: 'core/add-new-page',
label: (0,external_wp_i18n_namespaceObject.__)('Add new page'),
icon: library_plus,
callback: () => {
document.location.href = 'post-new.php?post_type=page';
}
hook: useAddNewPageCommand
});
}
;// CONCATENATED MODULE: external ["wp","element"]
const external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","data"]
const external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","coreData"]
const external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/post.js
/**
* WordPress dependencies
@@ -185,7 +264,9 @@ const styles = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ext
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
d: "M12 4c-4.4 0-8 3.6-8 8v.1c0 4.1 3.2 7.5 7.2 7.9h.8c4.4 0 8-3.6 8-8s-3.6-8-8-8zm0 15V5c3.9 0 7 3.1 7 7s-3.1 7-7 7z"
fillRule: "evenodd",
clipRule: "evenodd",
d: "M20 12a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-1.5 0a6.5 6.5 0 0 1-6.5 6.5v-13a6.5 6.5 0 0 1 6.5 6.5Z"
})
});
/* harmony default export */ const library_styles = (styles);
@@ -205,34 +286,10 @@ const symbol = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ext
});
/* harmony default export */ const library_symbol = (symbol);
;// CONCATENATED MODULE: external ["wp","router"]
const external_wp_router_namespaceObject = window["wp"]["router"];
;// CONCATENATED MODULE: external ["wp","url"]
const external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: external ["wp","compose"]
const external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/hooks.js
/**
* WordPress dependencies
*/
function useIsBlockBasedTheme() {
return (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_coreData_namespaceObject.store).getCurrentTheme()?.is_block_theme, []);
}
;// CONCATENATED MODULE: external ["wp","privateApis"]
const external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/lock-unlock.js
/**
* WordPress dependencies
*/
const {
lock,
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.', '@wordpress/core-commands');
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
const external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/utils/order-entity-records-by-search.js
function orderEntityRecordsBySearch(records = [], search = '') {
if (!Array.isArray(records) || !records.length) {
@@ -268,14 +325,14 @@ function orderEntityRecordsBySearch(records = [], search = '') {
/**
* Internal dependencies
*/
const {
useHistory
useHistory: site_editor_navigation_commands_useHistory
} = unlock(external_wp_router_namespaceObject.privateApis);
const icons = {
post: library_post,
@@ -295,8 +352,19 @@ function useDebouncedValue(value) {
const getNavigationCommandLoaderPerPostType = postType => function useNavigationCommandLoader({
search
}) {
const history = useHistory();
const isBlockBasedTheme = useIsBlockBasedTheme();
const history = site_editor_navigation_commands_useHistory();
const {
isBlockBasedTheme,
canCreateTemplate
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
isBlockBasedTheme: select(external_wp_coreData_namespaceObject.store).getCurrentTheme()?.is_block_theme,
canCreateTemplate: select(external_wp_coreData_namespaceObject.store).canUser('create', {
kind: 'postType',
name: 'wp_template'
})
};
}, []);
const delayedSearch = useDebouncedValue(search);
const {
records,
@@ -323,10 +391,10 @@ const getNavigationCommandLoaderPerPostType = postType => function useNavigation
const command = {
name: postType + '-' + record.id,
searchLabel: record.title?.rendered + ' ' + record.id,
label: record.title?.rendered ? record.title?.rendered : (0,external_wp_i18n_namespaceObject.__)('(no title)'),
label: record.title?.rendered ? (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(record.title?.rendered) : (0,external_wp_i18n_namespaceObject.__)('(no title)'),
icon: icons[postType]
};
if (postType === 'post' || postType === 'page' && !isBlockBasedTheme) {
if (!canCreateTemplate || postType === 'post' || postType === 'page' && !isBlockBasedTheme) {
return {
...command,
callback: ({
@@ -363,7 +431,7 @@ const getNavigationCommandLoaderPerPostType = postType => function useNavigation
}
};
});
}, [records, isBlockBasedTheme, history]);
}, [canCreateTemplate, records, isBlockBasedTheme, history]);
return {
commands,
isLoading
@@ -372,8 +440,19 @@ const getNavigationCommandLoaderPerPostType = postType => function useNavigation
const getNavigationCommandLoaderPerTemplate = templateType => function useNavigationCommandLoader({
search
}) {
const history = useHistory();
const isBlockBasedTheme = useIsBlockBasedTheme();
const history = site_editor_navigation_commands_useHistory();
const {
isBlockBasedTheme,
canCreateTemplate
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
isBlockBasedTheme: select(external_wp_coreData_namespaceObject.store).getCurrentTheme()?.is_block_theme,
canCreateTemplate: select(external_wp_coreData_namespaceObject.store).canUser('create', {
kind: 'postType',
name: templateType
})
};
}, []);
const {
records,
isLoading
@@ -399,7 +478,7 @@ const getNavigationCommandLoaderPerTemplate = templateType => function useNaviga
return orderEntityRecordsBySearch(records, search).slice(0, 10);
}, [records, search]);
const commands = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!isBlockBasedTheme && !templateType === 'wp_template_part') {
if (!canCreateTemplate || !isBlockBasedTheme && !templateType === 'wp_template_part') {
return [];
}
const isSiteEditor = (0,external_wp_url_namespaceObject.getPath)(window.location.href)?.includes('site-editor.php');
@@ -451,7 +530,7 @@ const getNavigationCommandLoaderPerTemplate = templateType => function useNaviga
});
}
return result;
}, [isBlockBasedTheme, orderedRecords, history]);
}, [canCreateTemplate, isBlockBasedTheme, orderedRecords, history]);
return {
commands,
isLoading
@@ -462,12 +541,20 @@ const usePostNavigationCommandLoader = getNavigationCommandLoaderPerPostType('po
const useTemplateNavigationCommandLoader = getNavigationCommandLoaderPerTemplate('wp_template');
const useTemplatePartNavigationCommandLoader = getNavigationCommandLoaderPerTemplate('wp_template_part');
function useSiteEditorBasicNavigationCommands() {
const history = useHistory();
const history = site_editor_navigation_commands_useHistory();
const isSiteEditor = (0,external_wp_url_namespaceObject.getPath)(window.location.href)?.includes('site-editor.php');
const canCreateTemplate = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_coreData_namespaceObject.store).canUser('create', 'templates');
const {
isBlockBasedTheme,
canCreateTemplate
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
isBlockBasedTheme: select(external_wp_coreData_namespaceObject.store).getCurrentTheme()?.is_block_theme,
canCreateTemplate: select(external_wp_coreData_namespaceObject.store).canUser('create', {
kind: 'postType',
name: 'wp_template'
})
};
}, []);
const isBlockBasedTheme = useIsBlockBasedTheme();
const commands = (0,external_wp_element_namespaceObject.useMemo)(() => {
const result = [];
if (canCreateTemplate && isBlockBasedTheme) {
File diff suppressed because one or more lines are too long
+953 -620
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+28 -22
View File
@@ -216,7 +216,10 @@ function CopyButton({
children
}) {
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(text);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button
// TODO: Switch to `true` (40px size) if possible
, {
__next40pxDefaultSize: false,
variant: "secondary",
ref: ref,
children: children
@@ -546,7 +549,10 @@ function Inserter({
id: inserterTitleId,
className: "customize-widgets-layout__inserter-panel-header-title",
children: (0,external_wp_i18n_namespaceObject.__)('Add a block')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button
// TODO: Switch to `true` (40px size) if possible
, {
__next40pxDefaultSize: false,
className: "customize-widgets-layout__inserter-panel-header-close-button",
icon: close_small,
onClick: () => setIsOpened(false),
@@ -1030,24 +1036,16 @@ function Header({
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_undo : library_redo
/* translators: button label text should, if possible, be under 16 characters. */,
label: (0,external_wp_i18n_namespaceObject.__)('Undo'),
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.primary('z')
// If there are no undo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasUndo,
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.primary('z'),
disabled: !hasUndo,
onClick: sidebar.undo,
className: "customize-widgets-editor-history-button undo-button"
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ToolbarButton, {
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_redo : library_undo
/* translators: button label text should, if possible, be under 16 characters. */,
label: (0,external_wp_i18n_namespaceObject.__)('Redo'),
shortcut: shortcut
// If there are no undo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasRedo,
shortcut: shortcut,
disabled: !hasRedo,
onClick: sidebar.redo,
className: "customize-widgets-editor-history-button redo-button"
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ToolbarButton, {
@@ -1519,7 +1517,10 @@ function WelcomeGuide({
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("p", {
className: "customize-widgets-welcome-guide__text",
children: isEntirelyBlockWidgets ? (0,external_wp_i18n_namespaceObject.__)('Your theme provides different “block” areas for you to add and edit content. Try adding a search bar, social icons, or other types of blocks here and see how theyll look on your site.') : (0,external_wp_i18n_namespaceObject.__)('You can now add any block to your sites widget areas. Dont worry, all of your favorite widgets still work flawlessly.')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button
// TODO: Switch to `true` (40px size) if possible
, {
__next40pxDefaultSize: false,
className: "customize-widgets-welcome-guide__button",
variant: "primary",
onClick: () => toggle('core/customize-widgets', 'welcomeGuide'),
@@ -1704,7 +1705,10 @@ function SidebarBlockEditor({
get
} = select(external_wp_preferences_namespaceObject.store);
return {
hasUploadPermissions: (_select$canUser = select(external_wp_coreData_namespaceObject.store).canUser('create', 'media')) !== null && _select$canUser !== void 0 ? _select$canUser : true,
hasUploadPermissions: (_select$canUser = select(external_wp_coreData_namespaceObject.store).canUser('create', {
kind: 'root',
name: 'media'
})) !== null && _select$canUser !== void 0 ? _select$canUser : true,
isFixedToolbarActive: !!get('core/customize-widgets', 'fixedToolbar'),
keepCaretInsideBlock: !!get('core/customize-widgets', 'keepCaretInsideBlock'),
isWelcomeGuideActive: !!get('core/customize-widgets', 'welcomeGuide')
@@ -2611,7 +2615,7 @@ const withMoveToSidebarToolbarItem = (0,external_wp_compose_namespaceObject.crea
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(BlockEdit, {
...props
}), hasMultipleSidebars && canInsertBlockInSidebar && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.BlockControls, {
}, "edit"), hasMultipleSidebars && canInsertBlockInSidebar && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.BlockControls, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_widgets_namespaceObject.MoveToWidgetArea, {
widgetAreas: sidebarControls.map(sidebarControl => ({
id: sidebarControl.id,
@@ -2654,7 +2658,7 @@ const withWideWidgetDisplay = (0,external_wp_compose_namespaceObject.createHighe
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(BlockEdit, {
...props,
isWide: isWide
});
}, "edit");
}, 'withWideWidgetDisplay');
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/customize-widgets/wide-widget-display', withWideWidgetDisplay);
@@ -2729,10 +2733,12 @@ function initialize(editorName, blockEditorSettings) {
sidebarControls.push(control);
}
});
(0,external_wp_element_namespaceObject.createRoot)(container).render( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(CustomizeWidgets, {
api: build_module_wp.customize,
sidebarControls: sidebarControls,
blockEditorSettings: blockEditorSettings
(0,external_wp_element_namespaceObject.createRoot)(container).render( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_element_namespaceObject.StrictMode, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(CustomizeWidgets, {
api: build_module_wp.customize,
sidebarControls: sidebarControls,
blockEditorSettings: blockEditorSettings
})
}));
});
}
File diff suppressed because one or more lines are too long
+6 -6
View File
@@ -3820,7 +3820,7 @@ const {
* children components. Used along with the RegistryProvider.
*
* You can read more about the react context api here:
* https://reactjs.org/docs/context.html#contextprovider
* https://react.dev/learn/passing-data-deeply-with-context#step-3-provide-the-context
*
* @example
* ```js
@@ -4177,7 +4177,7 @@ function useMappingSelect(suspense, mapSelect, deps) {
* Custom react hook for retrieving props from registered selectors.
*
* In general, this custom React hook follows the
* [rules of hooks](https://reactjs.org/docs/hooks-rules.html).
* [rules of hooks](https://react.dev/reference/rules/rules-of-hooks).
*
* @template {MapSelect | StoreDescriptor<any>} T
* @param {T} mapSelect Function called on every state change. The returned value is
@@ -4372,18 +4372,18 @@ const withSelect = mapSelectToProps => (0,external_wp_compose_namespaceObject.cr
*/
const useDispatchWithMap = (dispatchMap, deps) => {
const registry = useRegistry();
const currentDispatchMap = (0,external_wp_element_namespaceObject.useRef)(dispatchMap);
const currentDispatchMapRef = (0,external_wp_element_namespaceObject.useRef)(dispatchMap);
(0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
currentDispatchMap.current = dispatchMap;
currentDispatchMapRef.current = dispatchMap;
});
return (0,external_wp_element_namespaceObject.useMemo)(() => {
const currentDispatchProps = currentDispatchMap.current(registry.dispatch, registry);
const currentDispatchProps = currentDispatchMapRef.current(registry.dispatch, registry);
return Object.fromEntries(Object.entries(currentDispatchProps).map(([propName, dispatcher]) => {
if (typeof dispatcher !== 'function') {
// eslint-disable-next-line no-console
console.warn(`Property ${propName} returned from dispatchMap in useDispatchWithMap must be a function.`);
}
return [propName, (...args) => currentDispatchMap.current(registry.dispatch, registry)[propName](...args)];
return [propName, (...args) => currentDispatchMapRef.current(registry.dispatch, registry)[propName](...args)];
}));
}, [registry, ...deps]);
};
+2
View File
@@ -70,6 +70,7 @@ __webpack_require__.d(__webpack_exports__, {
isNumberInput: () => (/* reexport */ isNumberInput),
isPhrasingContent: () => (/* reexport */ isPhrasingContent),
isRTL: () => (/* reexport */ isRTL),
isSelectionForward: () => (/* reexport */ isSelectionForward),
isTextContent: () => (/* reexport */ isTextContent),
isTextField: () => (/* reexport */ isTextField),
isVerticalEdge: () => (/* reexport */ isVerticalEdge),
@@ -1965,6 +1966,7 @@ function removeInvalidHTML(HTML, schema, inline) {
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/data-transfer.js
+1 -1
View File
File diff suppressed because one or more lines are too long
+885 -696
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+15795 -14691
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+122 -85
View File
@@ -815,6 +815,17 @@ const external_wp_plugins_namespaceObject = window["wp"]["plugins"];
/**
* Whether the role supports checked state.
*
* @param {import('react').AriaRole} role Role.
* @return {boolean} Whether the role supports checked state.
* @see https://www.w3.org/TR/wai-aria-1.1/#aria-checked
*/
function roleSupportsCheckedState(role) {
return ['checkbox', 'option', 'radio', 'switch', 'menuitemcheckbox', 'menuitemradio', 'treeitem'].includes(role);
}
function ComplementaryAreaToggle({
as = external_wp_components_namespaceObject.Button,
scope,
@@ -822,6 +833,7 @@ function ComplementaryAreaToggle({
icon,
selectedIcon,
name,
shortcut,
...props
}) {
const ComponentToUse = as;
@@ -832,7 +844,10 @@ function ComplementaryAreaToggle({
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ComponentToUse, {
icon: selectedIcon && isSelected ? selectedIcon : icon,
"aria-controls": identifier.replace('/', ':'),
"aria-controls": identifier.replace('/', ':')
// Make sure aria-checked matches spec https://www.w3.org/TR/wai-aria-1.1/#aria-checked
,
"aria-checked": roleSupportsCheckedState(props.role) ? isSelected : undefined,
onClick: () => {
if (isSelected) {
disableComplementaryArea(scope);
@@ -840,6 +855,7 @@ function ComplementaryAreaToggle({
enableComplementaryArea(scope, identifier);
}
},
shortcut: shortcut,
...props
});
}
@@ -1151,8 +1167,8 @@ function ComplementaryAreaFill({
});
}
function useAdjustComplementaryListener(scope, identifier, activeArea, isActive, isSmall) {
const previousIsSmall = (0,external_wp_element_namespaceObject.useRef)(false);
const shouldOpenWhenNotSmall = (0,external_wp_element_namespaceObject.useRef)(false);
const previousIsSmallRef = (0,external_wp_element_namespaceObject.useRef)(false);
const shouldOpenWhenNotSmallRef = (0,external_wp_element_namespaceObject.useRef)(false);
const {
enableComplementaryArea,
disableComplementaryArea
@@ -1160,29 +1176,29 @@ function useAdjustComplementaryListener(scope, identifier, activeArea, isActive,
(0,external_wp_element_namespaceObject.useEffect)(() => {
// If the complementary area is active and the editor is switching from
// a big to a small window size.
if (isActive && isSmall && !previousIsSmall.current) {
if (isActive && isSmall && !previousIsSmallRef.current) {
disableComplementaryArea(scope);
// Flag the complementary area to be reopened when the window size
// goes from small to big.
shouldOpenWhenNotSmall.current = true;
shouldOpenWhenNotSmallRef.current = true;
} else if (
// If there is a flag indicating the complementary area should be
// enabled when we go from small to big window size and we are going
// from a small to big window size.
shouldOpenWhenNotSmall.current && !isSmall && previousIsSmall.current) {
shouldOpenWhenNotSmallRef.current && !isSmall && previousIsSmallRef.current) {
// Remove the flag indicating the complementary area should be
// enabled.
shouldOpenWhenNotSmall.current = false;
shouldOpenWhenNotSmallRef.current = false;
enableComplementaryArea(scope, identifier);
} else if (
// If the flag is indicating the current complementary should be
// reopened but another complementary area becomes active, remove
// the flag.
shouldOpenWhenNotSmall.current && activeArea && activeArea !== identifier) {
shouldOpenWhenNotSmall.current = false;
shouldOpenWhenNotSmallRef.current && activeArea && activeArea !== identifier) {
shouldOpenWhenNotSmallRef.current = false;
}
if (isSmall !== previousIsSmall.current) {
previousIsSmall.current = isSmall;
if (isSmall !== previousIsSmallRef.current) {
previousIsSmallRef.current = isSmall;
}
}, [isActive, isSmall, scope, identifier, activeArea, disableComplementaryArea, enableComplementaryArea]);
}
@@ -1269,7 +1285,8 @@ function ComplementaryArea({
icon: showIconLabels ? library_check : icon,
showTooltip: !showIconLabels,
variant: showIconLabels ? 'tertiary' : undefined,
size: "compact"
size: "compact",
shortcut: toggleShortcut
})
}), name && isPinnable && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ComplementaryAreaMoreMenuItem, {
target: name,
@@ -1320,19 +1337,25 @@ ComplementaryAreaWrapped.Slot = ComplementaryAreaSlot;
/* harmony default export */ const complementary_area = (ComplementaryAreaWrapped);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/navigable-region/index.js
/**
* WordPress dependencies
*/
/**
* External dependencies
*/
function NavigableRegion({
const NavigableRegion = (0,external_wp_element_namespaceObject.forwardRef)(({
children,
className,
ariaLabel,
as: Tag = 'div',
...props
}) {
}, ref) => {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Tag, {
ref: ref,
className: dist_clsx('interface-navigable-region', className),
"aria-label": ariaLabel,
role: "region",
@@ -1340,7 +1363,9 @@ function NavigableRegion({
...props,
children: children
});
}
});
NavigableRegion.displayName = 'NavigableRegion';
/* harmony default export */ const navigable_region = (NavigableRegion);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/interface-skeleton/index.js
/**
@@ -1422,11 +1447,7 @@ function InterfaceSkeleton({
content,
actions,
labels,
className,
enableRegionNavigation = true,
// Todo: does this need to be a prop.
// Can we use a dependency to keyboard-shortcuts directly?
shortcuts
className
}, ref) {
const [secondarySidebarResizeListener, secondarySidebarSize] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
@@ -1436,7 +1457,6 @@ function InterfaceSkeleton({
duration: disableMotion ? 0 : interface_skeleton_ANIMATION_DURATION,
ease: [0.6, 0, 0.4, 1]
};
const navigateRegionsProps = (0,external_wp_components_namespaceObject.__unstableUseNavigateRegions)(shortcuts);
useHTMLClass('interface-interface-skeleton__html-container');
const defaultLabels = {
/* translators: accessibility text for the top bar landmark region. */
@@ -1446,7 +1466,7 @@ function InterfaceSkeleton({
/* translators: accessibility text for the secondary sidebar landmark region. */
secondarySidebar: (0,external_wp_i18n_namespaceObject.__)('Block Library'),
/* translators: accessibility text for the settings landmark region. */
sidebar: (0,external_wp_i18n_namespaceObject.__)('Settings'),
sidebar: (0,external_wp_i18n_namespaceObject._x)('Settings', 'settings landmark area'),
/* translators: accessibility text for the publish landmark region. */
actions: (0,external_wp_i18n_namespaceObject.__)('Publish'),
/* translators: accessibility text for the footer landmark region. */
@@ -1457,21 +1477,20 @@ function InterfaceSkeleton({
...labels
};
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("div", {
...(enableRegionNavigation ? navigateRegionsProps : {}),
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, enableRegionNavigation ? navigateRegionsProps.ref : undefined]),
className: dist_clsx(className, 'interface-interface-skeleton', navigateRegionsProps.className, !!footer && 'has-footer'),
ref: ref,
className: dist_clsx(className, 'interface-interface-skeleton', !!footer && 'has-footer'),
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("div", {
className: "interface-interface-skeleton__editor",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__unstableAnimatePresence, {
initial: false,
children: !!header && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(NavigableRegion, {
children: !!header && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(navigable_region, {
as: external_wp_components_namespaceObject.__unstableMotion.div,
className: "interface-interface-skeleton__header",
"aria-label": mergedLabels.header,
initial: isDistractionFree ? 'distractionFreeHidden' : 'hidden',
whileHover: isDistractionFree ? 'distractionFreeHover' : 'visible',
animate: isDistractionFree ? 'distractionFreeDisabled' : 'visible',
exit: isDistractionFree ? 'distractionFreeHidden' : 'hidden',
initial: isDistractionFree && !isMobileViewport ? 'distractionFreeHidden' : 'hidden',
whileHover: isDistractionFree && !isMobileViewport ? 'distractionFreeHover' : 'visible',
animate: isDistractionFree && !isMobileViewport ? 'distractionFreeDisabled' : 'visible',
exit: isDistractionFree && !isMobileViewport ? 'distractionFreeHidden' : 'hidden',
variants: headerVariants,
transition: defaultTransition,
children: header
@@ -1483,12 +1502,12 @@ function InterfaceSkeleton({
className: "interface-interface-skeleton__body",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__unstableAnimatePresence, {
initial: false,
children: !!secondarySidebar && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(NavigableRegion, {
children: !!secondarySidebar && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(navigable_region, {
className: "interface-interface-skeleton__secondary-sidebar",
ariaLabel: mergedLabels.secondarySidebar,
as: external_wp_components_namespaceObject.__unstableMotion.div,
initial: "closed",
animate: isMobileViewport ? 'mobileOpen' : 'open',
animate: "open",
exit: "closed",
variants: {
open: {
@@ -1496,37 +1515,43 @@ function InterfaceSkeleton({
},
closed: {
width: 0
},
mobileOpen: {
width: '100vw'
}
},
transition: defaultTransition,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("div", {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__unstableMotion.div, {
style: {
position: 'absolute',
width: isMobileViewport ? '100vw' : 'fit-content',
height: '100%',
right: 0
left: 0
},
variants: {
open: {
x: 0
},
closed: {
x: '-100%'
}
},
transition: defaultTransition,
children: [secondarySidebarResizeListener, secondarySidebar]
})
})
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(NavigableRegion, {
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(navigable_region, {
className: "interface-interface-skeleton__content",
ariaLabel: mergedLabels.body,
children: content
}), !!sidebar && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(NavigableRegion, {
}), !!sidebar && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(navigable_region, {
className: "interface-interface-skeleton__sidebar",
ariaLabel: mergedLabels.sidebar,
children: sidebar
}), !!actions && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(NavigableRegion, {
}), !!actions && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(navigable_region, {
className: "interface-interface-skeleton__actions",
ariaLabel: mergedLabels.actions,
children: actions
})]
})]
}), !!footer && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(NavigableRegion, {
}), !!footer && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(navigable_region, {
className: "interface-interface-skeleton__footer",
ariaLabel: mergedLabels.footer,
children: footer
@@ -2169,16 +2194,16 @@ const EMPTY_INSERTION_POINT = {
*
* @return {Object[]} API List of widgets.
*/
const selectors_getWidgets = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
const selectors_getWidgets = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (0,external_wp_data_namespaceObject.createSelector)(() => {
var _widgets$reduce;
const widgets = select(external_wp_coreData_namespaceObject.store).getEntityRecords('root', 'widget', buildWidgetsQuery());
return (
// Key widgets by their ID.
widgets?.reduce((allWidgets, widget) => ({
return (// Key widgets by their ID.
(_widgets$reduce = widgets?.reduce((allWidgets, widget) => ({
...allWidgets,
[widget.id]: widget
}), {}) || {}
}), {})) !== null && _widgets$reduce !== void 0 ? _widgets$reduce : {}
);
});
}, () => [select(external_wp_coreData_namespaceObject.store).getEntityRecords('root', 'widget', buildWidgetsQuery())]));
/**
* Returns API widget data for a particular widget ID.
@@ -2499,7 +2524,7 @@ const withMoveToWidgetAreaToolbarItem = (0,external_wp_compose_namespaceObject.c
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(BlockEdit, {
...props
}), isMoveToWidgetAreaVisible && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.BlockControls, {
}, "edit"), isMoveToWidgetAreaVisible && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.BlockControls, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_widgets_namespaceObject.MoveToWidgetArea, {
widgetAreas: widgetAreas,
currentWidgetAreaId: currentWidgetAreaId,
@@ -2805,6 +2830,7 @@ function CopyButton({
}) {
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(text);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
variant: "secondary",
ref: ref,
children: children
@@ -3067,30 +3093,37 @@ const {
const {
BlockKeyboardShortcuts
} = unlock(external_wp_blockLibrary_namespaceObject.privateApis);
const EMPTY_ARRAY = [];
function WidgetAreasBlockEditorProvider({
blockEditorSettings,
children,
...props
}) {
const mediaPermissions = (0,external_wp_coreData_namespaceObject.useResourcePermissions)('media');
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
const {
hasUploadPermissions,
reusableBlocks,
isFixedToolbarActive,
keepCaretInsideBlock,
pageOnFront,
pageForPosts
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _canUser;
const {
canUser,
getEntityRecord,
getEntityRecords
} = select(external_wp_coreData_namespaceObject.store);
const siteSettings = canUser('read', 'settings') ? getEntityRecord('root', 'site') : undefined;
const siteSettings = canUser('read', {
kind: 'root',
name: 'site'
}) ? getEntityRecord('root', 'site') : undefined;
return {
widgetAreas: select(store_store).getWidgetAreas(),
widgets: select(store_store).getWidgets(),
reusableBlocks: ALLOW_REUSABLE_BLOCKS ? getEntityRecords('postType', 'wp_block') : [],
hasUploadPermissions: (_canUser = canUser('create', {
kind: 'root',
name: 'media'
})) !== null && _canUser !== void 0 ? _canUser : true,
reusableBlocks: ALLOW_REUSABLE_BLOCKS ? getEntityRecords('postType', 'wp_block') : EMPTY_ARRAY,
isFixedToolbarActive: !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'fixedToolbar'),
keepCaretInsideBlock: !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'keepCaretInsideBlock'),
pageOnFront: siteSettings?.page_on_front,
@@ -3102,7 +3135,7 @@ function WidgetAreasBlockEditorProvider({
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const settings = (0,external_wp_element_namespaceObject.useMemo)(() => {
let mediaUploadBlockEditor;
if (mediaPermissions.canCreate) {
if (hasUploadPermissions) {
mediaUploadBlockEditor = ({
onError,
...argumentsObject
@@ -3127,7 +3160,7 @@ function WidgetAreasBlockEditorProvider({
pageOnFront,
pageForPosts
};
}, [blockEditorSettings, isFixedToolbarActive, isLargeViewport, keepCaretInsideBlock, mediaPermissions.canCreate, reusableBlocks, setIsInserterOpened, pageOnFront, pageForPosts]);
}, [hasUploadPermissions, blockEditorSettings, isFixedToolbarActive, isLargeViewport, keepCaretInsideBlock, reusableBlocks, setIsInserterOpened, pageOnFront, pageForPosts]);
const widgetAreaId = use_last_selected_widget_area();
const [blocks, onInput, onChange] = (0,external_wp_coreData_namespaceObject.useEntityBlockEditor)(KIND, POST_TYPE, {
id: buildWidgetAreasPostId()
@@ -3254,6 +3287,7 @@ function WidgetAreas({
}), widgetAreas?.length === 0 && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("p", {
children: (0,external_wp_i18n_namespaceObject.__)('Your theme does not contain any Widget Areas.')
}), !selectedWidgetArea && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
href: (0,external_wp_url_namespaceObject.addQueryArgs)('customize.php', {
'autofocus[panel]': 'widgets',
return: window.location.pathname
@@ -4203,9 +4237,9 @@ function Header() {
})]
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("div", {
className: "edit-widgets-header__actions",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(save_button, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(pinned_items.Slot, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(pinned_items.Slot, {
scope: "core/edit-widgets"
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(MoreMenu, {})]
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(save_button, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(MoreMenu, {})]
})]
})
});
@@ -4296,7 +4330,7 @@ function WidgetAreasBlockEditorContent({
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_blockEditor_namespaceObject.BlockTools, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(keyboard_shortcuts, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.__unstableEditorStyles, {
styles: styles,
scope: ".editor-styles-wrapper"
scope: ":where(.editor-styles-wrapper)"
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.BlockSelectionClearer, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.WritingFlow, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.BlockList, {
@@ -4318,7 +4352,7 @@ const close_close = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
d: "M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"
d: "m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z"
})
});
/* harmony default export */ const library_close = (close_close);
@@ -4423,6 +4457,7 @@ function InserterSidebar() {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(TagName, {
className: "edit-widgets-layout__inserter-panel-header",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
icon: library_close,
onClick: closeInserter,
label: (0,external_wp_i18n_namespaceObject.__)('Close block inserter')
@@ -4495,6 +4530,7 @@ function ListViewSidebar() {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("strong", {
children: (0,external_wp_i18n_namespaceObject.__)('List View')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
icon: close_small,
label: (0,external_wp_i18n_namespaceObject.__)('Close'),
onClick: closeListView
@@ -4561,7 +4597,6 @@ function SecondarySidebar() {
/**
* Internal dependencies
*/
@@ -4595,16 +4630,12 @@ function Interface({
hasBlockBreadCrumbsEnabled,
hasSidebarEnabled,
isInserterOpened,
isListViewOpened,
previousShortcut,
nextShortcut
isListViewOpened
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
hasSidebarEnabled: !!select(store).getActiveComplementaryArea(store_store.name),
isInserterOpened: !!select(store_store).isInserterOpened(),
isListViewOpened: !!select(store_store).isListViewOpened(),
hasBlockBreadCrumbsEnabled: !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'showBlockBreadcrumbs'),
previousShortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getAllShortcutKeyCombinations('core/edit-widgets/previous-region'),
nextShortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getAllShortcutKeyCombinations('core/edit-widgets/next-region')
hasBlockBreadCrumbsEnabled: !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'showBlockBreadcrumbs')
}), []);
// Inserter and Sidebars are mutually exclusive
@@ -4641,11 +4672,7 @@ function Interface({
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.BlockBreadcrumb, {
rootLabelText: (0,external_wp_i18n_namespaceObject.__)('Widgets')
})
}),
shortcuts: {
previous: previousShortcut,
next: nextShortcut
}
})
});
}
/* harmony default export */ const layout_interface = (Interface);
@@ -4811,12 +4838,13 @@ function WelcomeGuide() {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("h1", {
className: "edit-widgets-welcome-guide__heading",
children: (0,external_wp_i18n_namespaceObject.__)('Learn how to use the block editor')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("p", {
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("p", {
className: "edit-widgets-welcome-guide__text",
children: [(0,external_wp_i18n_namespaceObject.__)('New to the block editor? Want to learn more about using it? '), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/documentation/article/wordpress-block-editor/'),
children: (0,external_wp_i18n_namespaceObject.__)("Here's a detailed guide.")
})]
children: (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.__)("New to the block editor? Want to learn more about using it? <a>Here's a detailed guide.</a>"), {
a: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/documentation/article/wordpress-block-editor/')
})
})
})]
})
}]
@@ -4849,6 +4877,7 @@ function WelcomeGuideImage({
/**
* Internal dependencies
*/
@@ -4870,14 +4899,20 @@ function Layout({
createErrorNotice((0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %s: plugin name */
(0,external_wp_i18n_namespaceObject.__)('The "%s" plugin has encountered an error and cannot be rendered.'), name));
}
const navigateRegionsProps = (0,external_wp_components_namespaceObject.__unstableUseNavigateRegions)();
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ErrorBoundary, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(WidgetAreasBlockEditorProvider, {
blockEditorSettings: blockEditorSettings,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(layout_interface, {
blockEditorSettings: blockEditorSettings
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Sidebar, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_plugins_namespaceObject.PluginArea, {
onError: onPluginAreaError
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(UnsavedChangesWarning, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(WelcomeGuide, {})]
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("div", {
className: navigateRegionsProps.className,
...navigateRegionsProps,
ref: navigateRegionsProps.ref,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(WidgetAreasBlockEditorProvider, {
blockEditorSettings: blockEditorSettings,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(layout_interface, {
blockEditorSettings: blockEditorSettings
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(Sidebar, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_plugins_namespaceObject.PluginArea, {
onError: onPluginAreaError
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(UnsavedChangesWarning, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(WelcomeGuide, {})]
})
})
});
}
@@ -4939,8 +4974,10 @@ function initializeEditor(id, settings) {
// do this will result in errors in the default block parser.
// see: https://github.com/WordPress/gutenberg/issues/33097
(0,external_wp_blocks_namespaceObject.setFreeformContentHandlerName)('core/html');
root.render( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(layout, {
blockEditorSettings: settings
root.render( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_element_namespaceObject.StrictMode, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(layout, {
blockEditorSettings: settings
})
}));
return root;
}
File diff suppressed because one or more lines are too long
+5431 -3315
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+58 -36
View File
@@ -472,12 +472,26 @@ function closeOuterElement(endOffset) {
*/
/**
* Object containing a React synthetic event.
* Object containing a React ref object.
*
* @template T
* @typedef {import('react').RefObject<T>} RefObject<T>
*/
/**
* Object containing a React ref callback.
*
* @template T
* @typedef {import('react').RefCallback<T>} RefCallback<T>
*/
/**
* Object containing a React ref.
*
* @template T
* @typedef {import('react').Ref<T>} Ref<T>
*/
/**
* Object that provides utilities for dealing with React children.
*/
@@ -558,7 +572,7 @@ function closeOuterElement(endOffset) {
/**
* @see https://reactjs.org/docs/react-api.html#reactmemo
* @see https://react.dev/reference/react/memo
*/
@@ -568,97 +582,97 @@ function closeOuterElement(endOffset) {
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecallback
* @see https://react.dev/reference/react/useCallback
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usecontext
* @see https://react.dev/reference/react/useContext
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedebugvalue
* @see https://react.dev/reference/react/useDebugValue
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usedeferredvalue
* @see https://react.dev/reference/react/useDeferredValue
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useeffect
* @see https://react.dev/reference/react/useEffect
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useid
* @see https://react.dev/reference/react/useId
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useimperativehandle
* @see https://react.dev/reference/react/useImperativeHandle
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useinsertioneffect
* @see https://react.dev/reference/react/useInsertionEffect
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#uselayouteffect
* @see https://react.dev/reference/react/useLayoutEffect
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usememo
* @see https://react.dev/reference/react/useMemo
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usereducer
* @see https://react.dev/reference/react/useReducer
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#useref
* @see https://react.dev/reference/react/useRef
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usestate
* @see https://react.dev/reference/react/useState
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore
* @see https://react.dev/reference/react/useSyncExternalStore
*/
/**
* @see https://reactjs.org/docs/hooks-reference.html#usetransition
* @see https://react.dev/reference/react/useTransition
*/
/**
* @see https://reactjs.org/docs/react-api.html#starttransition
* @see https://react.dev/reference/react/startTransition
*/
/**
* @see https://reactjs.org/docs/react-api.html#reactlazy
* @see https://react.dev/reference/react/lazy
*/
/**
* @see https://reactjs.org/docs/react-api.html#reactsuspense
* @see https://react.dev/reference/react/Suspense
*/
/**
* @see https://reactjs.org/docs/react-api.html#reactpurecomponent
* @see https://react.dev/reference/react/PureComponent
*/
@@ -888,7 +902,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
@@ -999,8 +1013,8 @@ function __awaiter(thisArg, _arguments, P, generator) {
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
@@ -1104,8 +1118,9 @@ function __await(v) {
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
@@ -1171,16 +1186,18 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
@@ -1199,17 +1216,22 @@ function __disposeResources(env) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
while (r = env.stack.pop()) {
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
+16 -18
View File
@@ -57,9 +57,9 @@ __webpack_require__.d(__webpack_exports__, {
*
* See: https://core.trac.wordpress.org/ticket/45387
*
* @param {string} value Original string.
* @param value Original string.
*
* @return {string} Escaped string.
* @return Escaped string.
*/
function __unstableEscapeGreaterThan(value) {
return value.replace(/>/g, '&gt;');
@@ -79,8 +79,6 @@ function __unstableEscapeGreaterThan(value) {
* and noncharacters."
*
* @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
*
* @type {RegExp}
*/
const REGEXP_INVALID_ATTRIBUTE_NAME = /[\u007F-\u009F "'>/="\uFDD0-\uFDEF]/;
@@ -94,9 +92,9 @@ const REGEXP_INVALID_ATTRIBUTE_NAME = /[\u007F-\u009F "'>/="\uFDD0-\uFDEF]/;
* @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.
* @param value Original string.
*
* @return {string} Escaped string.
* @return Escaped string.
*/
function escapeAmpersand(value) {
return value.replace(/&(?!([a-z0-9]+|#[0-9]+|#x[a-f0-9]+);)/gi, '&amp;');
@@ -105,9 +103,9 @@ function escapeAmpersand(value) {
/**
* Returns a string with quotation marks replaced.
*
* @param {string} value Original string.
* @param value Original string.
*
* @return {string} Escaped string.
* @return Escaped string.
*/
function escapeQuotationMark(value) {
return value.replace(/"/g, '&quot;');
@@ -116,9 +114,9 @@ function escapeQuotationMark(value) {
/**
* Returns a string with less-than sign replaced.
*
* @param {string} value Original string.
* @param value Original string.
*
* @return {string} Escaped string.
* @return Escaped string.
*/
function escapeLessThan(value) {
return value.replace(/</g, '&lt;');
@@ -140,9 +138,9 @@ function escapeLessThan(value) {
*
* See: https://core.trac.wordpress.org/ticket/45387
*
* @param {string} value Attribute value.
* @param value Attribute value.
*
* @return {string} Escaped attribute value.
* @return Escaped attribute value.
*/
function escapeAttribute(value) {
return __unstableEscapeGreaterThan(escapeQuotationMark(escapeAmpersand(value)));
@@ -156,9 +154,9 @@ function escapeAttribute(value) {
* "the text must not contain the character U+003C LESS-THAN SIGN (<) or an
* ambiguous ampersand."
*
* @param {string} value Element value.
* @param value Element value.
*
* @return {string} Escaped HTML element value.
* @return Escaped HTML element value.
*/
function escapeHTML(value) {
return escapeLessThan(escapeAmpersand(value));
@@ -169,9 +167,9 @@ function escapeHTML(value) {
* `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.
* @param value Element value.
*
* @return {string} Escaped HTML element value.
* @return Escaped HTML element value.
*/
function escapeEditableHTML(value) {
return escapeLessThan(value.replace(/&/g, '&amp;'));
@@ -180,9 +178,9 @@ function escapeEditableHTML(value) {
/**
* Returns true if the given attribute name is valid, or false otherwise.
*
* @param {string} name Attribute name to test.
* @param name Attribute name to test.
*
* @return {boolean} Whether attribute is valid.
* @return Whether attribute is valid.
*/
function isValidAttributeName(name) {
return !REGEXP_INVALID_ATTRIBUTE_NAME.test(name);
+1951
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+63 -40
View File
@@ -199,20 +199,6 @@ const code_code = {
const external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: external ["wp","element"]
const external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/keyboard-return.js
/**
* WordPress dependencies
*/
const keyboardReturn = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
d: "m6.734 16.106 2.176-2.38-1.093-1.028-3.846 4.158 3.846 4.158 1.093-1.028-2.176-2.38h2.811c1.125 0 2.25.03 3.374 0 1.428-.001 3.362-.25 4.963-1.277 1.66-1.065 2.868-2.906 2.868-5.859 0-2.479-1.327-4.896-3.65-5.93-1.82-.813-3.044-.8-4.806-.788l-.567.002v1.5c.184 0 .368 0 .553-.002 1.82-.007 2.704-.014 4.21.657 1.854.827 2.76 2.657 2.76 4.561 0 2.472-.973 3.824-2.178 4.596-1.258.807-2.864 1.04-4.163 1.04h-.02c-1.115.03-2.229 0-3.344 0H6.734Z"
})
});
/* harmony default export */ const keyboard_return = (keyboardReturn);
;// CONCATENATED MODULE: ./node_modules/@wordpress/format-library/build-module/image/index.js
/**
* WordPress dependencies
@@ -250,9 +236,13 @@ function InlineUI({
contentRef
}) {
const {
style
style,
alt
} = activeObjectAttributes;
const [width, setWidth] = (0,external_wp_element_namespaceObject.useState)(style?.replace(/\D/g, ''));
const width = style?.replace(/\D/g, '');
const [editedWidth, setEditedWidth] = (0,external_wp_element_namespaceObject.useState)(width);
const [editedAlt, setEditedAlt] = (0,external_wp_element_namespaceObject.useState)(alt);
const hasChanged = editedWidth !== width || editedAlt !== alt;
const popoverAnchor = (0,external_wp_richText_namespaceObject.useAnchor)({
editableContentElement: contentRef.current,
settings: image_image
@@ -270,7 +260,8 @@ function InlineUI({
type: image_name,
attributes: {
...activeObjectAttributes,
style: width ? `width: ${width}px;` : ''
style: width ? `width: ${editedWidth}px;` : '',
alt: editedAlt
}
};
onChange({
@@ -279,20 +270,41 @@ function InlineUI({
});
event.preventDefault();
},
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__experimentalHStack, {
alignment: "bottom",
spacing: "0",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: 4,
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__experimentalNumberControl, {
className: "block-editor-format-toolbar__image-container-value",
__next40pxDefaultSize: true,
label: (0,external_wp_i18n_namespaceObject.__)('Width'),
value: width,
value: editedWidth,
min: 1,
onChange: newWidth => setWidth(newWidth)
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
className: "block-editor-format-toolbar__image-container-button",
icon: keyboard_return,
label: (0,external_wp_i18n_namespaceObject.__)('Apply'),
type: "submit"
onChange: newWidth => {
setEditedWidth(newWidth);
}
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.TextareaControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Alternative text'),
__nextHasNoMarginBottom: true,
value: editedAlt,
onChange: newAlt => {
setEditedAlt(newAlt);
},
help: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_ReactJSXRuntime_namespaceObject.Fragment, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ExternalLink, {
href:
// translators: Localized tutorial, if one exists. W3C Web Accessibility Initiative link has list of existing translations.
(0,external_wp_i18n_namespaceObject.__)('https://www.w3.org/WAI/tutorials/images/decision-tree/'),
children: (0,external_wp_i18n_namespaceObject.__)('Describe the purpose of the image.')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("br", {}), (0,external_wp_i18n_namespaceObject.__)('Leave empty if decorative.')]
})
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__experimentalHStack, {
justify: "right",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
disabled: !hasChanged,
accessibleWhenDisabled: true,
variant: "primary",
type: "submit",
size: "compact",
children: (0,external_wp_i18n_namespaceObject.__)('Apply')
})
})]
})
})
@@ -984,6 +996,13 @@ function link_Edit({
url: `mailto:${text}`
}
}));
} else if (!isActive && text && (0,external_wp_url_namespaceObject.isPhoneNumber)(text)) {
onChange((0,external_wp_richText_namespaceObject.applyFormat)(value, {
type: link_name,
attributes: {
url: `tel:${text.replace(/\D/g, '')}`
}
}));
} else {
if (target) {
setOpenedBy({
@@ -1412,15 +1431,14 @@ function ColorPicker({
} = select(external_wp_blockEditor_namespaceObject.store);
return (_getSettings$colors = getSettings().colors) !== null && _getSettings$colors !== void 0 ? _getSettings$colors : [];
}, []);
const onColorChange = (0,external_wp_element_namespaceObject.useCallback)(color => {
onChange(setColors(value, name, colors, {
[property]: color
}));
}, [colors, onChange, property]);
const activeColors = (0,external_wp_element_namespaceObject.useMemo)(() => getActiveColors(value, name, colors), [name, value, colors]);
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.ColorPalette, {
value: activeColors[property],
onChange: onColorChange
onChange: color => {
onChange(setColors(value, name, colors, {
[property]: color
}));
}
});
}
function InlineColorUI({
@@ -1518,9 +1536,7 @@ function TextColorEdit({
}) {
const [allowCustomControl, colors = EMPTY_ARRAY] = (0,external_wp_blockEditor_namespaceObject.useSettings)('color.custom', 'color.palette');
const [isAddingColor, setIsAddingColor] = (0,external_wp_element_namespaceObject.useState)(false);
const enableIsAddingColor = (0,external_wp_element_namespaceObject.useCallback)(() => setIsAddingColor(true), [setIsAddingColor]);
const disableIsAddingColor = (0,external_wp_element_namespaceObject.useCallback)(() => setIsAddingColor(false), [setIsAddingColor]);
const colorIndicatorStyle = (0,external_wp_element_namespaceObject.useMemo)(() => fillComputedColors(contentRef.current, getActiveColors(value, text_color_name, colors)), [value, colors]);
const colorIndicatorStyle = (0,external_wp_element_namespaceObject.useMemo)(() => fillComputedColors(contentRef.current, getActiveColors(value, text_color_name, colors)), [contentRef, value, colors]);
const hasColorsToChoose = colors.length || !allowCustomControl;
if (!hasColorsToChoose && !isActive) {
return null;
@@ -1536,11 +1552,11 @@ function TextColorEdit({
title: text_color_title
// If has no colors to choose but a color is active remove the color onClick.
,
onClick: hasColorsToChoose ? enableIsAddingColor : () => onChange((0,external_wp_richText_namespaceObject.removeFormat)(value, text_color_name)),
onClick: hasColorsToChoose ? () => setIsAddingColor(true) : () => onChange((0,external_wp_richText_namespaceObject.removeFormat)(value, text_color_name)),
role: "menuitemcheckbox"
}), isAddingColor && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(InlineColorUI, {
name: text_color_name,
onClose: disableIsAddingColor,
onClose: () => setIsAddingColor(false),
activeAttributes: activeAttributes,
value: value,
onChange: onChange,
@@ -1884,7 +1900,9 @@ function InlineLanguageUI({
className: "block-editor-format-toolbar__language-popover",
anchor: popoverAnchor,
onClose: onClose,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)("form", {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__experimentalVStack, {
as: "form",
spacing: 4,
className: "block-editor-format-toolbar__language-container-content",
onSubmit: event => {
event.preventDefault();
@@ -1898,11 +1916,15 @@ function InlineLanguageUI({
onClose();
},
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.TextControl, {
__next40pxDefaultSize: true,
__nextHasNoMarginBottom: true,
label: language_title,
value: lang,
onChange: val => setLang(val),
help: (0,external_wp_i18n_namespaceObject.__)('A valid language attribute, like "en" or "fr".')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.SelectControl, {
__next40pxDefaultSize: true,
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Text direction'),
value: dir,
options: [{
@@ -1916,6 +1938,7 @@ function InlineLanguageUI({
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__experimentalHStack, {
alignment: "right",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
variant: "primary",
type: "submit",
text: (0,external_wp_i18n_namespaceObject.__)('Apply')
File diff suppressed because one or more lines are too long
+54 -26
View File
@@ -43,6 +43,7 @@ __webpack_require__.d(__webpack_exports__, {
addAction: () => (/* binding */ addAction),
addFilter: () => (/* binding */ addFilter),
applyFilters: () => (/* binding */ applyFilters),
applyFiltersAsync: () => (/* binding */ applyFiltersAsync),
createHooks: () => (/* reexport */ build_module_createHooks),
currentAction: () => (/* binding */ currentAction),
currentFilter: () => (/* binding */ currentFilter),
@@ -50,6 +51,7 @@ __webpack_require__.d(__webpack_exports__, {
didAction: () => (/* binding */ didAction),
didFilter: () => (/* binding */ didFilter),
doAction: () => (/* binding */ doAction),
doActionAsync: () => (/* binding */ doActionAsync),
doingAction: () => (/* binding */ doingAction),
doingFilter: () => (/* binding */ doingFilter),
filters: () => (/* binding */ filters),
@@ -330,15 +332,15 @@ function createHasHook(hooks, storeKey) {
* 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('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
* @param {boolean} [returnFirstArg=false] Whether each hook callback is expected to
* return its first argument.
* @param {boolean} returnFirstArg Whether each hook callback is expected to return its first argument.
* @param {boolean} async Whether the hook callback should be run asynchronously
*
* @return {(hookName:string, ...args: unknown[]) => undefined|unknown} Function that runs hook callbacks.
*/
function createRunHook(hooks, storeKey, returnFirstArg = false) {
return function runHooks(hookName, ...args) {
function createRunHook(hooks, storeKey, returnFirstArg, async) {
return function runHook(hookName, ...args) {
const hooksStore = hooks[storeKey];
if (!hooksStore[hookName]) {
hooksStore[hookName] = {
@@ -358,20 +360,41 @@ function createRunHook(hooks, storeKey, returnFirstArg = false) {
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;
async function asyncRunner() {
try {
hooksStore.__current.add(hookInfo);
let result = returnFirstArg ? args[0] : undefined;
while (hookInfo.currentIndex < handlers.length) {
const handler = handlers[hookInfo.currentIndex];
result = await handler.callback.apply(null, args);
if (returnFirstArg) {
args[0] = result;
}
hookInfo.currentIndex++;
}
return returnFirstArg ? result : undefined;
} finally {
hooksStore.__current.delete(hookInfo);
}
hookInfo.currentIndex++;
}
hooksStore.__current.pop();
if (returnFirstArg) {
return args[0];
function syncRunner() {
try {
hooksStore.__current.add(hookInfo);
let result = returnFirstArg ? args[0] : undefined;
while (hookInfo.currentIndex < handlers.length) {
const handler = handlers[hookInfo.currentIndex];
result = handler.callback.apply(null, args);
if (returnFirstArg) {
args[0] = result;
}
hookInfo.currentIndex++;
}
return returnFirstArg ? result : undefined;
} finally {
hooksStore.__current.delete(hookInfo);
}
}
return undefined;
return (async ? asyncRunner : syncRunner)();
};
}
/* harmony default export */ const build_module_createRunHook = (createRunHook);
@@ -389,9 +412,10 @@ function createRunHook(hooks, storeKey, returnFirstArg = false) {
*/
function createCurrentHook(hooks, storeKey) {
return function currentHook() {
var _hooksStore$__current;
var _currentArray$at$name;
const hooksStore = hooks[storeKey];
return (_hooksStore$__current = hooksStore.__current[hooksStore.__current.length - 1]?.name) !== null && _hooksStore$__current !== void 0 ? _hooksStore$__current : null;
const currentArray = Array.from(hooksStore.__current);
return (_currentArray$at$name = currentArray.at(-1)?.name) !== null && _currentArray$at$name !== void 0 ? _currentArray$at$name : null;
};
}
/* harmony default export */ const build_module_createCurrentHook = (createCurrentHook);
@@ -423,11 +447,11 @@ function createDoingHook(hooks, storeKey) {
// If the hookName was not passed, check for any current hook.
if ('undefined' === typeof hookName) {
return 'undefined' !== typeof hooksStore.__current[0];
return hooksStore.__current.size > 0;
}
// Return the __current hook.
return hooksStore.__current[0] ? hookName === hooksStore.__current[0].name : false;
// Find if the `hookName` hook is in `__current`.
return Array.from(hooksStore.__current).some(hook => hook.name === hookName);
};
}
/* harmony default export */ const build_module_createDoingHook = (createDoingHook);
@@ -491,11 +515,11 @@ class _Hooks {
constructor() {
/** @type {import('.').Store} actions */
this.actions = Object.create(null);
this.actions.__current = [];
this.actions.__current = new Set();
/** @type {import('.').Store} filters */
this.filters = Object.create(null);
this.filters.__current = [];
this.filters.__current = new Set();
this.addAction = build_module_createAddHook(this, 'actions');
this.addFilter = build_module_createAddHook(this, 'filters');
this.removeAction = build_module_createRemoveHook(this, 'actions');
@@ -504,8 +528,10 @@ class _Hooks {
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.doAction = build_module_createRunHook(this, 'actions', false, false);
this.doActionAsync = build_module_createRunHook(this, 'actions', false, true);
this.applyFilters = build_module_createRunHook(this, 'filters', true, false);
this.applyFiltersAsync = build_module_createRunHook(this, 'filters', true, true);
this.currentAction = build_module_createCurrentHook(this, 'actions');
this.currentFilter = build_module_createCurrentHook(this, 'filters');
this.doingAction = build_module_createDoingHook(this, 'actions');
@@ -555,7 +581,7 @@ function createHooks() {
*/
/**
* @typedef {Record<string, Hook> & {__current: Current[]}} Store
* @typedef {Record<string, Hook> & {__current: Set<Current>}} Store
*/
/**
@@ -577,7 +603,9 @@ const {
removeAllActions,
removeAllFilters,
doAction,
doActionAsync,
applyFilters,
applyFiltersAsync,
currentAction,
currentFilter,
doingAction,
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{actions:()=>S,addAction:()=>m,addFilter:()=>p,applyFilters:()=>k,createHooks:()=>h,currentAction:()=>w,currentFilter:()=>I,defaultHooks:()=>f,didAction:()=>O,didFilter:()=>j,doAction:()=>b,doingAction:()=>x,doingFilter:()=>T,filters:()=>z,hasAction:()=>v,hasFilter:()=>y,removeAction:()=>A,removeAllActions:()=>F,removeAllFilters:()=>g,removeFilter:()=>_});const n=function(t){return"string"!=typeof t||""===t?(console.error("The namespace must be a non-empty string."),!1):!!/^[a-zA-Z][a-zA-Z0-9_.\-\/]*$/.test(t)||(console.error("The namespace can only contain numbers, letters, dashes, periods, underscores and slashes."),!1)};const r=function(t){return"string"!=typeof t||""===t?(console.error("The hook name must be a non-empty string."),!1):/^__/.test(t)?(console.error("The hook name cannot begin with `__`."),!1):!!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||(console.error("The hook name can only contain numbers, letters, dashes, periods and underscores."),!1)};const o=function(t,e){return function(o,i,s,c=10){const l=t[e];if(!r(o))return;if(!n(i))return;if("function"!=typeof s)return void console.error("The hook callback must be a function.");if("number"!=typeof c)return void console.error("If specified, the hook priority must be a number.");const u={callback:s,priority:c,namespace:i};if(l[o]){const t=l[o].handlers;let e;for(e=t.length;e>0&&!(c>=t[e-1].priority);e--);e===t.length?t[e]=u:t.splice(e,0,u),l.__current.forEach((t=>{t.name===o&&t.currentIndex>=e&&t.currentIndex++}))}else l[o]={handlers:[u],runs:0};"hookAdded"!==o&&t.doAction("hookAdded",o,i,s,c)}};const i=function(t,e,o=!1){return function(i,s){const c=t[e];if(!r(i))return;if(!o&&!n(s))return;if(!c[i])return 0;let l=0;if(o)l=c[i].handlers.length,c[i]={runs:c[i].runs,handlers:[]};else{const t=c[i].handlers;for(let e=t.length-1;e>=0;e--)t[e].namespace===s&&(t.splice(e,1),l++,c.__current.forEach((t=>{t.name===i&&t.currentIndex>=e&&t.currentIndex--})))}return"hookRemoved"!==i&&t.doAction("hookRemoved",i,s),l}};const s=function(t,e){return function(n,r){const o=t[e];return void 0!==r?n in o&&o[n].handlers.some((t=>t.namespace===r)):n in o}};const c=function(t,e,n=!1){return function(r,...o){const i=t[e];i[r]||(i[r]={handlers:[],runs:0}),i[r].runs++;const s=i[r].handlers;if(!s||!s.length)return n?o[0]:void 0;const c={name:r,currentIndex:0};for(i.__current.push(c);c.currentIndex<s.length;){const t=s[c.currentIndex].callback.apply(null,o);n&&(o[0]=t),c.currentIndex++}return i.__current.pop(),n?o[0]:void 0}};const l=function(t,e){return function(){var n;const r=t[e];return null!==(n=r.__current[r.__current.length-1]?.name)&&void 0!==n?n:null}};const u=function(t,e){return function(n){const r=t[e];return void 0===n?void 0!==r.__current[0]:!!r.__current[0]&&n===r.__current[0].name}};const a=function(t,e){return function(n){const o=t[e];if(r(n))return o[n]&&o[n].runs?o[n].runs:0}};class d{constructor(){this.actions=Object.create(null),this.actions.__current=[],this.filters=Object.create(null),this.filters.__current=[],this.addAction=o(this,"actions"),this.addFilter=o(this,"filters"),this.removeAction=i(this,"actions"),this.removeFilter=i(this,"filters"),this.hasAction=s(this,"actions"),this.hasFilter=s(this,"filters"),this.removeAllActions=i(this,"actions",!0),this.removeAllFilters=i(this,"filters",!0),this.doAction=c(this,"actions"),this.applyFilters=c(this,"filters",!0),this.currentAction=l(this,"actions"),this.currentFilter=l(this,"filters"),this.doingAction=u(this,"actions"),this.doingFilter=u(this,"filters"),this.didAction=a(this,"actions"),this.didFilter=a(this,"filters")}}const h=function(){return new d},f=h(),{addAction:m,addFilter:p,removeAction:A,removeFilter:_,hasAction:v,hasFilter:y,removeAllActions:F,removeAllFilters:g,doAction:b,applyFilters:k,currentAction:w,currentFilter:I,doingAction:x,doingFilter:T,didAction:O,didFilter:j,actions:S,filters:z}=f;(window.wp=window.wp||{}).hooks=e})();
(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{actions:()=>P,addAction:()=>A,addFilter:()=>m,applyFilters:()=>w,applyFiltersAsync:()=>I,createHooks:()=>h,currentAction:()=>x,currentFilter:()=>T,defaultHooks:()=>f,didAction:()=>j,didFilter:()=>z,doAction:()=>g,doActionAsync:()=>k,doingAction:()=>O,doingFilter:()=>S,filters:()=>Z,hasAction:()=>_,hasFilter:()=>v,removeAction:()=>p,removeAllActions:()=>F,removeAllFilters:()=>b,removeFilter:()=>y});const n=function(t){return"string"!=typeof t||""===t?(console.error("The namespace must be a non-empty string."),!1):!!/^[a-zA-Z][a-zA-Z0-9_.\-\/]*$/.test(t)||(console.error("The namespace can only contain numbers, letters, dashes, periods, underscores and slashes."),!1)};const r=function(t){return"string"!=typeof t||""===t?(console.error("The hook name must be a non-empty string."),!1):/^__/.test(t)?(console.error("The hook name cannot begin with `__`."),!1):!!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||(console.error("The hook name can only contain numbers, letters, dashes, periods and underscores."),!1)};const o=function(t,e){return function(o,i,s,c=10){const l=t[e];if(!r(o))return;if(!n(i))return;if("function"!=typeof s)return void console.error("The hook callback must be a function.");if("number"!=typeof c)return void console.error("If specified, the hook priority must be a number.");const a={callback:s,priority:c,namespace:i};if(l[o]){const t=l[o].handlers;let e;for(e=t.length;e>0&&!(c>=t[e-1].priority);e--);e===t.length?t[e]=a:t.splice(e,0,a),l.__current.forEach((t=>{t.name===o&&t.currentIndex>=e&&t.currentIndex++}))}else l[o]={handlers:[a],runs:0};"hookAdded"!==o&&t.doAction("hookAdded",o,i,s,c)}};const i=function(t,e,o=!1){return function(i,s){const c=t[e];if(!r(i))return;if(!o&&!n(s))return;if(!c[i])return 0;let l=0;if(o)l=c[i].handlers.length,c[i]={runs:c[i].runs,handlers:[]};else{const t=c[i].handlers;for(let e=t.length-1;e>=0;e--)t[e].namespace===s&&(t.splice(e,1),l++,c.__current.forEach((t=>{t.name===i&&t.currentIndex>=e&&t.currentIndex--})))}return"hookRemoved"!==i&&t.doAction("hookRemoved",i,s),l}};const s=function(t,e){return function(n,r){const o=t[e];return void 0!==r?n in o&&o[n].handlers.some((t=>t.namespace===r)):n in o}};const c=function(t,e,n,r){return function(o,...i){const s=t[e];s[o]||(s[o]={handlers:[],runs:0}),s[o].runs++;const c=s[o].handlers;if(!c||!c.length)return n?i[0]:void 0;const l={name:o,currentIndex:0};return(r?async function(){try{s.__current.add(l);let t=n?i[0]:void 0;for(;l.currentIndex<c.length;){const e=c[l.currentIndex];t=await e.callback.apply(null,i),n&&(i[0]=t),l.currentIndex++}return n?t:void 0}finally{s.__current.delete(l)}}:function(){try{s.__current.add(l);let t=n?i[0]:void 0;for(;l.currentIndex<c.length;){t=c[l.currentIndex].callback.apply(null,i),n&&(i[0]=t),l.currentIndex++}return n?t:void 0}finally{s.__current.delete(l)}})()}};const l=function(t,e){return function(){var n;const r=t[e],o=Array.from(r.__current);return null!==(n=o.at(-1)?.name)&&void 0!==n?n:null}};const a=function(t,e){return function(n){const r=t[e];return void 0===n?r.__current.size>0:Array.from(r.__current).some((t=>t.name===n))}};const u=function(t,e){return function(n){const o=t[e];if(r(n))return o[n]&&o[n].runs?o[n].runs:0}};class d{constructor(){this.actions=Object.create(null),this.actions.__current=new Set,this.filters=Object.create(null),this.filters.__current=new Set,this.addAction=o(this,"actions"),this.addFilter=o(this,"filters"),this.removeAction=i(this,"actions"),this.removeFilter=i(this,"filters"),this.hasAction=s(this,"actions"),this.hasFilter=s(this,"filters"),this.removeAllActions=i(this,"actions",!0),this.removeAllFilters=i(this,"filters",!0),this.doAction=c(this,"actions",!1,!1),this.doActionAsync=c(this,"actions",!1,!0),this.applyFilters=c(this,"filters",!0,!1),this.applyFiltersAsync=c(this,"filters",!0,!0),this.currentAction=l(this,"actions"),this.currentFilter=l(this,"filters"),this.doingAction=a(this,"actions"),this.doingFilter=a(this,"filters"),this.didAction=u(this,"actions"),this.didFilter=u(this,"filters")}}const h=function(){return new d},f=h(),{addAction:A,addFilter:m,removeAction:p,removeFilter:y,hasAction:_,hasFilter:v,removeAllActions:F,removeAllFilters:b,doAction:g,doActionAsync:k,applyFilters:w,applyFiltersAsync:I,currentAction:x,currentFilter:T,doingAction:O,doingFilter:S,didAction:j,didFilter:z,actions:P,filters:Z}=f;(window.wp=window.wp||{}).hooks=e})();
-1
View File
@@ -1 +0,0 @@
<?php return array('dependencies' => array(), 'version' => '93ff47d0e70d75545606');
@@ -1 +0,0 @@
<?php return array('dependencies' => array(), 'version' => 'cb44832cae5c937ebbc3');
-2
View File
@@ -1,2 +0,0 @@
/*! This file is auto-generated */
import*as e from"@wordpress/interactivity";var t={d:(e,o)=>{for(var i in o)t.o(o,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:o[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},o={};t.d(o,{o:()=>x,w:()=>b});const i=(e=>{var o={};return t.d(o,e),o})({getConfig:()=>e.getConfig,privateApis:()=>e.privateApis,store:()=>e.store});var a;const{directivePrefix:n,getRegionRootFragment:r,initialVdom:s,toVdom:c,render:l,parseInitialData:d,populateInitialData:g,batch:w}=(0,i.privateApis)("I acknowledge that using private APIs means my theme or plugin will inevitably break in the next version of WordPress."),h=null!==(a=(0,i.getConfig)("core/router").navigationMode)&&void 0!==a?a:"regionBased",u=new Map,m=(new Map,e=>{const t=new URL(e,window.location.href);return t.pathname+t.search}),f=async(e,{vdom:t}={})=>{const o={body:void 0};if("regionBased"===h){const i=`data-${n}-router-region`;e.querySelectorAll(`[${i}]`).forEach((e=>{const a=e.getAttribute(i);o[a]=t?.has(e)?t.get(e):c(e)}))}const i=e.querySelector("title")?.innerText,a=d(e);return{regions:o,head:undefined,title:i,initialData:a}},p=e=>{w((()=>{if("regionBased"===h){g(e.initialData);const t=`data-${n}-router-region`;document.querySelectorAll(`[${t}]`).forEach((o=>{const i=o.getAttribute(t),a=r(o);l(e.regions[i],a)}))}e.title&&(document.title=e.title)}))},v=e=>(window.location.assign(e),new Promise((()=>{})));window.addEventListener("popstate",(async()=>{const e=m(window.location.href),t=u.has(e)&&await u.get(e);t?(p(t),b.url=window.location.href):window.location.reload()})),u.set(m(window.location.href),Promise.resolve(f(document,{vdom:s})));let y="";const{state:b,actions:x}=(0,i.store)("core/router",{state:{url:window.location.href,navigation:{hasStarted:!1,hasFinished:!1,texts:{loading:"",loaded:""},message:""}},actions:{*navigate(e,t={}){const{clientNavigationDisabled:o}=(0,i.getConfig)();o&&(yield v(e));const a=m(e),{navigation:n}=b,{loadingAnimation:r=!0,screenReaderAnnouncement:s=!0,timeout:c=1e4}=t;y=e,x.prefetch(a,t);const l=new Promise((e=>setTimeout(e,c))),d=setTimeout((()=>{y===e&&(r&&(n.hasStarted=!0,n.hasFinished=!1),s&&(n.message=n.texts.loading))}),400),g=yield Promise.race([u.get(a),l]);if(clearTimeout(d),y===e)if(g&&!g.initialData?.config?.["core/router"]?.clientNavigationDisabled){yield p(g),window.history[t.replace?"replaceState":"pushState"]({},"",e),b.url=e,r&&(n.hasStarted=!1,n.hasFinished=!0),s&&(n.message=n.texts.loaded+(n.message===n.texts.loaded?" ":""));const{hash:o}=new URL(e,window.location.href);o&&document.querySelector(o)?.scrollIntoView()}else yield v(e)},prefetch(e,t={}){const{clientNavigationDisabled:o}=(0,i.getConfig)();if(o)return;const a=m(e);!t.force&&u.has(a)||u.set(a,(async(e,{html:t})=>{try{if(!t){const o=await window.fetch(e);if(200!==o.status)return!1;t=await o.text()}const o=(new window.DOMParser).parseFromString(t,"text/html");return f(o)}catch(e){return!1}})(a,{html:t.html}))}}});var A=o.o,P=o.w;export{A as actions,P as state};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+31 -18
View File
@@ -68,7 +68,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
@@ -179,8 +179,8 @@ function __awaiter(thisArg, _arguments, P, generator) {
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
@@ -284,8 +284,9 @@ function __await(v) {
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
@@ -351,16 +352,18 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
@@ -379,17 +382,22 @@ function __disposeResources(env) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
while (r = env.stack.pop()) {
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
@@ -720,9 +728,10 @@ function ImportForm({
type: "file",
onChange: onChangeFile
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
type: "submit",
isBusy: isLoading,
__experimentalIsFocusable: true,
accessibleWhenDisabled: true,
disabled: !file || isLoading,
variant: "secondary",
className: "list-reusable-blocks-import-form__button",
@@ -757,6 +766,8 @@ function ImportDropdown({
isOpen,
onToggle
}) => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
size: "compact",
className: "list-reusable-blocks-import-dropdown__button",
"aria-expanded": isOpen,
onClick: onToggle,
variant: "primary",
@@ -813,8 +824,10 @@ document.addEventListener('DOMContentLoaded', () => {
const container = document.createElement('div');
container.className = 'list-reusable-blocks__container';
button.parentNode.insertBefore(container, button);
(0,external_wp_element_namespaceObject.createRoot)(container).render( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(import_dropdown, {
onUpload: showNotice
(0,external_wp_element_namespaceObject.createRoot)(container).render( /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_element_namespaceObject.StrictMode, {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(import_dropdown, {
onUpload: showNotice
})
}));
});
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t);const n=window.wp.element,o=window.wp.i18n;var r=function(){return r=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},r.apply(this,arguments)};Object.create;Object.create;"function"==typeof SuppressedError&&SuppressedError;function s(e){return e.toLowerCase()}var a=[/([a-z0-9])([A-Z])/g,/([A-Z])([A-Z][a-z])/g],i=/[^A-Z0-9]+/gi;function l(e,t,n){return t instanceof RegExp?e.replace(t,n):t.reduce((function(e,t){return e.replace(t,n)}),e)}function c(e,t){return void 0===t&&(t={}),function(e,t){void 0===t&&(t={});for(var n=t.splitRegexp,o=void 0===n?a:n,r=t.stripRegexp,c=void 0===r?i:r,p=t.transform,d=void 0===p?s:p,u=t.delimiter,w=void 0===u?" ":u,f=l(l(e,o,"$1\0$2"),c,"\0"),m=0,b=f.length;"\0"===f.charAt(m);)m++;for(;"\0"===f.charAt(b-1);)b--;return f.slice(m,b).split("\0").map(d).join(w)}(e,r({delimiter:"."},t))}const p=window.wp.apiFetch;var d=e.n(p);const u=window.wp.blob;const w=async function(e){const t=await d()({path:"/wp/v2/types/wp_block"}),n=await d()({path:`/wp/v2/${t.rest_base}/${e}?context=edit`}),o=n.title.raw,s=n.content.raw,a=n.wp_pattern_sync_status,i=JSON.stringify({__file:"wp_block",title:o,content:s,syncStatus:a},null,2),l=(void 0===p&&(p={}),c(o,r({delimiter:"-"},p))+".json");var p;(0,u.downloadBlob)(l,i,"application/json")},f=window.wp.compose,m=window.wp.components;const b=async function(e){const t=await function(e){const t=new window.FileReader;return new Promise((n=>{t.onload=()=>{n(t.result)},t.readAsText(e)}))}(e);let n;try{n=JSON.parse(t)}catch(e){throw new Error("Invalid JSON file")}if("wp_block"!==n.__file||!n.title||!n.content||"string"!=typeof n.title||"string"!=typeof n.content||n.syncStatus&&"string"!=typeof n.syncStatus)throw new Error("Invalid pattern JSON file");const o=await d()({path:"/wp/v2/types/wp_block"});return await d()({path:`/wp/v2/${o.rest_base}`,data:{title:n.title,content:n.content,status:"publish",meta:"unsynced"===n.syncStatus?{wp_pattern_sync_status:n.syncStatus}:void 0},method:"POST"})},_=window.ReactJSXRuntime;const v=(0,f.withInstanceId)((function({instanceId:e,onUpload:t}){const r="list-reusable-blocks-import-form-"+e,s=(0,n.useRef)(),[a,i]=(0,n.useState)(!1),[l,c]=(0,n.useState)(null),[p,d]=(0,n.useState)(null);return(0,_.jsxs)("form",{className:"list-reusable-blocks-import-form",onSubmit:e=>{e.preventDefault(),p&&(i({isLoading:!0}),b(p).then((e=>{s&&(i(!1),t(e))})).catch((e=>{if(!s)return;let t;switch(e.message){case"Invalid JSON file":t=(0,o.__)("Invalid JSON file");break;case"Invalid pattern JSON file":t=(0,o.__)("Invalid pattern JSON file");break;default:t=(0,o.__)("Unknown error")}i(!1),c(t)})))},ref:s,children:[l&&(0,_.jsx)(m.Notice,{status:"error",onRemove:()=>{c(null)},children:l}),(0,_.jsx)("label",{htmlFor:r,className:"list-reusable-blocks-import-form__label",children:(0,o.__)("File")}),(0,_.jsx)("input",{id:r,type:"file",onChange:e=>{d(e.target.files[0]),c(null)}}),(0,_.jsx)(m.Button,{type:"submit",isBusy:a,__experimentalIsFocusable:!0,disabled:!p||a,variant:"secondary",className:"list-reusable-blocks-import-form__button",children:(0,o._x)("Import","button label")})]})}));const y=function({onUpload:e}){return(0,_.jsx)(m.Dropdown,{popoverProps:{placement:"bottom-start"},contentClassName:"list-reusable-blocks-import-dropdown__content",renderToggle:({isOpen:e,onToggle:t})=>(0,_.jsx)(m.Button,{"aria-expanded":e,onClick:t,variant:"primary",children:(0,o.__)("Import from JSON")}),renderContent:({onClose:t})=>(0,_.jsx)(v,{onUpload:(0,f.pipe)(t,e)})})};document.body.addEventListener("click",(e=>{e.target.classList.contains("wp-list-reusable-blocks__export")&&(e.preventDefault(),w(e.target.dataset.id))})),document.addEventListener("DOMContentLoaded",(()=>{const e=document.querySelector(".page-title-action");if(!e)return;const t=document.createElement("div");t.className="list-reusable-blocks__container",e.parentNode.insertBefore(t,e),(0,n.createRoot)(t).render((0,_.jsx)(y,{onUpload:()=>{const e=document.createElement("div");e.className="notice notice-success is-dismissible",e.innerHTML=`<p>${(0,o.__)("Pattern imported successfully!")}</p>`;const t=document.querySelector(".wp-header-end");t&&t.parentNode.insertBefore(e,t)}}))})),(window.wp=window.wp||{}).listReusableBlocks=t})();
(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t);const n=window.wp.element,o=window.wp.i18n;var r=function(){return r=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},r.apply(this,arguments)};Object.create;Object.create;"function"==typeof SuppressedError&&SuppressedError;function s(e){return e.toLowerCase()}var a=[/([a-z0-9])([A-Z])/g,/([A-Z])([A-Z][a-z])/g],i=/[^A-Z0-9]+/gi;function l(e,t,n){return t instanceof RegExp?e.replace(t,n):t.reduce((function(e,t){return e.replace(t,n)}),e)}function c(e,t){return void 0===t&&(t={}),function(e,t){void 0===t&&(t={});for(var n=t.splitRegexp,o=void 0===n?a:n,r=t.stripRegexp,c=void 0===r?i:r,p=t.transform,d=void 0===p?s:p,u=t.delimiter,w=void 0===u?" ":u,f=l(l(e,o,"$1\0$2"),c,"\0"),m=0,b=f.length;"\0"===f.charAt(m);)m++;for(;"\0"===f.charAt(b-1);)b--;return f.slice(m,b).split("\0").map(d).join(w)}(e,r({delimiter:"."},t))}const p=window.wp.apiFetch;var d=e.n(p);const u=window.wp.blob;const w=async function(e){const t=await d()({path:"/wp/v2/types/wp_block"}),n=await d()({path:`/wp/v2/${t.rest_base}/${e}?context=edit`}),o=n.title.raw,s=n.content.raw,a=n.wp_pattern_sync_status,i=JSON.stringify({__file:"wp_block",title:o,content:s,syncStatus:a},null,2),l=(void 0===p&&(p={}),c(o,r({delimiter:"-"},p))+".json");var p;(0,u.downloadBlob)(l,i,"application/json")},f=window.wp.compose,m=window.wp.components;const b=async function(e){const t=await function(e){const t=new window.FileReader;return new Promise((n=>{t.onload=()=>{n(t.result)},t.readAsText(e)}))}(e);let n;try{n=JSON.parse(t)}catch(e){throw new Error("Invalid JSON file")}if("wp_block"!==n.__file||!n.title||!n.content||"string"!=typeof n.title||"string"!=typeof n.content||n.syncStatus&&"string"!=typeof n.syncStatus)throw new Error("Invalid pattern JSON file");const o=await d()({path:"/wp/v2/types/wp_block"});return await d()({path:`/wp/v2/${o.rest_base}`,data:{title:n.title,content:n.content,status:"publish",meta:"unsynced"===n.syncStatus?{wp_pattern_sync_status:n.syncStatus}:void 0},method:"POST"})},_=window.ReactJSXRuntime;const v=(0,f.withInstanceId)((function({instanceId:e,onUpload:t}){const r="list-reusable-blocks-import-form-"+e,s=(0,n.useRef)(),[a,i]=(0,n.useState)(!1),[l,c]=(0,n.useState)(null),[p,d]=(0,n.useState)(null);return(0,_.jsxs)("form",{className:"list-reusable-blocks-import-form",onSubmit:e=>{e.preventDefault(),p&&(i({isLoading:!0}),b(p).then((e=>{s&&(i(!1),t(e))})).catch((e=>{if(!s)return;let t;switch(e.message){case"Invalid JSON file":t=(0,o.__)("Invalid JSON file");break;case"Invalid pattern JSON file":t=(0,o.__)("Invalid pattern JSON file");break;default:t=(0,o.__)("Unknown error")}i(!1),c(t)})))},ref:s,children:[l&&(0,_.jsx)(m.Notice,{status:"error",onRemove:()=>{c(null)},children:l}),(0,_.jsx)("label",{htmlFor:r,className:"list-reusable-blocks-import-form__label",children:(0,o.__)("File")}),(0,_.jsx)("input",{id:r,type:"file",onChange:e=>{d(e.target.files[0]),c(null)}}),(0,_.jsx)(m.Button,{__next40pxDefaultSize:!0,type:"submit",isBusy:a,accessibleWhenDisabled:!0,disabled:!p||a,variant:"secondary",className:"list-reusable-blocks-import-form__button",children:(0,o._x)("Import","button label")})]})}));const y=function({onUpload:e}){return(0,_.jsx)(m.Dropdown,{popoverProps:{placement:"bottom-start"},contentClassName:"list-reusable-blocks-import-dropdown__content",renderToggle:({isOpen:e,onToggle:t})=>(0,_.jsx)(m.Button,{size:"compact",className:"list-reusable-blocks-import-dropdown__button","aria-expanded":e,onClick:t,variant:"primary",children:(0,o.__)("Import from JSON")}),renderContent:({onClose:t})=>(0,_.jsx)(v,{onUpload:(0,f.pipe)(t,e)})})};document.body.addEventListener("click",(e=>{e.target.classList.contains("wp-list-reusable-blocks__export")&&(e.preventDefault(),w(e.target.dataset.id))})),document.addEventListener("DOMContentLoaded",(()=>{const e=document.querySelector(".page-title-action");if(!e)return;const t=document.createElement("div");t.className="list-reusable-blocks__container",e.parentNode.insertBefore(t,e),(0,n.createRoot)(t).render((0,_.jsx)(n.StrictMode,{children:(0,_.jsx)(y,{onUpload:()=>{const e=document.createElement("div");e.className="notice notice-success is-dismissible",e.innerHTML=`<p>${(0,o.__)("Pattern imported successfully!")}</p>`;const t=document.querySelector(".wp-header-end");t&&t.parentNode.insertBefore(e,t)}})}))})),(window.wp=window.wp||{}).listReusableBlocks=t})();
+312 -158
View File
@@ -52,7 +52,11 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
MediaUpload: () => (/* reexport */ media_upload),
uploadMedia: () => (/* reexport */ uploadMedia)
transformAttachment: () => (/* reexport */ transformAttachment),
uploadMedia: () => (/* reexport */ uploadMedia),
validateFileSize: () => (/* reexport */ validateFileSize),
validateMimeType: () => (/* reexport */ validateMimeType),
validateMimeTypeForUser: () => (/* reexport */ validateMimeTypeForUser)
});
;// CONCATENATED MODULE: external ["wp","element"]
@@ -427,6 +431,7 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
if (onClose) {
onClose();
}
this.frame.detach();
}
updateCollection() {
const frameContent = this.frame.content.get();
@@ -489,11 +494,255 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/index.js
;// CONCATENATED MODULE: external ["wp","blob"]
const external_wp_blob_namespaceObject = window["wp"]["blob"];
;// CONCATENATED MODULE: external ["wp","apiFetch"]
const external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: external ["wp","blob"]
const external_wp_blob_namespaceObject = window["wp"]["blob"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/flatten-form-data.js
/**
* Determines whether the passed argument appears to be a plain object.
*
* @param data The object to inspect.
*/
function isPlainObject(data) {
return data !== null && typeof data === 'object' && Object.getPrototypeOf(data) === Object.prototype;
}
/**
* Recursively flatten data passed to form data, to allow using multi-level objects.
*
* @param {FormData} formData Form data object.
* @param {string} key Key to amend to form data object
* @param {string|Object} data Data to be amended to form data.
*/
function flattenFormData(formData, key, data) {
if (isPlainObject(data)) {
for (const [name, value] of Object.entries(data)) {
flattenFormData(formData, `${key}[${name}]`, value);
}
} else if (data !== undefined) {
formData.append(key, String(data));
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/transform-attachment.js
/**
* Internal dependencies
*/
/**
* Transforms an attachment object from the REST API shape into the shape expected by the block editor and other consumers.
*
* @param attachment REST API attachment object.
*/
function transformAttachment(attachment) {
var _attachment$caption$r;
// eslint-disable-next-line camelcase
const {
alt_text,
source_url,
...savedMediaProps
} = attachment;
return {
...savedMediaProps,
alt: attachment.alt_text,
caption: (_attachment$caption$r = attachment.caption?.raw) !== null && _attachment$caption$r !== void 0 ? _attachment$caption$r : '',
title: attachment.title.raw,
url: attachment.source_url,
poster: attachment._embedded?.['wp:featuredmedia']?.[0]?.source_url || undefined
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/upload-to-server.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
async function uploadToServer(file, additionalData = {}, signal) {
// Create upload payload.
const data = new FormData();
data.append('file', file, file.name || file.type.replace('/', '.'));
for (const [key, value] of Object.entries(additionalData)) {
flattenFormData(data, key, value);
}
return transformAttachment(await external_wp_apiFetch_default()({
// This allows the video block to directly get a video's poster image.
path: '/wp/v2/media?_embed=wp:featuredmedia',
body: data,
method: 'POST',
signal
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/upload-error.js
/**
* MediaError class.
*
* Small wrapper around the `Error` class
* to hold an error code and a reference to a file object.
*/
class UploadError extends Error {
constructor({
code,
message,
file,
cause
}) {
super(message, {
cause
});
Object.setPrototypeOf(this, new.target.prototype);
this.code = code;
this.file = file;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/validate-mime-type.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Verifies if the caller (e.g. a block) supports this mime type.
*
* @param file File object.
* @param allowedTypes List of allowed mime types.
*/
function validateMimeType(file, allowedTypes) {
if (!allowedTypes) {
return;
}
// Allowed type specified by consumer.
const isAllowedType = allowedTypes.some(allowedType => {
// If a complete mimetype is specified verify if it matches exactly the mime type of the file.
if (allowedType.includes('/')) {
return allowedType === file.type;
}
// Otherwise a general mime type is used, and we should verify if the file mimetype starts with it.
return file.type.startsWith(`${allowedType}/`);
});
if (file.type && !isAllowedType) {
throw new UploadError({
code: 'MIME_TYPE_NOT_SUPPORTED',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: Sorry, this file type is not supported here.'), file.name),
file
});
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/get-mime-types-array.js
/**
* Browsers may use unexpected mime types, and they differ from browser to browser.
* This function computes a flexible array of mime types from the mime type structured provided by the server.
* Converts { jpg|jpeg|jpe: "image/jpeg" } into [ "image/jpeg", "image/jpg", "image/jpeg", "image/jpe" ]
*
* @param {?Object} wpMimeTypesObject Mime type object received from the server.
* Extensions are keys separated by '|' and values are mime types associated with an extension.
*
* @return An array of mime types or null
*/
function getMimeTypesArray(wpMimeTypesObject) {
if (!wpMimeTypesObject) {
return null;
}
return Object.entries(wpMimeTypesObject).flatMap(([extensionsString, mime]) => {
const [type] = mime.split('/');
const extensions = extensionsString.split('|');
return [mime, ...extensions.map(extension => `${type}/${extension}`)];
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/validate-mime-type-for-user.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Verifies if the user is allowed to upload this mime type.
*
* @param file File object.
* @param wpAllowedMimeTypes List of allowed mime types and file extensions.
*/
function validateMimeTypeForUser(file, wpAllowedMimeTypes) {
// Allowed types for the current WP_User.
const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
if (!allowedMimeTypesForUser) {
return;
}
const isAllowedMimeTypeForUser = allowedMimeTypesForUser.includes(file.type);
if (file.type && !isAllowedMimeTypeForUser) {
throw new UploadError({
code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: Sorry, you are not allowed to upload this file type.'), file.name),
file
});
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/validate-file-size.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Verifies whether the file is within the file upload size limits for the site.
*
* @param file File object.
* @param maxUploadFileSize Maximum upload size in bytes allowed for the site.
*/
function validateFileSize(file, maxUploadFileSize) {
// Don't allow empty files to be uploaded.
if (file.size <= 0) {
throw new UploadError({
code: 'EMPTY_FILE',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: This file is empty.'), file.name),
file
});
}
if (maxUploadFileSize && file.size > maxUploadFileSize) {
throw new UploadError({
code: 'SIZE_ABOVE_LIMIT',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: This file exceeds the maximum upload size for this site.'), file.name),
file
});
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/upload-media.js
/**
* WordPress dependencies
@@ -501,134 +750,72 @@ const external_wp_blob_namespaceObject = window["wp"]["blob"];
const noop = () => {};
/**
* Internal dependencies
*/
/**
* Browsers may use unexpected mime types, and they differ from browser to browser.
* This function computes a flexible array of mime types from the mime type structured provided by the server.
* Converts { jpg|jpeg|jpe: "image/jpeg" } into [ "image/jpeg", "image/jpg", "image/jpeg", "image/jpe" ]
* The computation of this array instead of directly using the object,
* solves the problem in chrome where mp3 files have audio/mp3 as mime type instead of audio/mpeg.
* https://bugs.chromium.org/p/chromium/issues/detail?id=227004
* Upload a media file when the file upload button is activated
* or when adding a file to the editor via drag & drop.
*
* @param {?Object} wpMimeTypesObject Mime type object received from the server.
* Extensions are keys separated by '|' and values are mime types associated with an extension.
*
* @return {?Array} An array of mime types or the parameter passed if it was "falsy".
* @param $0 Parameters object passed to the function.
* @param $0.allowedTypes Array with the types of media that can be uploaded, if unset all types are allowed.
* @param $0.additionalData Additional data to include in the request.
* @param $0.filesList List of files.
* @param $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
* @param $0.onError Function called when an error happens.
* @param $0.onFileChange Function called each time a file or a temporary representation of the file is available.
* @param $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
* @param $0.signal Abort signal.
*/
function getMimeTypesArray(wpMimeTypesObject) {
if (!wpMimeTypesObject) {
return wpMimeTypesObject;
}
return Object.entries(wpMimeTypesObject).map(([extensionsString, mime]) => {
const [type] = mime.split('/');
const extensions = extensionsString.split('|');
return [mime, ...extensions.map(extension => `${type}/${extension}`)];
}).flat();
}
/**
* Media Upload is used by audio, image, gallery, video, and file blocks to
* handle uploading a media file when a file upload button is activated.
*
* TODO: future enhancement to add an upload indicator.
*
* @param {Object} $0 Parameters object passed to the function.
* @param {?Array} $0.allowedTypes Array with the types of media that can be uploaded, if unset all types are allowed.
* @param {?Object} $0.additionalData Additional data to include in the request.
* @param {Array} $0.filesList List of files.
* @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
* @param {Function} $0.onError Function called when an error happens.
* @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.
* @param {?Object} $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
*/
async function uploadMedia({
function uploadMedia({
wpAllowedMimeTypes,
allowedTypes,
additionalData = {},
filesList,
maxUploadFileSize,
onError = noop,
onError,
onFileChange,
wpAllowedMimeTypes = null
signal
}) {
// Cast filesList to array.
const files = [...filesList];
const filesSet = [];
const setAndUpdateFiles = (idx, value) => {
(0,external_wp_blob_namespaceObject.revokeBlobURL)(filesSet[idx]?.url);
filesSet[idx] = value;
onFileChange(filesSet.filter(Boolean));
};
// Allowed type specified by consumer.
const isAllowedType = fileType => {
if (!allowedTypes) {
return true;
}
return allowedTypes.some(allowedType => {
// If a complete mimetype is specified verify if it matches exactly the mime type of the file.
if (allowedType.includes('/')) {
return allowedType === fileType;
}
// Otherwise a general mime type is used and we should verify if the file mimetype starts with it.
return fileType.startsWith(`${allowedType}/`);
});
};
// Allowed types for the current WP_User.
const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
const isAllowedMimeTypeForUser = fileType => {
return allowedMimeTypesForUser.includes(fileType);
};
const validFiles = [];
for (const mediaFile of files) {
const filesSet = [];
const setAndUpdateFiles = (index, value) => {
if (filesSet[index]?.url) {
(0,external_wp_blob_namespaceObject.revokeBlobURL)(filesSet[index].url);
}
filesSet[index] = value;
onFileChange?.(filesSet.filter(attachment => attachment !== null));
};
for (const mediaFile of filesList) {
// Verify if user is allowed to upload this mime type.
// Defer to the server when type not detected.
if (allowedMimeTypesForUser && mediaFile.type && !isAllowedMimeTypeForUser(mediaFile.type)) {
onError({
code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: Sorry, you are not allowed to upload this file type.'), mediaFile.name),
file: mediaFile
});
try {
validateMimeTypeForUser(mediaFile, wpAllowedMimeTypes);
} catch (error) {
onError?.(error);
continue;
}
// Check if the block supports this mime type.
// Check if the caller (e.g. a block) supports this mime type.
// Defer to the server when type not detected.
if (mediaFile.type && !isAllowedType(mediaFile.type)) {
onError({
code: 'MIME_TYPE_NOT_SUPPORTED',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: Sorry, this file type is not supported here.'), mediaFile.name),
file: mediaFile
});
try {
validateMimeType(mediaFile, allowedTypes);
} catch (error) {
onError?.(error);
continue;
}
// Verify if file is greater than the maximum file upload size allowed for the site.
if (maxUploadFileSize && mediaFile.size > maxUploadFileSize) {
onError({
code: 'SIZE_ABOVE_LIMIT',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: This file exceeds the maximum upload size for this site.'), mediaFile.name),
file: mediaFile
});
continue;
}
// Don't allow empty files to be uploaded.
if (mediaFile.size <= 0) {
onError({
code: 'EMPTY_FILE',
message: (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: This file is empty.'), mediaFile.name),
file: mediaFile
});
try {
validateFileSize(mediaFile, maxUploadFileSize);
} catch (error) {
onError?.(error);
continue;
}
validFiles.push(mediaFile);
@@ -638,74 +825,41 @@ async function uploadMedia({
filesSet.push({
url: (0,external_wp_blob_namespaceObject.createBlobURL)(mediaFile)
});
onFileChange(filesSet);
onFileChange?.(filesSet);
}
for (let idx = 0; idx < validFiles.length; ++idx) {
const mediaFile = validFiles[idx];
validFiles.map(async (file, index) => {
try {
var _savedMedia$caption$r;
const savedMedia = await createMediaFromFile(mediaFile, additionalData);
// eslint-disable-next-line camelcase
const {
alt_text,
source_url,
...savedMediaProps
} = savedMedia;
const mediaObject = {
...savedMediaProps,
alt: savedMedia.alt_text,
caption: (_savedMedia$caption$r = savedMedia.caption?.raw) !== null && _savedMedia$caption$r !== void 0 ? _savedMedia$caption$r : '',
title: savedMedia.title.raw,
url: savedMedia.source_url
};
setAndUpdateFiles(idx, mediaObject);
const attachment = await uploadToServer(file, additionalData, signal);
setAndUpdateFiles(index, attachment);
} catch (error) {
// Reset to empty on failure.
setAndUpdateFiles(idx, null);
setAndUpdateFiles(index, null);
let message;
if (error.message) {
if (error instanceof Error) {
message = error.message;
} else {
message = (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: file name
(0,external_wp_i18n_namespaceObject.__)('Error while uploading file %s to the media library.'), mediaFile.name);
(0,external_wp_i18n_namespaceObject.__)('Error while uploading file %s to the media library.'), file.name);
}
onError({
onError?.(new UploadError({
code: 'GENERAL',
message,
file: mediaFile
});
file,
cause: error instanceof Error ? error : undefined
}));
}
}
}
/**
* @param {File} file Media File to Save.
* @param {?Object} additionalData Additional data to include in the request.
*
* @return {Promise} Media Object Promise.
*/
function createMediaFromFile(file, additionalData) {
// Create upload payload.
const data = new window.FormData();
data.append('file', file, file.name || file.type.replace('/', '.'));
if (additionalData) {
Object.entries(additionalData).forEach(([key, value]) => data.append(key, value));
}
return external_wp_apiFetch_default()({
path: '/wp/v2/media',
body: data,
method: 'POST'
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/index.js
(window.wp = window.wp || {}).mediaUtils = __webpack_exports__;
/******/ })()
;
File diff suppressed because one or more lines are too long
+3 -1
View File
@@ -337,7 +337,7 @@ const close_close = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_primitives_namespaceObject.Path, {
d: "M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"
d: "m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z"
})
});
/* harmony default export */ const library_close = (close_close);
@@ -397,11 +397,13 @@ function DotTip({
children: children
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("p", {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
variant: "link",
onClick: onDismiss,
children: hasNextTip ? (0,external_wp_i18n_namespaceObject.__)('See next tip') : (0,external_wp_i18n_namespaceObject.__)('Got it')
})
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
size: "small",
className: "nux-dot-tip__disable",
icon: library_close,
label: (0,external_wp_i18n_namespaceObject.__)('Disable tips'),
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
(()=>{"use strict";var e={n:i=>{var n=i&&i.__esModule?()=>i.default:()=>i;return e.d(n,{a:n}),n},d:(i,n)=>{for(var t in n)e.o(n,t)&&!e.o(i,t)&&Object.defineProperty(i,t,{enumerable:!0,get:n[t]})},o:(e,i)=>Object.prototype.hasOwnProperty.call(e,i),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},i={};e.r(i),e.d(i,{DotTip:()=>P,store:()=>I});var n={};e.r(n),e.d(n,{disableTips:()=>a,dismissTip:()=>u,enableTips:()=>l,triggerGuide:()=>p});var t={};e.r(t),e.d(t,{areTipsEnabled:()=>T,getAssociatedGuide:()=>w,isTipVisible:()=>f});const s=window.wp.deprecated;var r=e.n(s);const o=window.wp.data;const c=(0,o.combineReducers)({areTipsEnabled:function(e=!0,i){switch(i.type){case"DISABLE_TIPS":return!1;case"ENABLE_TIPS":return!0}return e},dismissedTips:function(e={},i){switch(i.type){case"DISMISS_TIP":return{...e,[i.id]:!0};case"ENABLE_TIPS":return{}}return e}}),d=(0,o.combineReducers)({guides:function(e=[],i){return"TRIGGER_GUIDE"===i.type?[...e,i.tipIds]:e},preferences:c});function p(e){return{type:"TRIGGER_GUIDE",tipIds:e}}function u(e){return{type:"DISMISS_TIP",id:e}}function a(){return{type:"DISABLE_TIPS"}}function l(){return{type:"ENABLE_TIPS"}}const w=(0,o.createSelector)(((e,i)=>{for(const n of e.guides)if(n.includes(i)){const i=n.filter((i=>!Object.keys(e.preferences.dismissedTips).includes(i))),[t=null,s=null]=i;return{tipIds:n,currentTipId:t,nextTipId:s}}return null}),(e=>[e.guides,e.preferences.dismissedTips]));function f(e,i){if(!e.preferences.areTipsEnabled)return!1;if(e.preferences.dismissedTips?.hasOwnProperty(i))return!1;const n=w(e,i);return!n||n.currentTipId===i}function T(e){return e.preferences.areTipsEnabled}const b="core/nux",I=(0,o.createReduxStore)(b,{reducer:d,actions:n,selectors:t,persist:["preferences"]});(0,o.registerStore)(b,{reducer:d,actions:n,selectors:t,persist:["preferences"]});const m=window.wp.compose,S=window.wp.components,_=window.wp.i18n,g=window.wp.element,h=window.wp.primitives,x=window.ReactJSXRuntime,y=(0,x.jsx)(h.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:(0,x.jsx)(h.Path,{d:"M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"})});function E(e){e.stopPropagation()}const P=(0,m.compose)((0,o.withSelect)(((e,{tipId:i})=>{const{isTipVisible:n,getAssociatedGuide:t}=e(I),s=t(i);return{isVisible:n(i),hasNextTip:!(!s||!s.nextTipId)}})),(0,o.withDispatch)(((e,{tipId:i})=>{const{dismissTip:n,disableTips:t}=e(I);return{onDismiss(){n(i)},onDisable(){t()}}})))((function({position:e="middle right",children:i,isVisible:n,hasNextTip:t,onDismiss:s,onDisable:r}){const o=(0,g.useRef)(null),c=(0,g.useCallback)((e=>{o.current&&(o.current.contains(e.relatedTarget)||r())}),[r,o]);return n?(0,x.jsxs)(S.Popover,{className:"nux-dot-tip",position:e,focusOnMount:!0,role:"dialog","aria-label":(0,_.__)("Editor tips"),onClick:E,onFocusOutside:c,children:[(0,x.jsx)("p",{children:i}),(0,x.jsx)("p",{children:(0,x.jsx)(S.Button,{variant:"link",onClick:s,children:t?(0,_.__)("See next tip"):(0,_.__)("Got it")})}),(0,x.jsx)(S.Button,{className:"nux-dot-tip__disable",icon:y,label:(0,_.__)("Disable tips"),onClick:r})]}):null}));r()("wp.nux",{since:"5.4",hint:"wp.components.Guide can be used to show a user guide.",version:"6.2"}),(window.wp=window.wp||{}).nux=i})();
(()=>{"use strict";var e={n:i=>{var n=i&&i.__esModule?()=>i.default:()=>i;return e.d(n,{a:n}),n},d:(i,n)=>{for(var t in n)e.o(n,t)&&!e.o(i,t)&&Object.defineProperty(i,t,{enumerable:!0,get:n[t]})},o:(e,i)=>Object.prototype.hasOwnProperty.call(e,i),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},i={};e.r(i),e.d(i,{DotTip:()=>P,store:()=>m});var n={};e.r(n),e.d(n,{disableTips:()=>l,dismissTip:()=>u,enableTips:()=>a,triggerGuide:()=>p});var t={};e.r(t),e.d(t,{areTipsEnabled:()=>T,getAssociatedGuide:()=>w,isTipVisible:()=>f});const s=window.wp.deprecated;var r=e.n(s);const o=window.wp.data;const c=(0,o.combineReducers)({areTipsEnabled:function(e=!0,i){switch(i.type){case"DISABLE_TIPS":return!1;case"ENABLE_TIPS":return!0}return e},dismissedTips:function(e={},i){switch(i.type){case"DISMISS_TIP":return{...e,[i.id]:!0};case"ENABLE_TIPS":return{}}return e}}),d=(0,o.combineReducers)({guides:function(e=[],i){return"TRIGGER_GUIDE"===i.type?[...e,i.tipIds]:e},preferences:c});function p(e){return{type:"TRIGGER_GUIDE",tipIds:e}}function u(e){return{type:"DISMISS_TIP",id:e}}function l(){return{type:"DISABLE_TIPS"}}function a(){return{type:"ENABLE_TIPS"}}const w=(0,o.createSelector)(((e,i)=>{for(const n of e.guides)if(n.includes(i)){const i=n.filter((i=>!Object.keys(e.preferences.dismissedTips).includes(i))),[t=null,s=null]=i;return{tipIds:n,currentTipId:t,nextTipId:s}}return null}),(e=>[e.guides,e.preferences.dismissedTips]));function f(e,i){if(!e.preferences.areTipsEnabled)return!1;if(e.preferences.dismissedTips?.hasOwnProperty(i))return!1;const n=w(e,i);return!n||n.currentTipId===i}function T(e){return e.preferences.areTipsEnabled}const b="core/nux",m=(0,o.createReduxStore)(b,{reducer:d,actions:n,selectors:t,persist:["preferences"]});(0,o.registerStore)(b,{reducer:d,actions:n,selectors:t,persist:["preferences"]});const I=window.wp.compose,S=window.wp.components,_=window.wp.i18n,x=window.wp.element,g=window.wp.primitives,h=window.ReactJSXRuntime,y=(0,h.jsx)(g.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:(0,h.jsx)(g.Path,{d:"m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z"})});function E(e){e.stopPropagation()}const P=(0,I.compose)((0,o.withSelect)(((e,{tipId:i})=>{const{isTipVisible:n,getAssociatedGuide:t}=e(m),s=t(i);return{isVisible:n(i),hasNextTip:!(!s||!s.nextTipId)}})),(0,o.withDispatch)(((e,{tipId:i})=>{const{dismissTip:n,disableTips:t}=e(m);return{onDismiss(){n(i)},onDisable(){t()}}})))((function({position:e="middle right",children:i,isVisible:n,hasNextTip:t,onDismiss:s,onDisable:r}){const o=(0,x.useRef)(null),c=(0,x.useCallback)((e=>{o.current&&(o.current.contains(e.relatedTarget)||r())}),[r,o]);return n?(0,h.jsxs)(S.Popover,{className:"nux-dot-tip",position:e,focusOnMount:!0,role:"dialog","aria-label":(0,_.__)("Editor tips"),onClick:E,onFocusOutside:c,children:[(0,h.jsx)("p",{children:i}),(0,h.jsx)("p",{children:(0,h.jsx)(S.Button,{__next40pxDefaultSize:!0,variant:"link",onClick:s,children:t?(0,_.__)("See next tip"):(0,_.__)("Got it")})}),(0,h.jsx)(S.Button,{size:"small",className:"nux-dot-tip__disable",icon:y,label:(0,_.__)("Disable tips"),onClick:r})]}):null}));r()("wp.nux",{since:"5.4",hint:"wp.components.Guide can be used to show a user guide.",version:"6.2"}),(window.wp=window.wp||{}).nux=i})();
+38 -36
View File
@@ -560,6 +560,8 @@ function CreatePatternModal({
title: modalTitle || defaultModalTitle,
onRequestClose: restProps.onClose,
overlayClassName: className,
focusOnMount: "firstContentElement",
size: "small",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(CreatePatternModalContents, {
...restProps
})
@@ -633,6 +635,7 @@ function CreatePatternModalContents({
onChange: setCategoryTerms,
categoryMap: categoryMap
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ToggleControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject._x)('Synced', 'pattern (singular)'),
help: (0,external_wp_i18n_namespaceObject.__)('Sync this pattern across multiple locations.'),
checked: syncType === PATTERN_SYNC_TYPES.full,
@@ -710,13 +713,13 @@ function useDuplicatePatternProps({
defaultSyncType: pattern.type !== PATTERN_TYPES.user // Theme patterns are unsynced by default.
? PATTERN_SYNC_TYPES.unsynced : pattern.wp_pattern_sync_status || PATTERN_SYNC_TYPES.full,
defaultTitle: (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %s: Existing pattern title */
(0,external_wp_i18n_namespaceObject.__)('%s (Copy)'), typeof pattern.title === 'string' ? pattern.title : pattern.title.raw),
(0,external_wp_i18n_namespaceObject._x)('%s (Copy)', 'pattern'), typeof pattern.title === 'string' ? pattern.title : pattern.title.raw),
onSuccess: ({
pattern: newPattern
}) => {
createSuccessNotice((0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: The new pattern's title e.g. 'Call to action (copy)'.
(0,external_wp_i18n_namespaceObject.__)('"%s" duplicated.'), newPattern.title.raw), {
(0,external_wp_i18n_namespaceObject._x)('"%s" duplicated.', 'pattern'), newPattern.title.raw), {
type: 'snackbar',
id: 'patterns-create'
});
@@ -818,6 +821,8 @@ function RenamePatternModal({
title: (0,external_wp_i18n_namespaceObject.__)('Rename'),
...props,
onRequestClose: onClose,
focusOnMount: "firstContentElement",
size: "small",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)("form", {
onSubmit: onRename,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__experimentalVStack, {
@@ -940,7 +945,11 @@ function PatternConvertButton({
// Hide when block doesn't support being made into a pattern.
(0,external_wp_blocks_namespaceObject.hasBlockSupport)(block.name, 'reusable', true)) &&
// Hide when current doesn't have permission to do that.
!!canUser('create', 'blocks');
// Blocks refers to the wp_block post type, this checks the ability to create a post of that type.
!!canUser('create', {
kind: 'postType',
name: 'wp_block'
});
return _canConvert;
}, [clientIds, rootClientId]);
const {
@@ -1034,12 +1043,19 @@ function PatternsManageButton({
const reusableBlock = getBlock(clientId);
return {
canRemove: canRemoveBlock(clientId),
isVisible: !!reusableBlock && (0,external_wp_blocks_namespaceObject.isReusableBlock)(reusableBlock) && !!canUser('update', 'blocks', reusableBlock.attributes.ref),
isVisible: !!reusableBlock && (0,external_wp_blocks_namespaceObject.isReusableBlock)(reusableBlock) && !!canUser('update', {
kind: 'postType',
name: 'wp_block',
id: reusableBlock.attributes.ref
}),
innerBlockCount: getBlockCount(clientId),
// The site editor and templates both check whether the user
// has edit_theme_options capabilities. We can leverage that here
// and omit the manage patterns link if the user can't access it.
managePatternsUrl: canUser('create', 'templates') ? (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', {
managePatternsUrl: canUser('create', {
kind: 'postType',
name: 'wp_template'
}) ? (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', {
path: '/patterns'
}) : (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
post_type: 'wp_block'
@@ -1392,24 +1408,6 @@ function DisallowOverridesModal({
function removeBindings(bindings) {
let updatedBindings = {
...bindings
};
delete updatedBindings.__default;
if (!Object.keys(updatedBindings).length) {
updatedBindings = undefined;
}
return updatedBindings;
}
function addBindings(bindings) {
return {
...bindings,
__default: {
source: PATTERN_OVERRIDES_BINDING_SOURCE
}
};
}
function PatternOverridesControls({
attributes,
setAttributes,
@@ -1422,18 +1420,22 @@ function PatternOverridesControls({
const defaultBindings = attributes.metadata?.bindings?.__default;
const hasOverrides = hasName && defaultBindings?.source === PATTERN_OVERRIDES_BINDING_SOURCE;
const isConnectedToOtherSources = defaultBindings?.source && defaultBindings.source !== PATTERN_OVERRIDES_BINDING_SOURCE;
const {
updateBlockBindings
} = (0,external_wp_blockEditor_namespaceObject.useBlockBindingsUtils)();
function updateBindings(isChecked, customName) {
const prevBindings = attributes?.metadata?.bindings;
const updatedBindings = isChecked ? addBindings(prevBindings) : removeBindings(prevBindings);
const updatedMetadata = {
...attributes.metadata,
bindings: updatedBindings
};
if (customName) {
updatedMetadata.name = customName;
setAttributes({
metadata: {
...attributes.metadata,
name: customName
}
});
}
setAttributes({
metadata: updatedMetadata
updateBlockBindings({
__default: isChecked ? {
source: PATTERN_OVERRIDES_BINDING_SOURCE
} : undefined
});
}
@@ -1447,6 +1449,7 @@ function PatternOverridesControls({
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_blockEditor_namespaceObject.InspectorControls, {
group: "advanced",
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.BaseControl, {
__nextHasNoMarginBottom: true,
id: controlId,
label: (0,external_wp_i18n_namespaceObject.__)('Overrides'),
help: helpText,
@@ -1463,7 +1466,7 @@ function PatternOverridesControls({
}
},
disabled: !hasOverrides && hasUnsupportedImageAttributes,
__experimentalIsFocusable: true,
accessibleWhenDisabled: true,
children: hasOverrides ? (0,external_wp_i18n_namespaceObject.__)('Disable overrides') : (0,external_wp_i18n_namespaceObject.__)('Enable overrides')
})
})
@@ -1546,7 +1549,6 @@ function ResetOverridesControl(props) {
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ToolbarButton, {
onClick: onClick,
disabled: !isOverriden,
__experimentalIsFocusable: true,
children: (0,external_wp_i18n_namespaceObject.__)('Reset')
})
})
@@ -1631,7 +1633,7 @@ function PatternOverridesToolbarIndicator({
clientId: clientIds[0],
maximumLength: 35
});
const blockDescription = isSingleBlockSelected ? (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %1s: The block type's name; %2s: The block's user-provided name (the same as the override name). */
const blockDescription = isSingleBlockSelected ? (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: 1: The block type's name. 2: The block's user-provided name (the same as the override name). */
(0,external_wp_i18n_namespaceObject.__)('This %1$s is editable using the "%2$s" override.'), firstBlockTitle.toLowerCase(), firstBlockName) : (0,external_wp_i18n_namespaceObject.__)('These blocks are editable using overrides.');
const descriptionId = (0,external_wp_element_namespaceObject.useId)();
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ToolbarItem, {
@@ -1650,7 +1652,7 @@ function PatternOverridesToolbarIndicator({
})
}),
toggleProps: {
describedBy: blockDescription,
description: blockDescription,
...toggleProps
},
menuProps: {
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -697,7 +697,7 @@ function PreferencesModalTabs({
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__experimentalItemGroup, {
children: tabs.map(tab => {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__experimentalNavigatorButton, {
path: tab.name,
path: `/${tab.name}`,
as: external_wp_components_namespaceObject.__experimentalItem,
isAction: true,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__experimentalHStack, {
@@ -719,7 +719,7 @@ function PreferencesModalTabs({
})
}), sections.length && sections.map(section => {
return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.__experimentalNavigatorScreen, {
path: section.name,
path: `/${section.name}`,
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.Card, {
isBorderless: true,
size: "large",
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -54,7 +54,7 @@ __webpack_require__.d(__webpack_exports__, {
/**
* The list of core modules allowed to opt-in to the private APIs.
*/
const CORE_MODULES_USING_PRIVATE_APIS = ['@wordpress/block-directory', '@wordpress/block-editor', '@wordpress/block-library', '@wordpress/blocks', '@wordpress/commands', '@wordpress/components', '@wordpress/core-commands', '@wordpress/core-data', '@wordpress/customize-widgets', '@wordpress/data', '@wordpress/edit-post', '@wordpress/edit-site', '@wordpress/edit-widgets', '@wordpress/editor', '@wordpress/format-library', '@wordpress/interface', '@wordpress/patterns', '@wordpress/preferences', '@wordpress/reusable-blocks', '@wordpress/router', '@wordpress/dataviews'];
const CORE_MODULES_USING_PRIVATE_APIS = ['@wordpress/block-directory', '@wordpress/block-editor', '@wordpress/block-library', '@wordpress/blocks', '@wordpress/commands', '@wordpress/components', '@wordpress/core-commands', '@wordpress/core-data', '@wordpress/customize-widgets', '@wordpress/data', '@wordpress/edit-post', '@wordpress/edit-site', '@wordpress/edit-widgets', '@wordpress/editor', '@wordpress/format-library', '@wordpress/interface', '@wordpress/patterns', '@wordpress/preferences', '@wordpress/reusable-blocks', '@wordpress/router', '@wordpress/dataviews', '@wordpress/fields'];
/**
* A list of core modules that already opted-in to
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
(()=>{"use strict";var e={d:(r,o)=>{for(var s in o)e.o(o,s)&&!e.o(r,s)&&Object.defineProperty(r,s,{enumerable:!0,get:o[s]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},r={};e.r(r),e.d(r,{__dangerousOptInToUnstableAPIsOnlyForCoreModules:()=>n});const o=["@wordpress/block-directory","@wordpress/block-editor","@wordpress/block-library","@wordpress/blocks","@wordpress/commands","@wordpress/components","@wordpress/core-commands","@wordpress/core-data","@wordpress/customize-widgets","@wordpress/data","@wordpress/edit-post","@wordpress/edit-site","@wordpress/edit-widgets","@wordpress/editor","@wordpress/format-library","@wordpress/interface","@wordpress/patterns","@wordpress/preferences","@wordpress/reusable-blocks","@wordpress/router","@wordpress/dataviews"],s=[];let t;try{t=!1}catch(e){t=!0}const n=(e,r)=>{if(!o.includes(r))throw new Error(`You tried to opt-in to unstable APIs as module "${r}". This feature is only for JavaScript modules shipped with WordPress core. Please do not use it in plugins and themes as the unstable APIs will be removed without a warning. If you ignore this error and depend on unstable features, your product will inevitably break on one of the next WordPress releases.`);if(!t&&s.includes(r))throw new Error(`You tried to opt-in to unstable APIs as module "${r}" which is already registered. This feature is only for JavaScript modules shipped with WordPress core. Please do not use it in plugins and themes as the unstable APIs will be removed without a warning. If you ignore this error and depend on unstable features, your product will inevitably break on one of the next WordPress releases.`);if("I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress."!==e)throw new Error("You tried to opt-in to unstable APIs without confirming you know the consequences. This feature is only for JavaScript modules shipped with WordPress core. Please do not use it in plugins and themes as the unstable APIs will removed without a warning. If you ignore this error and depend on unstable features, your product will inevitably break on the next WordPress release.");return s.push(r),{lock:i,unlock:d}};function i(e,r){if(!e)throw new Error("Cannot lock an undefined object.");l in e||(e[l]={}),a.set(e[l],r)}function d(e){if(!e)throw new Error("Cannot unlock an undefined object.");if(!(l in e))throw new Error("Cannot unlock an object that was not locked before. ");return a.get(e[l])}const a=new WeakMap,l=Symbol("Private API ID");(window.wp=window.wp||{}).privateApis=r})();
(()=>{"use strict";var e={d:(r,o)=>{for(var s in o)e.o(o,s)&&!e.o(r,s)&&Object.defineProperty(r,s,{enumerable:!0,get:o[s]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},r={};e.r(r),e.d(r,{__dangerousOptInToUnstableAPIsOnlyForCoreModules:()=>n});const o=["@wordpress/block-directory","@wordpress/block-editor","@wordpress/block-library","@wordpress/blocks","@wordpress/commands","@wordpress/components","@wordpress/core-commands","@wordpress/core-data","@wordpress/customize-widgets","@wordpress/data","@wordpress/edit-post","@wordpress/edit-site","@wordpress/edit-widgets","@wordpress/editor","@wordpress/format-library","@wordpress/interface","@wordpress/patterns","@wordpress/preferences","@wordpress/reusable-blocks","@wordpress/router","@wordpress/dataviews","@wordpress/fields"],s=[];let t;try{t=!1}catch(e){t=!0}const n=(e,r)=>{if(!o.includes(r))throw new Error(`You tried to opt-in to unstable APIs as module "${r}". This feature is only for JavaScript modules shipped with WordPress core. Please do not use it in plugins and themes as the unstable APIs will be removed without a warning. If you ignore this error and depend on unstable features, your product will inevitably break on one of the next WordPress releases.`);if(!t&&s.includes(r))throw new Error(`You tried to opt-in to unstable APIs as module "${r}" which is already registered. This feature is only for JavaScript modules shipped with WordPress core. Please do not use it in plugins and themes as the unstable APIs will be removed without a warning. If you ignore this error and depend on unstable features, your product will inevitably break on one of the next WordPress releases.`);if("I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress."!==e)throw new Error("You tried to opt-in to unstable APIs without confirming you know the consequences. This feature is only for JavaScript modules shipped with WordPress core. Please do not use it in plugins and themes as the unstable APIs will removed without a warning. If you ignore this error and depend on unstable features, your product will inevitably break on the next WordPress release.");return s.push(r),{lock:i,unlock:d}};function i(e,r){if(!e)throw new Error("Cannot lock an undefined object.");l in e||(e[l]={}),a.set(e[l],r)}function d(e){if(!e)throw new Error("Cannot unlock an undefined object.");if(!(l in e))throw new Error("Cannot unlock an object that was not locked before. ");return a.get(e[l])}const a=new WeakMap,l=Symbol("Private API ID");(window.wp=window.wp||{}).privateApis=r})();
+23 -25
View File
@@ -248,17 +248,6 @@ const symbol = /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ext
const external_wp_notices_namespaceObject = window["wp"]["notices"];
;// CONCATENATED MODULE: external ["wp","coreData"]
const external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: external ["wp","privateApis"]
const external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/reusable-blocks/build-module/lock-unlock.js
/**
* WordPress dependencies
*/
const {
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.', '@wordpress/reusable-blocks');
;// CONCATENATED MODULE: ./node_modules/@wordpress/reusable-blocks/build-module/components/reusable-blocks-menu-items/reusable-block-convert-button.js
/**
* WordPress dependencies
@@ -278,14 +267,6 @@ const {
*/
const {
useReusableBlocksRenameHint,
ReusableBlocksRenameHint
} = unlock(external_wp_blockEditor_namespaceObject.privateApis);
/**
* Menu control to convert block(s) to reusable block.
*
@@ -295,12 +276,14 @@ const {
* @param {()=>void} props.onClose Callback to close the menu.
* @return {import('react').ComponentType} The menu control or null.
*/
function ReusableBlockConvertButton({
clientIds,
rootClientId,
onClose
}) {
const showRenameHint = useReusableBlocksRenameHint();
const [syncType, setSyncType] = (0,external_wp_element_namespaceObject.useState)(undefined);
const [isModalOpen, setIsModalOpen] = (0,external_wp_element_namespaceObject.useState)(false);
const [title, setTitle] = (0,external_wp_element_namespaceObject.useState)('');
@@ -329,7 +312,11 @@ function ReusableBlockConvertButton({
// Hide when block doesn't support being made reusable.
(0,external_wp_blocks_namespaceObject.hasBlockSupport)(block.name, 'reusable', true)) &&
// Hide when current doesn't have permission to do that.
!!canUser('create', 'blocks');
// Blocks refers to the wp_block post type, this checks the ability to create a post of that type.
!!canUser('create', {
kind: 'postType',
name: 'wp_block'
});
return _canConvert;
}, [clientIds, rootClientId]);
const {
@@ -364,7 +351,7 @@ function ReusableBlockConvertButton({
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.MenuItem, {
icon: library_symbol,
onClick: () => setIsModalOpen(true),
children: showRenameHint ? (0,external_wp_i18n_namespaceObject.__)('Create pattern/reusable block') : (0,external_wp_i18n_namespaceObject.__)('Create pattern')
children: (0,external_wp_i18n_namespaceObject.__)('Create pattern')
}), isModalOpen && /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Modal, {
title: (0,external_wp_i18n_namespaceObject.__)('Create pattern'),
onRequestClose: () => {
@@ -382,13 +369,15 @@ function ReusableBlockConvertButton({
},
children: /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: "5",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(ReusableBlocksRenameHint, {}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.TextControl, {
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.TextControl, {
__next40pxDefaultSize: true,
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Name'),
value: title,
onChange: setTitle,
placeholder: (0,external_wp_i18n_namespaceObject.__)('My pattern')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.ToggleControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject._x)('Synced', 'pattern (singular)'),
help: (0,external_wp_i18n_namespaceObject.__)('Sync this pattern across multiple locations.'),
checked: !syncType,
@@ -398,6 +387,7 @@ function ReusableBlockConvertButton({
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsxs)(external_wp_components_namespaceObject.__experimentalHStack, {
justify: "right",
children: [/*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
variant: "tertiary",
onClick: () => {
setIsModalOpen(false);
@@ -405,6 +395,7 @@ function ReusableBlockConvertButton({
},
children: (0,external_wp_i18n_namespaceObject.__)('Cancel')
}), /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(external_wp_components_namespaceObject.Button, {
__next40pxDefaultSize: true,
variant: "primary",
type: "submit",
children: (0,external_wp_i18n_namespaceObject.__)('Create')
@@ -456,12 +447,19 @@ function ReusableBlocksManageButton({
const reusableBlock = getBlock(clientId);
return {
canRemove: canRemoveBlock(clientId),
isVisible: !!reusableBlock && (0,external_wp_blocks_namespaceObject.isReusableBlock)(reusableBlock) && !!canUser('update', 'blocks', reusableBlock.attributes.ref),
isVisible: !!reusableBlock && (0,external_wp_blocks_namespaceObject.isReusableBlock)(reusableBlock) && !!canUser('update', {
kind: 'postType',
name: 'wp_block',
id: reusableBlock.attributes.ref
}),
innerBlockCount: getBlockCount(clientId),
// The site editor and templates both check whether the user
// has edit_theme_options capabilities. We can leverage that here
// and omit the manage patterns link if the user can't access it.
managePatternsUrl: canUser('create', 'templates') ? (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', {
managePatternsUrl: canUser('create', {
kind: 'postType',
name: 'wp_template'
}) ? (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', {
path: '/patterns'
}) : (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
post_type: 'wp_block'
File diff suppressed because one or more lines are too long
+42 -39
View File
@@ -948,6 +948,9 @@ function toTree({
}
if (shouldInsertPadding && i === text.length) {
append(getParent(pointer), ZWNBSP);
// We CANNOT use CSS to add a placeholder with pseudo elements on
// the main block wrappers because that could clash with theme CSS.
if (placeholder && text.length === 0) {
append(getParent(pointer), {
type: 'span',
@@ -3716,40 +3719,40 @@ function useRichText({
}
// Internal values are updated synchronously, unlike props and state.
const _value = (0,external_wp_element_namespaceObject.useRef)(value);
const record = (0,external_wp_element_namespaceObject.useRef)();
const _valueRef = (0,external_wp_element_namespaceObject.useRef)(value);
const recordRef = (0,external_wp_element_namespaceObject.useRef)();
function setRecordFromProps() {
_value.current = value;
record.current = value;
_valueRef.current = value;
recordRef.current = value;
if (!(value instanceof RichTextData)) {
record.current = value ? RichTextData.fromHTMLString(value, {
recordRef.current = value ? RichTextData.fromHTMLString(value, {
preserveWhiteSpace
}) : RichTextData.empty();
}
// To do: make rich text internally work with RichTextData.
record.current = {
text: record.current.text,
formats: record.current.formats,
replacements: record.current.replacements
recordRef.current = {
text: recordRef.current.text,
formats: recordRef.current.formats,
replacements: recordRef.current.replacements
};
if (disableFormats) {
record.current.formats = Array(value.length);
record.current.replacements = Array(value.length);
recordRef.current.formats = Array(value.length);
recordRef.current.replacements = Array(value.length);
}
if (__unstableAfterParse) {
record.current.formats = __unstableAfterParse(record.current);
recordRef.current.formats = __unstableAfterParse(recordRef.current);
}
record.current.start = selectionStart;
record.current.end = selectionEnd;
recordRef.current.start = selectionStart;
recordRef.current.end = selectionEnd;
}
const hadSelectionUpdate = (0,external_wp_element_namespaceObject.useRef)(false);
if (!record.current) {
hadSelectionUpdate.current = isSelected;
const hadSelectionUpdateRef = (0,external_wp_element_namespaceObject.useRef)(false);
if (!recordRef.current) {
hadSelectionUpdateRef.current = isSelected;
setRecordFromProps();
} else if (selectionStart !== record.current.start || selectionEnd !== record.current.end) {
hadSelectionUpdate.current = isSelected;
record.current = {
...record.current,
} else if (selectionStart !== recordRef.current.start || selectionEnd !== recordRef.current.end) {
hadSelectionUpdateRef.current = isSelected;
recordRef.current = {
...recordRef.current,
start: selectionStart,
end: selectionEnd,
activeFormats: undefined
@@ -3763,10 +3766,10 @@ function useRichText({
* @param {Object} newRecord The record to sync and apply.
*/
function handleChange(newRecord) {
record.current = newRecord;
recordRef.current = newRecord;
applyRecord(newRecord);
if (disableFormats) {
_value.current = newRecord.text;
_valueRef.current = newRecord.text;
} else {
const newFormats = __unstableBeforeSerialize ? __unstableBeforeSerialize(newRecord) : newRecord.formats;
newRecord = {
@@ -3774,12 +3777,12 @@ function useRichText({
formats: newFormats
};
if (typeof value === 'string') {
_value.current = toHTMLString({
_valueRef.current = toHTMLString({
value: newRecord,
preserveWhiteSpace
});
} else {
_value.current = new RichTextData(newRecord);
_valueRef.current = new RichTextData(newRecord);
}
}
const {
@@ -3787,14 +3790,14 @@ function useRichText({
end,
formats,
text
} = record.current;
} = recordRef.current;
// Selection must be updated first, so it is recorded in history when
// the content change happens.
// We batch both calls to only attempt to rerender once.
registry.batch(() => {
onSelectionChange(start, end);
onChange(_value.current, {
onChange(_valueRef.current, {
__unstableFormats: formats,
__unstableText: text
});
@@ -3803,13 +3806,13 @@ function useRichText({
}
function applyFromProps() {
setRecordFromProps();
applyRecord(record.current);
applyRecord(recordRef.current);
}
const didMount = (0,external_wp_element_namespaceObject.useRef)(false);
const didMountRef = (0,external_wp_element_namespaceObject.useRef)(false);
// Value updates must happen synchonously to avoid overwriting newer values.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (didMount.current && value !== _value.current) {
if (didMountRef.current && value !== _valueRef.current) {
applyFromProps();
forceRender();
}
@@ -3817,19 +3820,19 @@ function useRichText({
// Value updates must happen synchonously to avoid overwriting newer values.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!hadSelectionUpdate.current) {
if (!hadSelectionUpdateRef.current) {
return;
}
if (ref.current.ownerDocument.activeElement !== ref.current) {
ref.current.focus();
}
applyRecord(record.current);
hadSelectionUpdate.current = false;
}, [hadSelectionUpdate.current]);
applyRecord(recordRef.current);
hadSelectionUpdateRef.current = false;
}, [hadSelectionUpdateRef.current]);
const mergedRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, useDefaultStyle(), useBoundaryStyle({
record
record: recordRef
}), useEventListeners({
record,
record: recordRef,
handleChange,
applyRecord,
createRecord,
@@ -3838,16 +3841,16 @@ function useRichText({
forceRender
}), (0,external_wp_compose_namespaceObject.useRefEffect)(() => {
applyFromProps();
didMount.current = true;
didMountRef.current = true;
}, [placeholder, ...__unstableDependencies])]);
return {
value: record.current,
value: recordRef.current,
// A function to get the most recent value so event handlers in
// useRichText implementations have access to it. For example when
// listening to input events, we internally update the state, but this
// state is not yet available to the input event handler because React
// may re-render asynchronously.
getValue: () => record.current,
getValue: () => recordRef.current,
onChange: handleChange,
ref: mergedRefs
};
+1
View File
@@ -852,6 +852,7 @@ function parsePath(path) {
;// CONCATENATED MODULE: external ["wp","url"]
const external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/router/build-module/history.js
/* wp:polyfill */
/**
* External dependencies
*/
+144
View File
@@ -0,0 +1,144 @@
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (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 */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
m: () => (/* binding */ setup),
L: () => (/* reexport */ speak)
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/shared/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/shared/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/shared/index.js
/**
* Internal dependencies
*/
/**
* 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 {'polite'|'assertive'} [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');
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/module/index.js
/**
* Internal dependencies
*/
/**
* This no-op function is exported to provide compatibility with the `wp-a11y` Script.
*
* Filters should inject the relevant HTML on page load instead of requiring setup.
*/
const setup = () => {};
var __webpack_exports__setup = __webpack_exports__.m;
var __webpack_exports__speak = __webpack_exports__.L;
export { __webpack_exports__setup as setup, __webpack_exports__speak as speak };
@@ -0,0 +1 @@
var e={d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{m:()=>a,L:()=>o});let n="";function o(e,t){!function(){const e=document.getElementsByClassName("a11y-speak-region"),t=document.getElementById("a11y-speak-intro-text");for(let t=0;t<e.length;t++)e[t].textContent="";t&&t.setAttribute("hidden","hidden")}(),e=function(e){return e=e.replace(/<[^<>]+>/g," "),n===e&&(e+=" "),n=e,e}(e);const o=document.getElementById("a11y-speak-intro-text"),a=document.getElementById("a11y-speak-assertive"),r=document.getElementById("a11y-speak-polite");a&&"assertive"===t?a.textContent=e:r&&(r.textContent=e),o&&o.removeAttribute("hidden")}const a=()=>{};var r=t.m,s=t.L;export{r as setup,s as speak};
@@ -0,0 +1,97 @@
import * as __WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__ from "@wordpress/interactivity";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (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 */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
;// CONCATENATED MODULE: external "@wordpress/interactivity"
var x = (y) => {
var x = {}; __webpack_require__.d(x, y); return x
}
var y = (x) => (() => (x))
const interactivity_namespaceObject = x({ ["store"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.store) });
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-library/build-module/file/utils/index.js
/**
* Uses a combination of user agent matching and feature detection to determine whether
* the current browser supports rendering PDFs inline.
*
* @return {boolean} Whether or not the browser supports inline PDFs.
*/
const browserSupportsPdfs = () => {
// Most mobile devices include "Mobi" in their UA.
if (window.navigator.userAgent.indexOf('Mobi') > -1) {
return false;
}
// Android tablets are the noteable exception.
if (window.navigator.userAgent.indexOf('Android') > -1) {
return false;
}
// iPad pretends to be a Mac.
if (window.navigator.userAgent.indexOf('Macintosh') > -1 && window.navigator.maxTouchPoints && window.navigator.maxTouchPoints > 2) {
return false;
}
// IE only supports PDFs when there's an ActiveX object available for it.
if (!!(window.ActiveXObject || 'ActiveXObject' in window) && !(createActiveXObject('AcroPDF.PDF') || createActiveXObject('PDF.PdfCtrl'))) {
return false;
}
return true;
};
/**
* Helper function for creating ActiveX objects, catching any errors that are thrown
* when it's generated.
*
* @param {string} type The name of the ActiveX object to create.
* @return {window.ActiveXObject|undefined} The generated ActiveXObject, or null if it failed.
*/
const createActiveXObject = type => {
let ax;
try {
ax = new window.ActiveXObject(type);
} catch (e) {
ax = undefined;
}
return ax;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-library/build-module/file/view.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
(0,interactivity_namespaceObject.store)('core/file', {
state: {
get hasPdfPreview() {
return browserSupportsPdfs();
}
}
}, {
lock: true
});
@@ -0,0 +1 @@
import*as e from"@wordpress/interactivity";var t={d:(e,o)=>{for(var r in o)t.o(o,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:o[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const o=(e=>{var o={};return t.d(o,e),o})({store:()=>e.store}),r=e=>{let t;try{t=new window.ActiveXObject(e)}catch(e){t=void 0}return t};(0,o.store)("core/file",{state:{get hasPdfPreview(){return!(window.navigator.userAgent.indexOf("Mobi")>-1||window.navigator.userAgent.indexOf("Android")>-1||window.navigator.userAgent.indexOf("Macintosh")>-1&&window.navigator.maxTouchPoints&&window.navigator.maxTouchPoints>2||(window.ActiveXObject||"ActiveXObject"in window)&&!r("AcroPDF.PDF")&&!r("PDF.PdfCtrl"))}}},{lock:!0});
@@ -0,0 +1,440 @@
import * as __WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__ from "@wordpress/interactivity";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (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 */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
;// CONCATENATED MODULE: external "@wordpress/interactivity"
var x = (y) => {
var x = {}; __webpack_require__.d(x, y); return x
}
var y = (x) => (() => (x))
const interactivity_namespaceObject = x({ ["getContext"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getContext), ["getElement"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getElement), ["store"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.store) });
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-library/build-module/image/view.js
/**
* WordPress dependencies
*/
/**
* Tracks whether user is touching screen; used to differentiate behavior for
* touch and mouse input.
*
* @type {boolean}
*/
let isTouching = false;
/**
* Tracks the last time the screen was touched; used to differentiate behavior
* for touch and mouse input.
*
* @type {number}
*/
let lastTouchTime = 0;
const {
state,
actions,
callbacks
} = (0,interactivity_namespaceObject.store)('core/image', {
state: {
currentImageId: null,
get currentImage() {
return state.metadata[state.currentImageId];
},
get overlayOpened() {
return state.currentImageId !== null;
},
get roleAttribute() {
return state.overlayOpened ? 'dialog' : null;
},
get ariaModal() {
return state.overlayOpened ? 'true' : null;
},
get enlargedSrc() {
return state.currentImage.uploadedSrc || 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
},
get figureStyles() {
return state.overlayOpened && `${state.currentImage.figureStyles?.replace(/margin[^;]*;?/g, '')};`;
},
get imgStyles() {
return state.overlayOpened && `${state.currentImage.imgStyles?.replace(/;$/, '')}; object-fit:cover;`;
},
get imageButtonRight() {
const {
imageId
} = (0,interactivity_namespaceObject.getContext)();
return state.metadata[imageId].imageButtonRight;
},
get imageButtonTop() {
const {
imageId
} = (0,interactivity_namespaceObject.getContext)();
return state.metadata[imageId].imageButtonTop;
},
get isContentHidden() {
const ctx = (0,interactivity_namespaceObject.getContext)();
return state.overlayEnabled && state.currentImageId === ctx.imageId;
},
get isContentVisible() {
const ctx = (0,interactivity_namespaceObject.getContext)();
return !state.overlayEnabled && state.currentImageId === ctx.imageId;
}
},
actions: {
showLightbox() {
const {
imageId
} = (0,interactivity_namespaceObject.getContext)();
// Bails out if the image has not loaded yet.
if (!state.metadata[imageId].imageRef?.complete) {
return;
}
// Stores the positions of the scroll to fix it until the overlay is
// closed.
state.scrollTopReset = document.documentElement.scrollTop;
state.scrollLeftReset = document.documentElement.scrollLeft;
// Sets the current expanded image in the state and enables the overlay.
state.overlayEnabled = true;
state.currentImageId = imageId;
// Computes the styles of the overlay for the animation.
callbacks.setOverlayStyles();
},
hideLightbox() {
if (state.overlayEnabled) {
// Starts the overlay closing animation. The showClosingAnimation
// class is used to avoid showing it on page load.
state.showClosingAnimation = true;
state.overlayEnabled = false;
// Waits until the close animation has completed before allowing a
// user to scroll again. The duration of this animation is defined in
// the `styles.scss` file, but in any case we should wait a few
// milliseconds longer than the duration, otherwise a user may scroll
// too soon and cause the animation to look sloppy.
setTimeout(function () {
// Delays before changing the focus. Otherwise the focus ring will
// appear on Firefox before the image has finished animating, which
// looks broken.
state.currentImage.buttonRef.focus({
preventScroll: true
});
// Resets the current image id to mark the overlay as closed.
state.currentImageId = null;
}, 450);
}
},
handleKeydown(event) {
if (state.overlayEnabled) {
// Focuses the close button when the user presses the tab key.
if (event.key === 'Tab') {
event.preventDefault();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
ref.querySelector('button').focus();
}
// Closes the lightbox when the user presses the escape key.
if (event.key === 'Escape') {
actions.hideLightbox();
}
}
},
handleTouchMove(event) {
// On mobile devices, prevents triggering the scroll event because
// otherwise the page jumps around when it resets the scroll position.
// This also means that closing the lightbox requires that a user
// perform a simple tap. This may be changed in the future if there is a
// better alternative to override or reset the scroll position during
// swipe actions.
if (state.overlayEnabled) {
event.preventDefault();
}
},
handleTouchStart() {
isTouching = true;
},
handleTouchEnd() {
// Waits a few milliseconds before resetting to ensure that pinch to
// zoom works consistently on mobile devices when the lightbox is open.
lastTouchTime = Date.now();
isTouching = false;
},
handleScroll() {
// Prevents scrolling behaviors that trigger content shift while the
// lightbox is open. It would be better to accomplish through CSS alone,
// but using overflow: hidden is currently the only way to do so and
// that causes a layout to shift and prevents the zoom animation from
// working in some cases because it's not possible to account for the
// layout shift when doing the animation calculations. Instead, it uses
// JavaScript to prevent and reset the scrolling behavior.
if (state.overlayOpened) {
// Avoids overriding the scroll behavior on mobile devices because
// doing so breaks the pinch to zoom functionality, and users should
// be able to zoom in further on the high-res image.
if (!isTouching && Date.now() - lastTouchTime > 450) {
// It doesn't rely on `event.preventDefault()` to prevent scrolling
// because the scroll event can't be canceled, so it resets the
// position instead.
window.scrollTo(state.scrollLeftReset, state.scrollTopReset);
}
}
}
},
callbacks: {
setOverlayStyles() {
if (!state.overlayEnabled) {
return;
}
let {
naturalWidth,
naturalHeight,
offsetWidth: originalWidth,
offsetHeight: originalHeight
} = state.currentImage.imageRef;
let {
x: screenPosX,
y: screenPosY
} = state.currentImage.imageRef.getBoundingClientRect();
// Natural ratio of the image clicked to open the lightbox.
const naturalRatio = naturalWidth / naturalHeight;
// Original ratio of the image clicked to open the lightbox.
let originalRatio = originalWidth / originalHeight;
// If it has object-fit: contain, recalculates the original sizes
// and the screen position without the blank spaces.
if (state.currentImage.scaleAttr === 'contain') {
if (naturalRatio > originalRatio) {
const heightWithoutSpace = originalWidth / naturalRatio;
// Recalculates screen position without the top space.
screenPosY += (originalHeight - heightWithoutSpace) / 2;
originalHeight = heightWithoutSpace;
} else {
const widthWithoutSpace = originalHeight * naturalRatio;
// Recalculates screen position without the left space.
screenPosX += (originalWidth - widthWithoutSpace) / 2;
originalWidth = widthWithoutSpace;
}
}
originalRatio = originalWidth / originalHeight;
// Typically, it uses the image's full-sized dimensions. If those
// dimensions have not been set (i.e. an external image with only one
// size), the image's dimensions in the lightbox are the same
// as those of the image in the content.
let imgMaxWidth = parseFloat(state.currentImage.targetWidth !== 'none' ? state.currentImage.targetWidth : naturalWidth);
let imgMaxHeight = parseFloat(state.currentImage.targetHeight !== 'none' ? state.currentImage.targetHeight : naturalHeight);
// Ratio of the biggest image stored in the database.
let imgRatio = imgMaxWidth / imgMaxHeight;
let containerMaxWidth = imgMaxWidth;
let containerMaxHeight = imgMaxHeight;
let containerWidth = imgMaxWidth;
let containerHeight = imgMaxHeight;
// Checks if the target image has a different ratio than the original
// one (thumbnail). Recalculates the width and height.
if (naturalRatio.toFixed(2) !== imgRatio.toFixed(2)) {
if (naturalRatio > imgRatio) {
// If the width is reached before the height, it keeps the maxWidth
// and recalculates the height unless the difference between the
// maxHeight and the reducedHeight is higher than the maxWidth,
// where it keeps the reducedHeight and recalculate the width.
const reducedHeight = imgMaxWidth / naturalRatio;
if (imgMaxHeight - reducedHeight > imgMaxWidth) {
imgMaxHeight = reducedHeight;
imgMaxWidth = reducedHeight * naturalRatio;
} else {
imgMaxHeight = imgMaxWidth / naturalRatio;
}
} else {
// If the height is reached before the width, it keeps the maxHeight
// and recalculate the width unlesss the difference between the
// maxWidth and the reducedWidth is higher than the maxHeight, where
// it keeps the reducedWidth and recalculate the height.
const reducedWidth = imgMaxHeight * naturalRatio;
if (imgMaxWidth - reducedWidth > imgMaxHeight) {
imgMaxWidth = reducedWidth;
imgMaxHeight = reducedWidth / naturalRatio;
} else {
imgMaxWidth = imgMaxHeight * naturalRatio;
}
}
containerWidth = imgMaxWidth;
containerHeight = imgMaxHeight;
imgRatio = imgMaxWidth / imgMaxHeight;
// Calculates the max size of the container.
if (originalRatio > imgRatio) {
containerMaxWidth = imgMaxWidth;
containerMaxHeight = containerMaxWidth / originalRatio;
} else {
containerMaxHeight = imgMaxHeight;
containerMaxWidth = containerMaxHeight * originalRatio;
}
}
// If the image has been pixelated on purpose, it keeps that size.
if (originalWidth > containerWidth || originalHeight > containerHeight) {
containerWidth = originalWidth;
containerHeight = originalHeight;
}
// Calculates the final lightbox image size and the scale factor.
// MaxWidth is either the window container (accounting for padding) or
// the image resolution.
let horizontalPadding = 0;
if (window.innerWidth > 480) {
horizontalPadding = 80;
} else if (window.innerWidth > 1920) {
horizontalPadding = 160;
}
const verticalPadding = 80;
const targetMaxWidth = Math.min(window.innerWidth - horizontalPadding, containerWidth);
const targetMaxHeight = Math.min(window.innerHeight - verticalPadding, containerHeight);
const targetContainerRatio = targetMaxWidth / targetMaxHeight;
if (originalRatio > targetContainerRatio) {
// If targetMaxWidth is reached before targetMaxHeight.
containerWidth = targetMaxWidth;
containerHeight = containerWidth / originalRatio;
} else {
// If targetMaxHeight is reached before targetMaxWidth.
containerHeight = targetMaxHeight;
containerWidth = containerHeight * originalRatio;
}
const containerScale = originalWidth / containerWidth;
const lightboxImgWidth = imgMaxWidth * (containerWidth / containerMaxWidth);
const lightboxImgHeight = imgMaxHeight * (containerHeight / containerMaxHeight);
// As of this writing, using the calculations above will render the
// lightbox with a small, erroneous whitespace on the left side of the
// image in iOS Safari, perhaps due to an inconsistency in how browsers
// handle absolute positioning and CSS transformation. In any case,
// adding 1 pixel to the container width and height solves the problem,
// though this can be removed if the issue is fixed in the future.
state.overlayStyles = `
:root {
--wp--lightbox-initial-top-position: ${screenPosY}px;
--wp--lightbox-initial-left-position: ${screenPosX}px;
--wp--lightbox-container-width: ${containerWidth + 1}px;
--wp--lightbox-container-height: ${containerHeight + 1}px;
--wp--lightbox-image-width: ${lightboxImgWidth}px;
--wp--lightbox-image-height: ${lightboxImgHeight}px;
--wp--lightbox-scale: ${containerScale};
--wp--lightbox-scrollbar-width: ${window.innerWidth - document.documentElement.clientWidth}px;
}
`;
},
setButtonStyles() {
const {
imageId
} = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
state.metadata[imageId].imageRef = ref;
state.metadata[imageId].currentSrc = ref.currentSrc;
const {
naturalWidth,
naturalHeight,
offsetWidth,
offsetHeight
} = ref;
// If the image isn't loaded yet, it can't calculate where the button
// should be.
if (naturalWidth === 0 || naturalHeight === 0) {
return;
}
const figure = ref.parentElement;
const figureWidth = ref.parentElement.clientWidth;
// It needs special handling for the height because a caption will cause
// the figure to be taller than the image, which means it needs to
// account for that when calculating the placement of the button in the
// top right corner of the image.
let figureHeight = ref.parentElement.clientHeight;
const caption = figure.querySelector('figcaption');
if (caption) {
const captionComputedStyle = window.getComputedStyle(caption);
if (!['absolute', 'fixed'].includes(captionComputedStyle.position)) {
figureHeight = figureHeight - caption.offsetHeight - parseFloat(captionComputedStyle.marginTop) - parseFloat(captionComputedStyle.marginBottom);
}
}
const buttonOffsetTop = figureHeight - offsetHeight;
const buttonOffsetRight = figureWidth - offsetWidth;
let imageButtonTop = buttonOffsetTop + 16;
let imageButtonRight = buttonOffsetRight + 16;
// In the case of an image with object-fit: contain, the size of the
// <img> element can be larger than the image itself, so it needs to
// calculate where to place the button.
if (state.metadata[imageId].scaleAttr === 'contain') {
// Natural ratio of the image.
const naturalRatio = naturalWidth / naturalHeight;
// Offset ratio of the image.
const offsetRatio = offsetWidth / offsetHeight;
if (naturalRatio >= offsetRatio) {
// If it reaches the width first, it keeps the width and compute the
// height.
const referenceHeight = offsetWidth / naturalRatio;
imageButtonTop = (offsetHeight - referenceHeight) / 2 + buttonOffsetTop + 16;
imageButtonRight = buttonOffsetRight + 16;
} else {
// If it reaches the height first, it keeps the height and compute
// the width.
const referenceWidth = offsetHeight * naturalRatio;
imageButtonTop = buttonOffsetTop + 16;
imageButtonRight = (offsetWidth - referenceWidth) / 2 + buttonOffsetRight + 16;
}
}
state.metadata[imageId].imageButtonTop = imageButtonTop;
state.metadata[imageId].imageButtonRight = imageButtonRight;
},
setOverlayFocus() {
if (state.overlayEnabled) {
// Moves the focus to the dialog when it opens.
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
ref.focus();
}
},
initTriggerButton() {
const {
imageId
} = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
state.metadata[imageId].buttonRef = ref;
}
}
}, {
lock: true
});
@@ -0,0 +1 @@
import*as t from"@wordpress/interactivity";var e={d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)};const n=(t=>{var n={};return e.d(n,t),n})({getContext:()=>t.getContext,getElement:()=>t.getElement,store:()=>t.store});let o=!1,a=0;const{state:r,actions:i,callbacks:l}=(0,n.store)("core/image",{state:{currentImageId:null,get currentImage(){return r.metadata[r.currentImageId]},get overlayOpened(){return null!==r.currentImageId},get roleAttribute(){return r.overlayOpened?"dialog":null},get ariaModal(){return r.overlayOpened?"true":null},get enlargedSrc(){return r.currentImage.uploadedSrc||"data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="},get figureStyles(){return r.overlayOpened&&`${r.currentImage.figureStyles?.replace(/margin[^;]*;?/g,"")};`},get imgStyles(){return r.overlayOpened&&`${r.currentImage.imgStyles?.replace(/;$/,"")}; object-fit:cover;`},get imageButtonRight(){const{imageId:t}=(0,n.getContext)();return r.metadata[t].imageButtonRight},get imageButtonTop(){const{imageId:t}=(0,n.getContext)();return r.metadata[t].imageButtonTop},get isContentHidden(){const t=(0,n.getContext)();return r.overlayEnabled&&r.currentImageId===t.imageId},get isContentVisible(){const t=(0,n.getContext)();return!r.overlayEnabled&&r.currentImageId===t.imageId}},actions:{showLightbox(){const{imageId:t}=(0,n.getContext)();r.metadata[t].imageRef?.complete&&(r.scrollTopReset=document.documentElement.scrollTop,r.scrollLeftReset=document.documentElement.scrollLeft,r.overlayEnabled=!0,r.currentImageId=t,l.setOverlayStyles())},hideLightbox(){r.overlayEnabled&&(r.showClosingAnimation=!0,r.overlayEnabled=!1,setTimeout((function(){r.currentImage.buttonRef.focus({preventScroll:!0}),r.currentImageId=null}),450))},handleKeydown(t){if(r.overlayEnabled){if("Tab"===t.key){t.preventDefault();const{ref:e}=(0,n.getElement)();e.querySelector("button").focus()}"Escape"===t.key&&i.hideLightbox()}},handleTouchMove(t){r.overlayEnabled&&t.preventDefault()},handleTouchStart(){o=!0},handleTouchEnd(){a=Date.now(),o=!1},handleScroll(){r.overlayOpened&&!o&&Date.now()-a>450&&window.scrollTo(r.scrollLeftReset,r.scrollTopReset)}},callbacks:{setOverlayStyles(){if(!r.overlayEnabled)return;let{naturalWidth:t,naturalHeight:e,offsetWidth:n,offsetHeight:o}=r.currentImage.imageRef,{x:a,y:i}=r.currentImage.imageRef.getBoundingClientRect();const l=t/e;let g=n/o;if("contain"===r.currentImage.scaleAttr)if(l>g){const t=n/l;i+=(o-t)/2,o=t}else{const t=o*l;a+=(n-t)/2,n=t}g=n/o;let c=parseFloat("none"!==r.currentImage.targetWidth?r.currentImage.targetWidth:t),s=parseFloat("none"!==r.currentImage.targetHeight?r.currentImage.targetHeight:e),d=c/s,u=c,m=s,h=c,p=s;if(l.toFixed(2)!==d.toFixed(2)){if(l>d){const t=c/l;s-t>c?(s=t,c=t*l):s=c/l}else{const t=s*l;c-t>s?(c=t,s=t/l):c=s*l}h=c,p=s,d=c/s,g>d?(u=c,m=u/g):(m=s,u=m*g)}(n>h||o>p)&&(h=n,p=o);let f=0;window.innerWidth>480?f=80:window.innerWidth>1920&&(f=160);const y=Math.min(window.innerWidth-f,h),b=Math.min(window.innerHeight-80,p);g>y/b?(h=y,p=h/g):(p=b,h=p*g);const w=n/h,I=c*(h/u),x=s*(p/m);r.overlayStyles=`\n\t\t\t\t:root {\n\t\t\t\t\t--wp--lightbox-initial-top-position: ${i}px;\n\t\t\t\t\t--wp--lightbox-initial-left-position: ${a}px;\n\t\t\t\t\t--wp--lightbox-container-width: ${h+1}px;\n\t\t\t\t\t--wp--lightbox-container-height: ${p+1}px;\n\t\t\t\t\t--wp--lightbox-image-width: ${I}px;\n\t\t\t\t\t--wp--lightbox-image-height: ${x}px;\n\t\t\t\t\t--wp--lightbox-scale: ${w};\n\t\t\t\t\t--wp--lightbox-scrollbar-width: ${window.innerWidth-document.documentElement.clientWidth}px;\n\t\t\t\t}\n\t\t\t`},setButtonStyles(){const{imageId:t}=(0,n.getContext)(),{ref:e}=(0,n.getElement)();r.metadata[t].imageRef=e,r.metadata[t].currentSrc=e.currentSrc;const{naturalWidth:o,naturalHeight:a,offsetWidth:i,offsetHeight:l}=e;if(0===o||0===a)return;const g=e.parentElement,c=e.parentElement.clientWidth;let s=e.parentElement.clientHeight;const d=g.querySelector("figcaption");if(d){const t=window.getComputedStyle(d);["absolute","fixed"].includes(t.position)||(s=s-d.offsetHeight-parseFloat(t.marginTop)-parseFloat(t.marginBottom))}const u=s-l,m=c-i;let h=u+16,p=m+16;if("contain"===r.metadata[t].scaleAttr){const t=o/a;if(t>=i/l){h=(l-i/t)/2+u+16,p=m+16}else{h=u+16,p=(i-l*t)/2+m+16}}r.metadata[t].imageButtonTop=h,r.metadata[t].imageButtonRight=p},setOverlayFocus(){if(r.overlayEnabled){const{ref:t}=(0,n.getElement)();t.focus()}},initTriggerButton(){const{imageId:t}=(0,n.getContext)(),{ref:e}=(0,n.getElement)();r.metadata[t].buttonRef=e}}},{lock:!0});
@@ -0,0 +1,223 @@
import * as __WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__ from "@wordpress/interactivity";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (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 */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
;// CONCATENATED MODULE: external "@wordpress/interactivity"
var x = (y) => {
var x = {}; __webpack_require__.d(x, y); return x
}
var y = (x) => (() => (x))
const interactivity_namespaceObject = x({ ["getContext"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getContext), ["getElement"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getElement), ["store"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.store) });
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-library/build-module/navigation/view.js
/**
* WordPress dependencies
*/
const focusableSelectors = ['a[href]', 'input:not([disabled]):not([type="hidden"]):not([aria-hidden])', 'select:not([disabled]):not([aria-hidden])', 'textarea:not([disabled]):not([aria-hidden])', 'button:not([disabled]):not([aria-hidden])', '[contenteditable]', '[tabindex]:not([tabindex^="-"])'];
// This is a fix for Safari in iOS/iPadOS. Without it, Safari doesn't focus out
// when the user taps in the body. It can be removed once we add an overlay to
// capture the clicks, instead of relying on the focusout event.
document.addEventListener('click', () => {});
const {
state,
actions
} = (0,interactivity_namespaceObject.store)('core/navigation', {
state: {
get roleAttribute() {
const ctx = (0,interactivity_namespaceObject.getContext)();
return ctx.type === 'overlay' && state.isMenuOpen ? 'dialog' : null;
},
get ariaModal() {
const ctx = (0,interactivity_namespaceObject.getContext)();
return ctx.type === 'overlay' && state.isMenuOpen ? 'true' : null;
},
get ariaLabel() {
const ctx = (0,interactivity_namespaceObject.getContext)();
return ctx.type === 'overlay' && state.isMenuOpen ? ctx.ariaLabel : null;
},
get isMenuOpen() {
// The menu is opened if either `click`, `hover` or `focus` is true.
return Object.values(state.menuOpenedBy).filter(Boolean).length > 0;
},
get menuOpenedBy() {
const ctx = (0,interactivity_namespaceObject.getContext)();
return ctx.type === 'overlay' ? ctx.overlayOpenedBy : ctx.submenuOpenedBy;
}
},
actions: {
openMenuOnHover() {
const {
type,
overlayOpenedBy
} = (0,interactivity_namespaceObject.getContext)();
if (type === 'submenu' &&
// Only open on hover if the overlay is closed.
Object.values(overlayOpenedBy || {}).filter(Boolean).length === 0) {
actions.openMenu('hover');
}
},
closeMenuOnHover() {
const {
type,
overlayOpenedBy
} = (0,interactivity_namespaceObject.getContext)();
if (type === 'submenu' &&
// Only close on hover if the overlay is closed.
Object.values(overlayOpenedBy || {}).filter(Boolean).length === 0) {
actions.closeMenu('hover');
}
},
openMenuOnClick() {
const ctx = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
ctx.previousFocus = ref;
actions.openMenu('click');
},
closeMenuOnClick() {
actions.closeMenu('click');
actions.closeMenu('focus');
},
openMenuOnFocus() {
actions.openMenu('focus');
},
toggleMenuOnClick() {
const ctx = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
// Safari won't send focus to the clicked element, so we need to manually place it: https://bugs.webkit.org/show_bug.cgi?id=22261
if (window.document.activeElement !== ref) {
ref.focus();
}
const {
menuOpenedBy
} = state;
if (menuOpenedBy.click || menuOpenedBy.focus) {
actions.closeMenu('click');
actions.closeMenu('focus');
} else {
ctx.previousFocus = ref;
actions.openMenu('click');
}
},
handleMenuKeydown(event) {
const {
type,
firstFocusableElement,
lastFocusableElement
} = (0,interactivity_namespaceObject.getContext)();
if (state.menuOpenedBy.click) {
// If Escape close the menu.
if (event?.key === 'Escape') {
actions.closeMenu('click');
actions.closeMenu('focus');
return;
}
// Trap focus if it is an overlay (main menu).
if (type === 'overlay' && event.key === 'Tab') {
// If shift + tab it change the direction.
if (event.shiftKey && window.document.activeElement === firstFocusableElement) {
event.preventDefault();
lastFocusableElement.focus();
} else if (!event.shiftKey && window.document.activeElement === lastFocusableElement) {
event.preventDefault();
firstFocusableElement.focus();
}
}
}
},
handleMenuFocusout(event) {
const {
modal,
type
} = (0,interactivity_namespaceObject.getContext)();
// If focus is outside modal, and in the document, close menu
// event.target === The element losing focus
// event.relatedTarget === The element receiving focus (if any)
// When focusout is outside the document,
// `window.document.activeElement` doesn't change.
// The event.relatedTarget is null when something outside the navigation menu is clicked. This is only necessary for Safari.
if (event.relatedTarget === null || !modal?.contains(event.relatedTarget) && event.target !== window.document.activeElement && type === 'submenu') {
actions.closeMenu('click');
actions.closeMenu('focus');
}
},
openMenu(menuOpenedOn = 'click') {
const {
type
} = (0,interactivity_namespaceObject.getContext)();
state.menuOpenedBy[menuOpenedOn] = true;
if (type === 'overlay') {
// Add a `has-modal-open` class to the <html> root.
document.documentElement.classList.add('has-modal-open');
}
},
closeMenu(menuClosedOn = 'click') {
const ctx = (0,interactivity_namespaceObject.getContext)();
state.menuOpenedBy[menuClosedOn] = false;
// Check if the menu is still open or not.
if (!state.isMenuOpen) {
if (ctx.modal?.contains(window.document.activeElement)) {
ctx.previousFocus?.focus();
}
ctx.modal = null;
ctx.previousFocus = null;
if (ctx.type === 'overlay') {
document.documentElement.classList.remove('has-modal-open');
}
}
}
},
callbacks: {
initMenu() {
const ctx = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
if (state.isMenuOpen) {
const focusableElements = ref.querySelectorAll(focusableSelectors);
ctx.modal = ref;
ctx.firstFocusableElement = focusableElements[0];
ctx.lastFocusableElement = focusableElements[focusableElements.length - 1];
}
},
focusFirstElement() {
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
if (state.isMenuOpen) {
const focusableElements = ref.querySelectorAll(focusableSelectors);
focusableElements?.[0]?.focus();
}
}
}
}, {
lock: true
});
@@ -0,0 +1 @@
import*as e from"@wordpress/interactivity";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const n=(e=>{var n={};return t.d(n,e),n})({getContext:()=>e.getContext,getElement:()=>e.getElement,store:()=>e.store}),o=["a[href]",'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',"select:not([disabled]):not([aria-hidden])","textarea:not([disabled]):not([aria-hidden])","button:not([disabled]):not([aria-hidden])","[contenteditable]",'[tabindex]:not([tabindex^="-"])'];document.addEventListener("click",(()=>{}));const{state:l,actions:c}=(0,n.store)("core/navigation",{state:{get roleAttribute(){return"overlay"===(0,n.getContext)().type&&l.isMenuOpen?"dialog":null},get ariaModal(){return"overlay"===(0,n.getContext)().type&&l.isMenuOpen?"true":null},get ariaLabel(){const e=(0,n.getContext)();return"overlay"===e.type&&l.isMenuOpen?e.ariaLabel:null},get isMenuOpen(){return Object.values(l.menuOpenedBy).filter(Boolean).length>0},get menuOpenedBy(){const e=(0,n.getContext)();return"overlay"===e.type?e.overlayOpenedBy:e.submenuOpenedBy}},actions:{openMenuOnHover(){const{type:e,overlayOpenedBy:t}=(0,n.getContext)();"submenu"===e&&0===Object.values(t||{}).filter(Boolean).length&&c.openMenu("hover")},closeMenuOnHover(){const{type:e,overlayOpenedBy:t}=(0,n.getContext)();"submenu"===e&&0===Object.values(t||{}).filter(Boolean).length&&c.closeMenu("hover")},openMenuOnClick(){const e=(0,n.getContext)(),{ref:t}=(0,n.getElement)();e.previousFocus=t,c.openMenu("click")},closeMenuOnClick(){c.closeMenu("click"),c.closeMenu("focus")},openMenuOnFocus(){c.openMenu("focus")},toggleMenuOnClick(){const e=(0,n.getContext)(),{ref:t}=(0,n.getElement)();window.document.activeElement!==t&&t.focus();const{menuOpenedBy:o}=l;o.click||o.focus?(c.closeMenu("click"),c.closeMenu("focus")):(e.previousFocus=t,c.openMenu("click"))},handleMenuKeydown(e){const{type:t,firstFocusableElement:o,lastFocusableElement:u}=(0,n.getContext)();if(l.menuOpenedBy.click){if("Escape"===e?.key)return c.closeMenu("click"),void c.closeMenu("focus");"overlay"===t&&"Tab"===e.key&&(e.shiftKey&&window.document.activeElement===o?(e.preventDefault(),u.focus()):e.shiftKey||window.document.activeElement!==u||(e.preventDefault(),o.focus()))}},handleMenuFocusout(e){const{modal:t,type:o}=(0,n.getContext)();(null===e.relatedTarget||!t?.contains(e.relatedTarget)&&e.target!==window.document.activeElement&&"submenu"===o)&&(c.closeMenu("click"),c.closeMenu("focus"))},openMenu(e="click"){const{type:t}=(0,n.getContext)();l.menuOpenedBy[e]=!0,"overlay"===t&&document.documentElement.classList.add("has-modal-open")},closeMenu(e="click"){const t=(0,n.getContext)();l.menuOpenedBy[e]=!1,l.isMenuOpen||(t.modal?.contains(window.document.activeElement)&&t.previousFocus?.focus(),t.modal=null,t.previousFocus=null,"overlay"===t.type&&document.documentElement.classList.remove("has-modal-open"))}},callbacks:{initMenu(){const e=(0,n.getContext)(),{ref:t}=(0,n.getElement)();if(l.isMenuOpen){const n=t.querySelectorAll(o);e.modal=t,e.firstFocusableElement=n[0],e.lastFocusableElement=n[n.length-1]}},focusFirstElement(){const{ref:e}=(0,n.getElement)();if(l.isMenuOpen){const t=e.querySelectorAll(o);t?.[0]?.focus()}}}},{lock:!0});
@@ -0,0 +1,135 @@
import * as __WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__ from "@wordpress/interactivity";
/******/ var __webpack_modules__ = ({
/***/ 438:
/***/ ((module) => {
module.exports = import("@wordpress/interactivity-router");;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.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/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (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 */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
;// CONCATENATED MODULE: external "@wordpress/interactivity"
var x = (y) => {
var x = {}; __webpack_require__.d(x, y); return x
}
var y = (x) => (() => (x))
const interactivity_namespaceObject = x({ ["getContext"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getContext), ["getElement"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getElement), ["store"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.store) });
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-library/build-module/query/view.js
/**
* WordPress dependencies
*/
const isValidLink = ref => ref && ref instanceof window.HTMLAnchorElement && ref.href && (!ref.target || ref.target === '_self') && ref.origin === window.location.origin;
const isValidEvent = event => event.button === 0 &&
// Left clicks only.
!event.metaKey &&
// Open in new tab (Mac).
!event.ctrlKey &&
// Open in new tab (Windows).
!event.altKey &&
// Download.
!event.shiftKey && !event.defaultPrevented;
(0,interactivity_namespaceObject.store)('core/query', {
actions: {
*navigate(event) {
const ctx = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
const queryRef = ref.closest('.wp-block-query[data-wp-router-region]');
if (isValidLink(ref) && isValidEvent(event)) {
event.preventDefault();
const {
actions
} = yield Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 438));
yield actions.navigate(ref.href);
ctx.url = ref.href;
// Focus the first anchor of the Query block.
const firstAnchor = `.wp-block-post-template a[href]`;
queryRef.querySelector(firstAnchor)?.focus();
}
},
*prefetch() {
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
if (isValidLink(ref)) {
const {
actions
} = yield Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 438));
yield actions.prefetch(ref.href);
}
}
},
callbacks: {
*prefetch() {
const {
url
} = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
if (url && isValidLink(ref)) {
const {
actions
} = yield Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 438));
yield actions.prefetch(ref.href);
}
}
}
}, {
lock: true
});
})();
@@ -0,0 +1 @@
import*as e from"@wordpress/interactivity";var t={438:e=>{e.exports=import("@wordpress/interactivity-router")}},r={};function o(e){var n=r[e];if(void 0!==n)return n.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,o),i.exports}o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const t=(e=>{var t={};return o.d(t,e),t})({getContext:()=>e.getContext,getElement:()=>e.getElement,store:()=>e.store}),r=e=>e&&e instanceof window.HTMLAnchorElement&&e.href&&(!e.target||"_self"===e.target)&&e.origin===window.location.origin;(0,t.store)("core/query",{actions:{*navigate(e){const n=(0,t.getContext)(),{ref:i}=(0,t.getElement)(),s=i.closest(".wp-block-query[data-wp-router-region]");if(r(i)&&(e=>!(0!==e.button||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey||e.defaultPrevented))(e)){e.preventDefault();const{actions:t}=yield Promise.resolve().then(o.bind(o,438));yield t.navigate(i.href),n.url=i.href;const r=".wp-block-post-template a[href]";s.querySelector(r)?.focus()}},*prefetch(){const{ref:e}=(0,t.getElement)();if(r(e)){const{actions:t}=yield Promise.resolve().then(o.bind(o,438));yield t.prefetch(e.href)}}},callbacks:{*prefetch(){const{url:e}=(0,t.getContext)(),{ref:n}=(0,t.getElement)();if(e&&r(n)){const{actions:e}=yield Promise.resolve().then(o.bind(o,438));yield e.prefetch(n.href)}}}},{lock:!0})})();
@@ -0,0 +1,112 @@
import * as __WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__ from "@wordpress/interactivity";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (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 */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
;// CONCATENATED MODULE: external "@wordpress/interactivity"
var x = (y) => {
var x = {}; __webpack_require__.d(x, y); return x
}
var y = (x) => (() => (x))
const interactivity_namespaceObject = x({ ["getContext"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getContext), ["getElement"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.getElement), ["store"]: () => (__WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__.store) });
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-library/build-module/search/view.js
/**
* WordPress dependencies
*/
const {
actions
} = (0,interactivity_namespaceObject.store)('core/search', {
state: {
get ariaLabel() {
const {
isSearchInputVisible,
ariaLabelCollapsed,
ariaLabelExpanded
} = (0,interactivity_namespaceObject.getContext)();
return isSearchInputVisible ? ariaLabelExpanded : ariaLabelCollapsed;
},
get ariaControls() {
const {
isSearchInputVisible,
inputId
} = (0,interactivity_namespaceObject.getContext)();
return isSearchInputVisible ? null : inputId;
},
get type() {
const {
isSearchInputVisible
} = (0,interactivity_namespaceObject.getContext)();
return isSearchInputVisible ? 'submit' : 'button';
},
get tabindex() {
const {
isSearchInputVisible
} = (0,interactivity_namespaceObject.getContext)();
return isSearchInputVisible ? '0' : '-1';
}
},
actions: {
openSearchInput(event) {
const ctx = (0,interactivity_namespaceObject.getContext)();
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
if (!ctx.isSearchInputVisible) {
event.preventDefault();
ctx.isSearchInputVisible = true;
ref.parentElement.querySelector('input').focus();
}
},
closeSearchInput() {
const ctx = (0,interactivity_namespaceObject.getContext)();
ctx.isSearchInputVisible = false;
},
handleSearchKeydown(event) {
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
// If Escape close the menu.
if (event?.key === 'Escape') {
actions.closeSearchInput();
ref.querySelector('button').focus();
}
},
handleSearchFocusout(event) {
const {
ref
} = (0,interactivity_namespaceObject.getElement)();
// If focus is outside search form, and in the document, close menu
// event.target === The element losing focus
// event.relatedTarget === The element receiving focus (if any)
// When focusout is outside the document,
// `window.document.activeElement` doesn't change.
if (!ref.contains(event.relatedTarget) && event.target !== window.document.activeElement) {
actions.closeSearchInput();
}
}
}
}, {
lock: true
});
@@ -0,0 +1 @@
import*as e from"@wordpress/interactivity";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const n=(e=>{var n={};return t.d(n,e),n})({getContext:()=>e.getContext,getElement:()=>e.getElement,store:()=>e.store}),{actions:r}=(0,n.store)("core/search",{state:{get ariaLabel(){const{isSearchInputVisible:e,ariaLabelCollapsed:t,ariaLabelExpanded:r}=(0,n.getContext)();return e?r:t},get ariaControls(){const{isSearchInputVisible:e,inputId:t}=(0,n.getContext)();return e?null:t},get type(){const{isSearchInputVisible:e}=(0,n.getContext)();return e?"submit":"button"},get tabindex(){const{isSearchInputVisible:e}=(0,n.getContext)();return e?"0":"-1"}},actions:{openSearchInput(e){const t=(0,n.getContext)(),{ref:r}=(0,n.getElement)();t.isSearchInputVisible||(e.preventDefault(),t.isSearchInputVisible=!0,r.parentElement.querySelector("input").focus())},closeSearchInput(){(0,n.getContext)().isSearchInputVisible=!1},handleSearchKeydown(e){const{ref:t}=(0,n.getElement)();"Escape"===e?.key&&(r.closeSearchInput(),t.querySelector("button").focus())},handleSearchFocusout(e){const{ref:t}=(0,n.getElement)();t.contains(e.relatedTarget)||e.target===window.document.activeElement||r.closeSearchInput()}}},{lock:!0});
@@ -1,6 +1,38 @@
import * as __WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__ from "@wordpress/interactivity";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/ var __webpack_modules__ = ({
/***/ 317:
/***/ ((module) => {
module.exports = import("@wordpress/a11y");;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.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/define property getters */
@@ -22,6 +54,8 @@ import * as __WEBPACK_EXTERNAL_MODULE__wordpress_interactivity_8e89b257__ from "
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
@@ -52,8 +86,8 @@ const {
initialVdom,
toVdom,
render,
parseInitialData,
populateInitialData,
parseServerData,
populateServerData,
batch
} = (0,interactivity_namespaceObject.privateApis)('I acknowledge that using private APIs means my theme or plugin will inevitably break in the next version of WordPress.');
// Check if the navigation mode is full page or region based.
@@ -107,7 +141,7 @@ const regionsToVdom = async (dom, {
});
}
const title = dom.querySelector('title')?.innerText;
const initialData = parseInitialData(dom);
const initialData = parseServerData(dom);
return {
regions,
head,
@@ -121,7 +155,7 @@ const renderRegions = page => {
batch(() => {
if (false) {}
if (navigationMode === 'regionBased') {
populateInitialData(page.initialData);
populateServerData(page.initialData);
const attrName = `data-${directivePrefix}-router-region`;
document.querySelectorAll(`[${attrName}]`).forEach(region => {
const id = region.getAttribute(attrName);
@@ -188,6 +222,11 @@ const isValidEvent = event => event && event.button === 0 &&
// Variable to store the current navigation.
let navigatingTo = '';
let hasLoadedNavigationTextsData = false;
const navigationTexts = {
loading: 'Loading page, please wait.',
loaded: 'Page Loaded.'
};
const {
state,
actions
@@ -196,12 +235,7 @@ const {
url: window.location.href,
navigation: {
hasStarted: false,
hasFinished: false,
texts: {
loading: '',
loaded: ''
},
message: ''
hasFinished: false
}
},
actions: {
@@ -256,7 +290,7 @@ const {
navigation.hasFinished = false;
}
if (screenReaderAnnouncement) {
navigation.message = navigation.texts.loading;
a11ySpeak('loading');
}
}, 400);
const page = yield Promise.race([pages.get(pagePath), timeoutPromise]);
@@ -284,10 +318,7 @@ const {
navigation.hasFinished = true;
}
if (screenReaderAnnouncement) {
// Announce that the page has been loaded. If the message is the
// same, we use a no-break space similar to the @wordpress/a11y
// package: https://github.com/WordPress/gutenberg/blob/c395242b8e6ee20f8b06c199e4fc2920d7018af1/packages/a11y/src/filter-message.js#L20-L26
navigation.message = navigation.texts.loaded + (navigation.message === navigation.texts.loaded ? '\u00A0' : '');
a11ySpeak('loaded');
}
// Scroll to the anchor if exits in the link.
@@ -329,9 +360,57 @@ const {
}
});
/**
* Announces a message to screen readers.
*
* This is a wrapper around the `@wordpress/a11y` package's `speak` function. It handles importing
* the package on demand and should be used instead of calling `ally.speak` direacly.
*
* @param messageKey The message to be announced by assistive technologies.
*/
function a11ySpeak(messageKey) {
if (!hasLoadedNavigationTextsData) {
hasLoadedNavigationTextsData = true;
const content = document.getElementById('wp-script-module-data-@wordpress/interactivity-router')?.textContent;
if (content) {
try {
const parsed = JSON.parse(content);
if (typeof parsed?.i18n?.loading === 'string') {
navigationTexts.loading = parsed.i18n.loading;
}
if (typeof parsed?.i18n?.loaded === 'string') {
navigationTexts.loaded = parsed.i18n.loaded;
}
} catch {}
} else {
// Fallback to localized strings from Interactivity API state.
// @todo This block is for Core < 6.7.0. Remove when support is dropped.
// @ts-expect-error
if (state.navigation.texts?.loading) {
// @ts-expect-error
navigationTexts.loading = state.navigation.texts.loading;
}
// @ts-expect-error
if (state.navigation.texts?.loaded) {
// @ts-expect-error
navigationTexts.loaded = state.navigation.texts.loaded;
}
}
}
const message = navigationTexts[messageKey];
Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 317)).then(({
speak
}) => speak(message),
// Ignore failures to load the a11y module.
() => {});
}
// Add click and prefetch to all links.
if (false) {}
})();
var __webpack_exports__actions = __webpack_exports__.o;
var __webpack_exports__state = __webpack_exports__.w;
export { __webpack_exports__actions as actions, __webpack_exports__state as state };
@@ -0,0 +1 @@
import*as e from"@wordpress/interactivity";var t={317:e=>{e.exports=import("@wordpress/a11y")}},o={};function i(e){var n=o[e];if(void 0!==n)return n.exports;var a=o[e]={exports:{}};return t[e](a,a.exports,i),a.exports}i.d=(e,t)=>{for(var o in t)i.o(t,o)&&!i.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var n={};(()=>{i.d(n,{o:()=>P,w:()=>S});const t=(e=>{var t={};return i.d(t,e),t})({getConfig:()=>e.getConfig,privateApis:()=>e.privateApis,store:()=>e.store});var o;const{directivePrefix:a,getRegionRootFragment:r,initialVdom:s,toVdom:d,render:l,parseServerData:c,populateServerData:g,batch:p}=(0,t.privateApis)("I acknowledge that using private APIs means my theme or plugin will inevitably break in the next version of WordPress."),u=null!==(o=(0,t.getConfig)("core/router").navigationMode)&&void 0!==o?o:"regionBased",w=new Map,h=(new Map,e=>{const t=new URL(e,window.location.href);return t.pathname+t.search}),f=async(e,{vdom:t}={})=>{const o={body:void 0};if("regionBased"===u){const i=`data-${a}-router-region`;e.querySelectorAll(`[${i}]`).forEach((e=>{const n=e.getAttribute(i);o[n]=t?.has(e)?t.get(e):d(e)}))}const i=e.querySelector("title")?.innerText,n=c(e);return{regions:o,head:undefined,title:i,initialData:n}},v=e=>{p((()=>{if("regionBased"===u){g(e.initialData);const t=`data-${a}-router-region`;document.querySelectorAll(`[${t}]`).forEach((o=>{const i=o.getAttribute(t),n=r(o);l(e.regions[i],n)}))}e.title&&(document.title=e.title)}))},m=e=>(window.location.assign(e),new Promise((()=>{})));window.addEventListener("popstate",(async()=>{const e=h(window.location.href),t=w.has(e)&&await w.get(e);t?(v(t),S.url=window.location.href):window.location.reload()})),w.set(h(window.location.href),Promise.resolve(f(document,{vdom:s})));let y="",x=!1;const b={loading:"Loading page, please wait.",loaded:"Page Loaded."},{state:S,actions:P}=(0,t.store)("core/router",{state:{url:window.location.href,navigation:{hasStarted:!1,hasFinished:!1}},actions:{*navigate(e,o={}){const{clientNavigationDisabled:i}=(0,t.getConfig)();i&&(yield m(e));const n=h(e),{navigation:a}=S,{loadingAnimation:r=!0,screenReaderAnnouncement:s=!0,timeout:d=1e4}=o;y=e,P.prefetch(n,o);const l=new Promise((e=>setTimeout(e,d))),c=setTimeout((()=>{y===e&&(r&&(a.hasStarted=!0,a.hasFinished=!1),s&&A("loading"))}),400),g=yield Promise.race([w.get(n),l]);if(clearTimeout(c),y===e)if(g&&!g.initialData?.config?.["core/router"]?.clientNavigationDisabled){yield v(g),window.history[o.replace?"replaceState":"pushState"]({},"",e),S.url=e,r&&(a.hasStarted=!1,a.hasFinished=!0),s&&A("loaded");const{hash:t}=new URL(e,window.location.href);t&&document.querySelector(t)?.scrollIntoView()}else yield m(e)},prefetch(e,o={}){const{clientNavigationDisabled:i}=(0,t.getConfig)();if(i)return;const n=h(e);!o.force&&w.has(n)||w.set(n,(async(e,{html:t})=>{try{if(!t){const o=await window.fetch(e);if(200!==o.status)return!1;t=await o.text()}const o=(new window.DOMParser).parseFromString(t,"text/html");return f(o)}catch(e){return!1}})(n,{html:o.html}))}}});function A(e){if(!x){x=!0;const e=document.getElementById("wp-script-module-data-@wordpress/interactivity-router")?.textContent;if(e)try{const t=JSON.parse(e);"string"==typeof t?.i18n?.loading&&(b.loading=t.i18n.loading),"string"==typeof t?.i18n?.loaded&&(b.loaded=t.i18n.loaded)}catch{}else S.navigation.texts?.loading&&(b.loading=S.navigation.texts.loading),S.navigation.texts?.loaded&&(b.loaded=S.navigation.texts.loaded)}const t=b[e];Promise.resolve().then(i.bind(i,317)).then((({speak:e})=>e(t)),(()=>{}))}})();var a=n.o,r=n.w;export{a as actions,r as state};
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 one or more lines are too long
+56 -32
View File
@@ -40,7 +40,8 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
compileCSS: () => (/* binding */ compileCSS),
getCSSRules: () => (/* binding */ getCSSRules)
getCSSRules: () => (/* binding */ getCSSRules),
getCSSValueFromRawStyle: () => (/* reexport */ getCSSValueFromRawStyle)
});
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.mjs
@@ -58,7 +59,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
@@ -169,8 +170,8 @@ function __awaiter(thisArg, _arguments, P, generator) {
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
@@ -274,8 +275,9 @@ function __await(v) {
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
@@ -341,16 +343,18 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
@@ -369,17 +373,22 @@ function __disposeResources(env) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
while (r = env.stack.pop()) {
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
@@ -560,7 +569,7 @@ function generateRule(style, options, path, ruleKey) {
return styleValue ? [{
selector: options?.selector,
key: ruleKey,
value: getCSSVarFromStyleValue(styleValue)
value: getCSSValueFromRawStyle(styleValue)
}] : [];
}
@@ -589,7 +598,7 @@ function generateBoxRules(style, options, path, ruleKeys, individualProperties =
});
} else {
const sideRules = individualProperties.reduce((acc, side) => {
const value = getCSSVarFromStyleValue(getStyleValueByPath(boxStyle, [side]));
const value = getCSSValueFromRawStyle(getStyleValueByPath(boxStyle, [side]));
if (value) {
acc.push({
selector: options?.selector,
@@ -605,13 +614,21 @@ function generateBoxRules(style, options, path, ruleKeys, individualProperties =
}
/**
* Returns a CSS var value from incoming style value following the pattern `var:description|context|slug`.
* Returns a WordPress CSS custom var value from incoming style preset value,
* if one is detected.
*
* @param styleValue A raw style value.
* The preset value is a string and follows the pattern `var:description|context|slug`.
*
* @return string A CSS var value.
* Example:
*
* `getCSSValueFromRawStyle( 'var:preset|color|heavenlyBlue' )` // returns 'var(--wp--preset--color--heavenly-blue)'
*
* @param styleValue A string representing a raw CSS value. Non-strings won't be processed.
*
* @return A CSS custom var value if the incoming style value is a preset value.
*/
function getCSSVarFromStyleValue(styleValue) {
function getCSSValueFromRawStyle(styleValue) {
if (typeof styleValue === 'string' && styleValue.startsWith(VARIABLE_REFERENCE_PREFIX)) {
const variable = styleValue.slice(VARIABLE_REFERENCE_PREFIX.length).split(VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE).map(presetVariable => paramCase(presetVariable, {
splitRegexp: [/([a-z0-9])([A-Z])/g,
@@ -826,6 +843,12 @@ const backgroundImage = {
name: 'backgroundImage',
generate: (style, options) => {
const _backgroundImage = style?.background?.backgroundImage;
/*
* The background image can be a string or an object.
* If the background image is a string, it could already contain a url() function,
* or have a linear-gradient value.
*/
if (typeof _backgroundImage === 'object' && _backgroundImage?.url) {
return [{
selector: options.selector,
@@ -834,15 +857,7 @@ const backgroundImage = {
value: `url( '${encodeURI(safeDecodeURI(_backgroundImage.url))}' )`
}];
}
/*
* If the background image is a string, it could already contain a url() function,
* or have a linear-gradient value.
*/
if (typeof _backgroundImage === 'string') {
return generateRule(style, options, ['background', 'backgroundImage'], 'backgroundImage');
}
return [];
return generateRule(style, options, ['background', 'backgroundImage'], 'backgroundImage');
}
};
const backgroundPosition = {
@@ -863,7 +878,13 @@ const backgroundSize = {
return generateRule(style, options, ['background', 'backgroundSize'], 'backgroundSize');
}
};
/* harmony default export */ const styles_background = ([backgroundImage, backgroundPosition, backgroundRepeat, backgroundSize]);
const backgroundAttachment = {
name: 'backgroundAttachment',
generate: (style, options) => {
return generateRule(style, options, ['background', 'backgroundAttachment'], 'backgroundAttachment');
}
};
/* harmony default export */ const styles_background = ([backgroundImage, backgroundPosition, backgroundRepeat, backgroundSize, backgroundAttachment]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/shadow/index.js
/**
@@ -1108,6 +1129,9 @@ function getCSSRules(style, options = {}) {
return rules;
}
// Export style utils.
(window.wp = window.wp || {}).styleEngine = __webpack_exports__;
/******/ })()
;
File diff suppressed because one or more lines are too long
+25 -45
View File
@@ -35,45 +35,22 @@ class TokenList {
/**
* Constructs a new instance of TokenList.
*
* @param {string} initialValue Initial value to assign.
* @param initialValue Initial value to assign.
*/
constructor(initialValue = '') {
this._currentValue = '';
this._valueAsArray = [];
this.value = initialValue;
// Disable reason: These are type hints on the class.
/* eslint-disable no-unused-expressions */
/** @type {string} */
this._currentValue;
/** @type {string[]} */
this._valueAsArray;
/* eslint-enable no-unused-expressions */
}
/**
* @param {Parameters<Array<string>['entries']>} args
*/
entries(...args) {
return this._valueAsArray.entries(...args);
}
/**
* @param {Parameters<Array<string>['forEach']>} args
*/
forEach(...args) {
return this._valueAsArray.forEach(...args);
}
/**
* @param {Parameters<Array<string>['keys']>} args
*/
keys(...args) {
return this._valueAsArray.keys(...args);
}
/**
* @param {Parameters<Array<string>['values']>} args
*/
values(...args) {
return this._valueAsArray.values(...args);
}
@@ -83,7 +60,7 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-value
*
* @return {string} Token set as string.
* @return Token set as string.
*/
get value() {
return this._currentValue;
@@ -94,7 +71,7 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-value
*
* @param {string} value New token set as string.
* @param value New token set as string.
*/
set value(value) {
value = String(value);
@@ -107,7 +84,7 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-length
*
* @return {number} Number of tokens.
* @return Number of tokens.
*/
get length() {
return this._valueAsArray.length;
@@ -119,7 +96,7 @@ class TokenList {
* @see https://dom.spec.whatwg.org/#DOMTokenList-stringification-behavior
* @see https://www.ecma-international.org/ecma-262/9.0/index.html#sec-tostring
*
* @return {string} Token set as string.
* @return Token set as string.
*/
toString() {
return this.value;
@@ -130,7 +107,7 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#domtokenlist
*
* @return {IterableIterator<string>} TokenList iterator.
* @return TokenList iterator.
*/
*[Symbol.iterator]() {
return yield* this._valueAsArray;
@@ -141,9 +118,9 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-item
*
* @param {number} index Index at which to return token.
* @param index Index at which to return token.
*
* @return {string|undefined} Token at index.
* @return Token at index.
*/
item(index) {
return this._valueAsArray[index];
@@ -154,9 +131,9 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-contains
*
* @param {string} item Token to test.
* @param item Token to test.
*
* @return {boolean} Whether token is present.
* @return Whether token is present.
*/
contains(item) {
return this._valueAsArray.indexOf(item) !== -1;
@@ -167,7 +144,7 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-add
*
* @param {...string} items Items to add.
* @param items Items to add.
*/
add(...items) {
this.value += ' ' + items.join(' ');
@@ -178,7 +155,7 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-remove
*
* @param {...string} items Items to remove.
* @param items Items to remove.
*/
remove(...items) {
this.value = this._valueAsArray.filter(val => !items.includes(val)).join(' ');
@@ -192,10 +169,10 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
*
* @param {string} token Token to toggle.
* @param {boolean} [force] Presence to force.
* @param token Token to toggle.
* @param [force] Presence to force.
*
* @return {boolean} Whether token is present after toggle.
* @return Whether token is present after toggle.
*/
toggle(token, force) {
if (undefined === force) {
@@ -215,10 +192,10 @@ class TokenList {
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-replace
*
* @param {string} token Token to replace with `newToken`.
* @param {string} newToken Token to use in place of `token`.
* @param token Token to replace with `newToken`.
* @param newToken Token to use in place of `token`.
*
* @return {boolean} Whether replacement occurred.
* @return Whether replacement occurred.
*/
replace(token, newToken) {
if (!this.contains(token)) {
@@ -229,19 +206,22 @@ class TokenList {
return true;
}
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
* Returns true if `token` is in the associated attributes supported
* tokens. Returns false otherwise.
*
* Always returns `true` in this implementation.
*
* @param _token
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-supports
*
* @return {boolean} Whether token is supported.
* @return Whether token is supported.
*/
supports() {
supports(_token) {
return true;
}
/* eslint-enable @typescript-eslint/no-unused-vars */
}
(window.wp = window.wp || {}).tokenList = __webpack_exports__["default"];
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
(()=>{"use strict";var e={d:(r,t)=>{for(var s in t)e.o(t,s)&&!e.o(r,s)&&Object.defineProperty(r,s,{enumerable:!0,get:t[s]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)},r={};e.d(r,{default:()=>t});class t{constructor(e=""){this.value=e,this._currentValue,this._valueAsArray}entries(...e){return this._valueAsArray.entries(...e)}forEach(...e){return this._valueAsArray.forEach(...e)}keys(...e){return this._valueAsArray.keys(...e)}values(...e){return this._valueAsArray.values(...e)}get value(){return this._currentValue}set value(e){e=String(e),this._valueAsArray=[...new Set(e.split(/\s+/g).filter(Boolean))],this._currentValue=this._valueAsArray.join(" ")}get length(){return this._valueAsArray.length}toString(){return this.value}*[Symbol.iterator](){return yield*this._valueAsArray}item(e){return this._valueAsArray[e]}contains(e){return-1!==this._valueAsArray.indexOf(e)}add(...e){this.value+=" "+e.join(" ")}remove(...e){this.value=this._valueAsArray.filter((r=>!e.includes(r))).join(" ")}toggle(e,r){return void 0===r&&(r=!this.contains(e)),r?this.add(e):this.remove(e),r}replace(e,r){return!!this.contains(e)&&(this.remove(e),this.add(r),!0)}supports(){return!0}}(window.wp=window.wp||{}).tokenList=r.default})();
(()=>{"use strict";var e={d:(r,t)=>{for(var s in t)e.o(t,s)&&!e.o(r,s)&&Object.defineProperty(r,s,{enumerable:!0,get:t[s]})},o:(e,r)=>Object.prototype.hasOwnProperty.call(e,r)},r={};e.d(r,{default:()=>t});class t{constructor(e=""){this._currentValue="",this._valueAsArray=[],this.value=e}entries(...e){return this._valueAsArray.entries(...e)}forEach(...e){return this._valueAsArray.forEach(...e)}keys(...e){return this._valueAsArray.keys(...e)}values(...e){return this._valueAsArray.values(...e)}get value(){return this._currentValue}set value(e){e=String(e),this._valueAsArray=[...new Set(e.split(/\s+/g).filter(Boolean))],this._currentValue=this._valueAsArray.join(" ")}get length(){return this._valueAsArray.length}toString(){return this.value}*[Symbol.iterator](){return yield*this._valueAsArray}item(e){return this._valueAsArray[e]}contains(e){return-1!==this._valueAsArray.indexOf(e)}add(...e){this.value+=" "+e.join(" ")}remove(...e){this.value=this._valueAsArray.filter((r=>!e.includes(r))).join(" ")}toggle(e,r){return void 0===r&&(r=!this.contains(e)),r?this.add(e):this.remove(e),r}replace(e,r){return!!this.contains(e)&&(this.remove(e),this.add(r),!0)}supports(e){return!0}}(window.wp=window.wp||{}).tokenList=r.default})();
+31 -1
View File
@@ -581,6 +581,7 @@ __webpack_require__.d(__webpack_exports__, {
getQueryString: () => (/* reexport */ getQueryString),
hasQueryArg: () => (/* reexport */ hasQueryArg),
isEmail: () => (/* reexport */ isEmail),
isPhoneNumber: () => (/* reexport */ isPhoneNumber),
isURL: () => (/* reexport */ isURL),
isValidAuthority: () => (/* reexport */ isValidAuthority),
isValidFragment: () => (/* reexport */ isValidFragment),
@@ -596,6 +597,7 @@ __webpack_require__.d(__webpack_exports__, {
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-url.js
/* wp:polyfill */
/**
* Determines whether the given string looks like a URL.
*
@@ -641,6 +643,27 @@ function isEmail(email) {
return EMAIL_REGEXP.test(email);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-phone-number.js
const PHONE_REGEXP = /^(tel:)?(\+)?\d{6,15}$/;
/**
* Determines whether the given string looks like a phone number.
*
* @param {string} phoneNumber The string to scrutinize.
*
* @example
* ```js
* const isPhoneNumber = isPhoneNumber('+1 (555) 123-4567'); // true
* ```
*
* @return {boolean} Whether or not it looks like a phone number.
*/
function isPhoneNumber(phoneNumber) {
// Remove any seperator from phone number.
phoneNumber = phoneNumber.replace(/[-.() ]/g, '');
return PHONE_REGEXP.test(phoneNumber);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-protocol.js
/**
* Returns the protocol part of the URL.
@@ -768,6 +791,7 @@ function isValidPath(path) {
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-query-string.js
/* wp:polyfill */
/**
* Returns the query string part of the URL.
*
@@ -1243,8 +1267,12 @@ function safeDecodeURI(uri) {
* @return {string} Displayed URL.
*/
function filterURLForDisplay(url, maxLength = null) {
if (!url) {
return '';
}
// Remove protocol and www prefixes.
let filteredURL = url.replace(/^(?:https?:)\/\/(?:www\.)?/, '');
let filteredURL = url.replace(/^[a-z\-.\+]+[0-9]*:(\/\/)?/i, '').replace(/^www\./i, '');
// Ends with / and only has that single slash, strip it.
if (filteredURL.match(/^[^\/]+\/$/)) {
@@ -1315,6 +1343,7 @@ function cleanForSlug(string) {
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-filename.js
/* wp:polyfill */
/**
* Returns the filename part of the URL.
*
@@ -1437,6 +1466,7 @@ function prependHTTPS(url) {
})();
+1 -1
View File
File diff suppressed because one or more lines are too long
+368 -365
View File
@@ -1,5 +1,5 @@
//! moment.js
//! version : 2.29.4
//! version : 2.30.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
@@ -155,24 +155,25 @@
}
function isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m),
parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
}),
isNowValid =
!isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidEra &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.weekdayMismatch &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated &&
(!flags.meridiem || (flags.meridiem && parsedParts));
var flags = null,
parsedParts = false,
isNowValid = m._d && !isNaN(m._d.getTime());
if (isNowValid) {
flags = getParsingFlags(m);
parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
});
isNowValid =
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidEra &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.weekdayMismatch &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated &&
(!flags.meridiem || (flags.meridiem && parsedParts));
if (m._strict) {
isNowValid =
isNowValid &&
@@ -180,12 +181,11 @@
flags.unusedTokens.length === 0 &&
flags.bigHour === undefined;
}
if (Object.isFrozen == null || !Object.isFrozen(m)) {
m._isValid = isNowValid;
} else {
return isNowValid;
}
}
if (Object.isFrozen == null || !Object.isFrozen(m)) {
m._isValid = isNowValid;
} else {
return isNowValid;
}
return m._isValid;
}
@@ -630,12 +630,56 @@
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}
var aliases = {};
function addUnitAlias(unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
var aliases = {
D: 'date',
dates: 'date',
date: 'date',
d: 'day',
days: 'day',
day: 'day',
e: 'weekday',
weekdays: 'weekday',
weekday: 'weekday',
E: 'isoWeekday',
isoweekdays: 'isoWeekday',
isoweekday: 'isoWeekday',
DDD: 'dayOfYear',
dayofyears: 'dayOfYear',
dayofyear: 'dayOfYear',
h: 'hour',
hours: 'hour',
hour: 'hour',
ms: 'millisecond',
milliseconds: 'millisecond',
millisecond: 'millisecond',
m: 'minute',
minutes: 'minute',
minute: 'minute',
M: 'month',
months: 'month',
month: 'month',
Q: 'quarter',
quarters: 'quarter',
quarter: 'quarter',
s: 'second',
seconds: 'second',
second: 'second',
gg: 'weekYear',
weekyears: 'weekYear',
weekyear: 'weekYear',
GG: 'isoWeekYear',
isoweekyears: 'isoWeekYear',
isoweekyear: 'isoWeekYear',
w: 'week',
weeks: 'week',
week: 'week',
W: 'isoWeek',
isoweeks: 'isoWeek',
isoweek: 'isoWeek',
y: 'year',
years: 'year',
year: 'year',
};
function normalizeUnits(units) {
return typeof units === 'string'
@@ -660,11 +704,24 @@
return normalizedInput;
}
var priorities = {};
function addUnitPriority(unit, priority) {
priorities[unit] = priority;
}
var priorities = {
date: 9,
day: 11,
weekday: 11,
isoWeekday: 11,
dayOfYear: 4,
hour: 13,
millisecond: 16,
minute: 14,
month: 8,
quarter: 7,
second: 15,
weekYear: 1,
isoWeekYear: 1,
week: 5,
isoWeek: 5,
year: 1,
};
function getPrioritizedUnits(unitsObj) {
var units = [],
@@ -680,96 +737,6 @@
return units;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function absFloor(number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
function makeGetSet(unit, keepTime) {
return function (value) {
if (value != null) {
set$1(this, unit, value);
hooks.updateOffset(this, keepTime);
return this;
} else {
return get(this, unit);
}
};
}
function get(mom, unit) {
return mom.isValid()
? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
: NaN;
}
function set$1(mom, unit, value) {
if (mom.isValid() && !isNaN(value)) {
if (
unit === 'FullYear' &&
isLeapYear(mom.year()) &&
mom.month() === 1 &&
mom.date() === 29
) {
value = toInt(value);
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
value,
mom.month(),
daysInMonth(value, mom.month())
);
} else {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
}
// MOMENTS
function stringGet(units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet(units, value) {
if (typeof units === 'object') {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units),
i,
prioritizedLen = prioritized.length;
for (i = 0; i < prioritizedLen; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
var match1 = /\d/, // 0 - 9
match2 = /\d\d/, // 00 - 99
match3 = /\d{3}/, // 000 - 999
@@ -790,6 +757,8 @@
// includes scottish gaelic two word and hyphenated months
matchWord =
/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
match1to2NoLeadingZero = /^[1-9]\d?/, // 1-99
match1to2HasZero = /^([1-9]\d|\d)/, // 0-99
regexes;
regexes = {};
@@ -828,6 +797,26 @@
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
function absFloor(number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
var tokens = {};
function addParseToken(token, callback) {
@@ -861,6 +850,10 @@
}
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
var YEAR = 0,
MONTH = 1,
DATE = 2,
@@ -871,6 +864,173 @@
WEEK = 7,
WEEKDAY = 8;
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : '+' + y;
});
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
// PARSING
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] =
input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// HOOKS
hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', true);
function getIsLeapYear() {
return isLeapYear(this.year());
}
function makeGetSet(unit, keepTime) {
return function (value) {
if (value != null) {
set$1(this, unit, value);
hooks.updateOffset(this, keepTime);
return this;
} else {
return get(this, unit);
}
};
}
function get(mom, unit) {
if (!mom.isValid()) {
return NaN;
}
var d = mom._d,
isUTC = mom._isUTC;
switch (unit) {
case 'Milliseconds':
return isUTC ? d.getUTCMilliseconds() : d.getMilliseconds();
case 'Seconds':
return isUTC ? d.getUTCSeconds() : d.getSeconds();
case 'Minutes':
return isUTC ? d.getUTCMinutes() : d.getMinutes();
case 'Hours':
return isUTC ? d.getUTCHours() : d.getHours();
case 'Date':
return isUTC ? d.getUTCDate() : d.getDate();
case 'Day':
return isUTC ? d.getUTCDay() : d.getDay();
case 'Month':
return isUTC ? d.getUTCMonth() : d.getMonth();
case 'FullYear':
return isUTC ? d.getUTCFullYear() : d.getFullYear();
default:
return NaN; // Just in case
}
}
function set$1(mom, unit, value) {
var d, isUTC, year, month, date;
if (!mom.isValid() || isNaN(value)) {
return;
}
d = mom._d;
isUTC = mom._isUTC;
switch (unit) {
case 'Milliseconds':
return void (isUTC
? d.setUTCMilliseconds(value)
: d.setMilliseconds(value));
case 'Seconds':
return void (isUTC ? d.setUTCSeconds(value) : d.setSeconds(value));
case 'Minutes':
return void (isUTC ? d.setUTCMinutes(value) : d.setMinutes(value));
case 'Hours':
return void (isUTC ? d.setUTCHours(value) : d.setHours(value));
case 'Date':
return void (isUTC ? d.setUTCDate(value) : d.setDate(value));
// case 'Day': // Not real
// return void (isUTC ? d.setUTCDay(value) : d.setDay(value));
// case 'Month': // Not used because we need to pass two variables
// return void (isUTC ? d.setUTCMonth(value) : d.setMonth(value));
case 'FullYear':
break; // See below ...
default:
return; // Just in case
}
year = value;
month = mom.month();
date = mom.date();
date = date === 29 && month === 1 && !isLeapYear(year) ? 28 : date;
void (isUTC
? d.setUTCFullYear(year, month, date)
: d.setFullYear(year, month, date));
}
// MOMENTS
function stringGet(units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet(units, value) {
if (typeof units === 'object') {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units),
i,
prioritizedLen = prioritized.length;
for (i = 0; i < prioritizedLen; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
function mod(n, x) {
return ((n % x) + x) % x;
}
@@ -919,17 +1079,9 @@
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias('month', 'M');
// PRIORITY
addUnitPriority('month', 8);
// PARSING
addRegexToken('M', match1to2);
addRegexToken('M', match1to2, match1to2NoLeadingZero);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
@@ -1095,8 +1247,6 @@
// MOMENTS
function setMonth(mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
@@ -1114,8 +1264,13 @@
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
var month = value,
date = mom.date();
date = date < 29 ? date : Math.min(date, daysInMonth(mom.year(), month));
void (mom._isUTC
? mom._d.setUTCMonth(month, date)
: mom._d.setMonth(month, date));
return mom;
}
@@ -1182,27 +1337,24 @@
longPieces = [],
mixedPieces = [],
i,
mom;
mom,
shortP,
longP;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ''));
longPieces.push(this.months(mom, ''));
mixedPieces.push(this.months(mom, ''));
mixedPieces.push(this.monthsShort(mom, ''));
shortP = regexEscape(this.monthsShort(mom, ''));
longP = regexEscape(this.months(mom, ''));
shortPieces.push(shortP);
longPieces.push(longP);
mixedPieces.push(longP);
mixedPieces.push(shortP);
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._monthsShortRegex = this._monthsRegex;
@@ -1216,69 +1368,6 @@
);
}
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : '+' + y;
});
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
// ALIASES
addUnitAlias('year', 'y');
// PRIORITIES
addUnitPriority('year', 1);
// PARSING
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] =
input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// HOOKS
hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', true);
function getIsLeapYear() {
return isLeapYear(this.year());
}
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
@@ -1384,21 +1473,11 @@
addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
// ALIASES
addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');
// PRIORITIES
addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);
// PARSING
addRegexToken('w', match1to2);
addRegexToken('w', match1to2, match1to2NoLeadingZero);
addRegexToken('ww', match1to2, match2);
addRegexToken('W', match1to2);
addRegexToken('W', match1to2, match1to2NoLeadingZero);
addRegexToken('WW', match1to2, match2);
addWeekParseToken(
@@ -1460,17 +1539,6 @@
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
// ALIASES
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);
// PARSING
addRegexToken('d', match1to2);
@@ -1550,24 +1618,24 @@
return m === true
? shiftWeekdays(weekdays, this._week.dow)
: m
? weekdays[m.day()]
: weekdays;
? weekdays[m.day()]
: weekdays;
}
function localeWeekdaysShort(m) {
return m === true
? shiftWeekdays(this._weekdaysShort, this._week.dow)
: m
? this._weekdaysShort[m.day()]
: this._weekdaysShort;
? this._weekdaysShort[m.day()]
: this._weekdaysShort;
}
function localeWeekdaysMin(m) {
return m === true
? shiftWeekdays(this._weekdaysMin, this._week.dow)
: m
? this._weekdaysMin[m.day()]
: this._weekdaysMin;
? this._weekdaysMin[m.day()]
: this._weekdaysMin;
}
function handleStrictParse$1(weekdayName, format, strict) {
@@ -1716,7 +1784,8 @@
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
var day = get(this, 'Day');
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
@@ -1915,13 +1984,6 @@
meridiem('a', true);
meridiem('A', false);
// ALIASES
addUnitAlias('hour', 'h');
// PRIORITY
addUnitPriority('hour', 13);
// PARSING
function matchMeridiem(isStrict, locale) {
@@ -1930,9 +1992,9 @@
addRegexToken('a', matchMeridiem);
addRegexToken('A', matchMeridiem);
addRegexToken('H', match1to2);
addRegexToken('h', match1to2);
addRegexToken('k', match1to2);
addRegexToken('H', match1to2, match1to2HasZero);
addRegexToken('h', match1to2, match1to2NoLeadingZero);
addRegexToken('k', match1to2, match1to2NoLeadingZero);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);
@@ -2082,7 +2144,8 @@
function isLocaleNameSane(name) {
// Prevent names that look like filesystem paths, i.e contain '/' or '\'
return name.match('^[^/\\\\]*$') != null;
// Ensure name is available and function returns boolean
return !!(name && name.match('^[^/\\\\]*$'));
}
function loadLocale(name) {
@@ -2274,21 +2337,21 @@
a[MONTH] < 0 || a[MONTH] > 11
? MONTH
: a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
? DATE
: a[HOUR] < 0 ||
a[HOUR] > 24 ||
(a[HOUR] === 24 &&
(a[MINUTE] !== 0 ||
a[SECOND] !== 0 ||
a[MILLISECOND] !== 0))
? HOUR
: a[MINUTE] < 0 || a[MINUTE] > 59
? MINUTE
: a[SECOND] < 0 || a[SECOND] > 59
? SECOND
: a[MILLISECOND] < 0 || a[MILLISECOND] > 999
? MILLISECOND
: -1;
? DATE
: a[HOUR] < 0 ||
a[HOUR] > 24 ||
(a[HOUR] === 24 &&
(a[MINUTE] !== 0 ||
a[SECOND] !== 0 ||
a[MILLISECOND] !== 0))
? HOUR
: a[MINUTE] < 0 || a[MINUTE] > 59
? MINUTE
: a[SECOND] < 0 || a[SECOND] > 59
? SECOND
: a[MILLISECOND] < 0 || a[MILLISECOND] > 999
? MILLISECOND
: -1;
if (
getParsingFlags(m)._overflowDayOfYear &&
@@ -3729,16 +3792,16 @@
return diff < -6
? 'sameElse'
: diff < -1
? 'lastWeek'
: diff < 0
? 'lastDay'
: diff < 1
? 'sameDay'
: diff < 2
? 'nextDay'
: diff < 7
? 'nextWeek'
: 'sameElse';
? 'lastWeek'
: diff < 0
? 'lastDay'
: diff < 1
? 'sameDay'
: diff < 2
? 'nextDay'
: diff < 7
? 'nextWeek'
: 'sameElse';
}
function calendar$1(time, formats) {
@@ -4546,16 +4609,22 @@
mixedPieces = [],
i,
l,
erasName,
erasAbbr,
erasNarrow,
eras = this.eras();
for (i = 0, l = eras.length; i < l; ++i) {
namePieces.push(regexEscape(eras[i].name));
abbrPieces.push(regexEscape(eras[i].abbr));
narrowPieces.push(regexEscape(eras[i].narrow));
erasName = regexEscape(eras[i].name);
erasAbbr = regexEscape(eras[i].abbr);
erasNarrow = regexEscape(eras[i].narrow);
mixedPieces.push(regexEscape(eras[i].name));
mixedPieces.push(regexEscape(eras[i].abbr));
mixedPieces.push(regexEscape(eras[i].narrow));
namePieces.push(erasName);
abbrPieces.push(erasAbbr);
narrowPieces.push(erasNarrow);
mixedPieces.push(erasName);
mixedPieces.push(erasAbbr);
mixedPieces.push(erasNarrow);
}
this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
@@ -4588,14 +4657,6 @@
// ALIASES
addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');
// PRIORITY
addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);
// PARSING
addRegexToken('G', matchSigned);
@@ -4625,7 +4686,7 @@
this,
input,
this.week(),
this.weekday(),
this.weekday() + this.localeData()._week.dow,
this.localeData()._week.dow,
this.localeData()._week.doy
);
@@ -4687,14 +4748,6 @@
addFormatToken('Q', 0, 'Qo', 'quarter');
// ALIASES
addUnitAlias('quarter', 'Q');
// PRIORITY
addUnitPriority('quarter', 7);
// PARSING
addRegexToken('Q', match1);
@@ -4714,16 +4767,9 @@
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIORITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('D', match1to2, match1to2NoLeadingZero);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
@@ -4745,13 +4791,6 @@
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
// ALIASES
addUnitAlias('dayOfYear', 'DDD');
// PRIORITY
addUnitPriority('dayOfYear', 4);
// PARSING
addRegexToken('DDD', match1to3);
@@ -4776,17 +4815,9 @@
addFormatToken('m', ['mm', 2], 0, 'minute');
// ALIASES
addUnitAlias('minute', 'm');
// PRIORITY
addUnitPriority('minute', 14);
// PARSING
addRegexToken('m', match1to2);
addRegexToken('m', match1to2, match1to2HasZero);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);
@@ -4798,17 +4829,9 @@
addFormatToken('s', ['ss', 2], 0, 'second');
// ALIASES
addUnitAlias('second', 's');
// PRIORITY
addUnitPriority('second', 15);
// PARSING
addRegexToken('s', match1to2);
addRegexToken('s', match1to2, match1to2HasZero);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);
@@ -4846,14 +4869,6 @@
return this.millisecond() * 1000000;
});
// ALIASES
addUnitAlias('millisecond', 'ms');
// PRIORITY
addUnitPriority('millisecond', 16);
// PARSING
addRegexToken('S', match1to3, match1);
@@ -5161,12 +5176,12 @@
toInt((number % 100) / 10) === 1
? 'th'
: b === 1
? 'st'
: b === 2
? 'nd'
: b === 3
? 'rd'
: 'th';
? 'st'
: b === 2
? 'nd'
: b === 3
? 'rd'
: 'th';
return number + output;
},
});
@@ -5339,19 +5354,6 @@
}
}
// TODO: Use this.as('ms')?
function valueOf$1() {
if (!this.isValid()) {
return NaN;
}
return (
this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6
);
}
function makeAs(alias) {
return function () {
return this.as(alias);
@@ -5366,7 +5368,8 @@
asWeeks = makeAs('w'),
asMonths = makeAs('M'),
asQuarters = makeAs('Q'),
asYears = makeAs('y');
asYears = makeAs('y'),
valueOf$1 = asMilliseconds;
function clone$1() {
return createDuration(this);
@@ -5635,7 +5638,7 @@
//! moment.js
hooks.version = '2.29.4';
hooks.version = '2.30.1';
setHookCallback(createLocal);
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
@@ -1,19 +0,0 @@
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
+3335 -73
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,9 +0,0 @@
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
+5 -4
View File
@@ -259,8 +259,9 @@ var runtime = (function (exports) {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
// Be forgiving, per GeneratorResume behavior specified since ES2015:
// ES2015 spec, step 3: https://262.ecma-international.org/6.0/#sec-generatorresume
// Latest spec, step 2: https://tc39.es/ecma262/#sec-generatorresume
return doneResult();
}
@@ -333,7 +334,7 @@ var runtime = (function (exports) {
var method = delegate.iterator[methodName];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method, or a missing .next mehtod, always terminate the
// method, or a missing .next method, always terminate the
// yield* loop.
context.delegate = null;
@@ -487,7 +488,7 @@ var runtime = (function (exports) {
};
function values(iterable) {
if (iterable || iterable === "") {
if (iterable != null) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
File diff suppressed because one or more lines are too long

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