Merged in feature/81-dev-dev01 (pull request #5)

auto-patch  81-dev-dev01-2023-12-05T22_45_26

* auto-patch  81-dev-dev01-2023-12-05T22_45_26
This commit is contained in:
Tony Volpe
2023-12-05 23:05:59 +00:00
parent ba16964e7a
commit 725d3043d5
1463 changed files with 142461 additions and 89421 deletions
+11 -22
View File
@@ -51,8 +51,8 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"setup": function() { return /* binding */ setup; },
"speak": function() { return /* binding */ speak; }
setup: function() { return /* binding */ setup; },
speak: function() { return /* binding */ speak; }
});
;// CONCATENATED MODULE: external ["wp","domReady"]
@@ -65,6 +65,7 @@ var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
* WordPress dependencies
*/
/**
* Build the explanatory text to be placed before the aria live regions.
*
@@ -73,7 +74,6 @@ var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
*
* @return {HTMLParagraphElement} The explanatory text HTML element.
*/
function addIntroText() {
const introText = document.createElement('p');
introText.id = 'a11y-speak-intro-text';
@@ -84,11 +84,9 @@ function addIntroText() {
const {
body
} = document;
if (body) {
body.appendChild(introText);
}
return introText;
}
@@ -111,11 +109,9 @@ function addContainer(ariaLive = 'polite') {
const {
body
} = document;
if (body) {
body.appendChild(container);
}
return container;
}
@@ -126,12 +122,11 @@ function addContainer(ariaLive = 'polite') {
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.
}
// Make sure the explanatory text is hidden from assistive technologies.
if (introText) {
introText.setAttribute('hidden', 'hidden');
}
@@ -139,6 +134,7 @@ function clear() {
;// CONCATENATED MODULE: ./node_modules/@wordpress/a11y/build-module/filter-message.js
let previousMessage = '';
/**
* Filter the message to be announced to the screenreader.
*
@@ -146,7 +142,6 @@ let previousMessage = '';
*
* @return {string} The filtered message.
*/
function filterMessage(message) {
/*
* Strip HTML tags (if any) from the message string. Ideally, messages should
@@ -156,15 +151,14 @@ function filterMessage(message) {
* 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;
}
@@ -174,6 +168,7 @@ function filterMessage(message) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -185,29 +180,26 @@ function filterMessage(message) {
/**
* 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`.
@@ -226,7 +218,6 @@ external_wp_domReady_default()(setup);
* 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
@@ -237,18 +228,16 @@ function speak(message, ariaLive) {
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');
}
+70 -101
View File
@@ -39,27 +39,27 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"store": function() { return /* reexport */ store; }
store: function() { return /* reexport */ store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/annotations/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"__experimentalGetAllAnnotationsForBlock": function() { return __experimentalGetAllAnnotationsForBlock; },
"__experimentalGetAnnotations": function() { return __experimentalGetAnnotations; },
"__experimentalGetAnnotationsForBlock": function() { return __experimentalGetAnnotationsForBlock; },
"__experimentalGetAnnotationsForRichText": function() { return __experimentalGetAnnotationsForRichText; }
__experimentalGetAllAnnotationsForBlock: function() { return __experimentalGetAllAnnotationsForBlock; },
__experimentalGetAnnotations: function() { return __experimentalGetAnnotations; },
__experimentalGetAnnotationsForBlock: function() { return __experimentalGetAnnotationsForBlock; },
__experimentalGetAnnotationsForRichText: function() { return __experimentalGetAnnotationsForRichText; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/annotations/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"__experimentalAddAnnotation": function() { return __experimentalAddAnnotation; },
"__experimentalRemoveAnnotation": function() { return __experimentalRemoveAnnotation; },
"__experimentalRemoveAnnotationsBySource": function() { return __experimentalRemoveAnnotationsBySource; },
"__experimentalUpdateAnnotationRange": function() { return __experimentalUpdateAnnotationRange; }
__experimentalAddAnnotation: function() { return __experimentalAddAnnotation; },
__experimentalRemoveAnnotation: function() { return __experimentalRemoveAnnotation; },
__experimentalRemoveAnnotationsBySource: function() { return __experimentalRemoveAnnotationsBySource; },
__experimentalUpdateAnnotationRange: function() { return __experimentalUpdateAnnotationRange; }
});
;// CONCATENATED MODULE: external ["wp","richText"]
@@ -94,22 +94,18 @@ const ANNOTATION_ATTRIBUTE_PREFIX = 'annotation-text-';
* @param {Array} annotations The annotation to apply.
* @return {Object} A record with the annotations applied.
*/
function applyAnnotations(record, annotations = []) {
annotations.forEach(annotation => {
let {
start,
end
} = annotation;
if (start > record.text.length) {
start = record.text.length;
}
if (end > record.text.length) {
end = record.text.length;
}
const className = ANNOTATION_ATTRIBUTE_PREFIX + annotation.source;
const id = ANNOTATION_ATTRIBUTE_PREFIX + annotation.id;
record = (0,external_wp_richText_namespaceObject.applyFormat)(record, {
@@ -122,23 +118,23 @@ function applyAnnotations(record, annotations = []) {
});
return record;
}
/**
* Removes annotations from the given record.
*
* @param {Object} record Record to remove annotations from.
* @return {Object} The cleaned record.
*/
function removeAnnotations(record) {
return removeFormat(record, 'core/annotation', 0, record.text.length);
}
/**
* Retrieves the positions of annotations inside an array of formats.
*
* @param {Array} formats Formats with annotations in there.
* @return {Object} ID keyed positions of annotations.
*/
function retrieveAnnotationPositions(formats) {
const positions = {};
formats.forEach((characterFormats, i) => {
@@ -149,21 +145,21 @@ function retrieveAnnotationPositions(formats) {
id
} = format.attributes;
id = id.replace(ANNOTATION_ATTRIBUTE_PREFIX, '');
if (!positions.hasOwnProperty(id)) {
positions[id] = {
start: i
};
} // Annotations refer to positions between characters.
}
// Annotations refer to positions between characters.
// Formats refer to the character themselves.
// So we need to adjust for that here.
positions[id].end = i + 1;
});
});
return positions;
}
/**
* Updates annotations in the state based on positions retrieved from RichText.
*
@@ -173,33 +169,28 @@ function retrieveAnnotationPositions(formats) {
* @param {Function} actions.removeAnnotation Function to remove an annotation from the state.
* @param {Function} actions.updateAnnotationRange Function to update an annotation range in the state.
*/
function updateAnnotationsWithPositions(annotations, positions, {
removeAnnotation,
updateAnnotationRange
}) {
annotations.forEach(currentAnnotation => {
const position = positions[currentAnnotation.id]; // If we cannot find an annotation, delete it.
const position = positions[currentAnnotation.id];
// If we cannot find an annotation, delete it.
if (!position) {
// Apparently the annotation has been removed, so remove it from the state:
// Remove...
removeAnnotation(currentAnnotation.id);
return;
}
const {
start,
end
} = currentAnnotation;
if (start !== position.start || end !== position.end) {
updateAnnotationRange(currentAnnotation.id, position.start, position.end);
}
});
}
const annotation = {
name: FORMAT_NAME,
title: (0,external_wp_i18n_namespaceObject.__)('Annotation'),
@@ -209,11 +200,9 @@ const annotation = {
className: 'class',
id: 'id'
},
edit() {
return null;
},
__experimentalGetPropsForEditableTreePreparation(select, {
richTextIdentifier,
blockClientId
@@ -222,7 +211,6 @@ const annotation = {
annotations: select(STORE_NAME).__experimentalGetAnnotationsForRichText(blockClientId, richTextIdentifier)
};
},
__experimentalCreatePrepareEditableTree({
annotations
}) {
@@ -230,7 +218,6 @@ const annotation = {
if (annotations.length === 0) {
return formats;
}
let record = {
formats,
text
@@ -239,14 +226,12 @@ const annotation = {
return record.formats;
};
},
__experimentalGetPropsForEditableTreeChangeHandler(dispatch) {
return {
removeAnnotation: dispatch(STORE_NAME).__experimentalRemoveAnnotation,
updateAnnotationRange: dispatch(STORE_NAME).__experimentalUpdateAnnotationRange
};
},
__experimentalCreateOnChangeEditableValue(props) {
return formats => {
const positions = retrieveAnnotationPositions(formats);
@@ -261,7 +246,6 @@ const annotation = {
});
};
}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/format/index.js
@@ -269,11 +253,11 @@ const annotation = {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
name: format_name,
...settings
@@ -290,25 +274,23 @@ var external_wp_data_namespaceObject = window["wp"]["data"];
*/
/**
* Internal dependencies
*/
/**
* Adds annotation className to the block-list-block component.
*
* @param {Object} OriginalComponent The original BlockListBlock component.
* @return {Object} The enhanced component.
*/
const addAnnotationClassName = OriginalComponent => {
return (0,external_wp_data_namespaceObject.withSelect)((select, {
clientId,
className
}) => {
const annotations = select(STORE_NAME).__experimentalGetAnnotationsForBlock(clientId);
return {
className: annotations.map(annotation => {
return 'is-annotated-by-' + annotation.source;
@@ -316,7 +298,6 @@ const addAnnotationClassName = OriginalComponent => {
};
})(OriginalComponent);
};
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/annotations', addAnnotationClassName);
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/store/reducer.js
@@ -333,6 +314,7 @@ function filterWithReference(collection, predicate) {
const filteredCollection = collection.filter(predicate);
return collection.length === filteredCollection.length ? collection : filteredCollection;
}
/**
* Creates a new object with the same keys, but with `callback()` called as
* a transformer function on each of the values.
@@ -341,22 +323,21 @@ function filterWithReference(collection, predicate) {
* @param {Function} callback The function to transform each object value.
* @return {Array} Transformed object.
*/
const mapValues = (obj, callback) => Object.entries(obj).reduce((acc, [key, value]) => ({ ...acc,
const mapValues = (obj, callback) => Object.entries(obj).reduce((acc, [key, value]) => ({
...acc,
[key]: callback(value)
}), {});
/**
* Verifies whether the given annotations is a valid annotation.
*
* @param {Object} annotation The annotation to verify.
* @return {boolean} Whether the given annotation is valid.
*/
function isValidAnnotationRange(annotation) {
return typeof annotation.start === 'number' && typeof annotation.end === 'number' && annotation.start <= annotation.end;
}
/**
* Reducer managing annotations.
*
@@ -365,11 +346,8 @@ function isValidAnnotationRange(annotation) {
*
* @return {Array} Updated state.
*/
function annotations(state = {}, action) {
var _state$blockClientId;
switch (action.type) {
case 'ANNOTATION_ADD':
const blockClientId = action.blockClientId;
@@ -381,42 +359,38 @@ function annotations(state = {}, action) {
selector: action.selector,
range: action.range
};
if (newAnnotation.selector === 'range' && !isValidAnnotationRange(newAnnotation.range)) {
return state;
}
const previousAnnotationsForBlock = (_state$blockClientId = state?.[blockClientId]) !== null && _state$blockClientId !== void 0 ? _state$blockClientId : [];
return { ...state,
return {
...state,
[blockClientId]: [...previousAnnotationsForBlock, newAnnotation]
};
case 'ANNOTATION_REMOVE':
return mapValues(state, annotationsForBlock => {
return filterWithReference(annotationsForBlock, annotation => {
return annotation.id !== action.annotationId;
});
});
case 'ANNOTATION_UPDATE_RANGE':
return mapValues(state, annotationsForBlock => {
let hasChangedRange = false;
const newAnnotations = annotationsForBlock.map(annotation => {
if (annotation.id === action.annotationId) {
hasChangedRange = true;
return { ...annotation,
return {
...annotation,
range: {
start: action.start,
end: action.end
}
};
}
return annotation;
});
return hasChangedRange ? newAnnotations : annotationsForBlock;
});
case 'ANNOTATION_REMOVE_SOURCE':
return mapValues(state, annotationsForBlock => {
return filterWithReference(annotationsForBlock, annotation => {
@@ -424,7 +398,6 @@ function annotations(state = {}, action) {
});
});
}
return state;
}
/* harmony default export */ var reducer = (annotations);
@@ -732,6 +705,7 @@ function isShallowEqual(a, b, fromIndex) {
* External dependencies
*/
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation, as in a connected or
@@ -741,8 +715,8 @@ function isShallowEqual(a, b, fromIndex) {
*
* @type {Array}
*/
const EMPTY_ARRAY = [];
/**
* Returns the annotations for a specific client ID.
*
@@ -751,23 +725,20 @@ const EMPTY_ARRAY = [];
*
* @return {Array} The annotations applicable to this block.
*/
const __experimentalGetAnnotationsForBlock = rememo((state, blockClientId) => {
var _state$blockClientId;
return ((_state$blockClientId = state?.[blockClientId]) !== null && _state$blockClientId !== void 0 ? _state$blockClientId : []).filter(annotation => {
return annotation.selector === 'block';
});
}, (state, blockClientId) => {
var _state$blockClientId2;
return [(_state$blockClientId2 = state?.[blockClientId]) !== null && _state$blockClientId2 !== void 0 ? _state$blockClientId2 : EMPTY_ARRAY];
});
function __experimentalGetAllAnnotationsForBlock(state, blockClientId) {
var _state$blockClientId3;
return (_state$blockClientId3 = state?.[blockClientId]) !== null && _state$blockClientId3 !== void 0 ? _state$blockClientId3 : EMPTY_ARRAY;
}
/**
* Returns the annotations that apply to the given RichText instance.
*
@@ -780,10 +751,8 @@ function __experimentalGetAllAnnotationsForBlock(state, blockClientId) {
* @param {string} richTextIdentifier Unique identifier that identifies the given RichText.
* @return {Array} All the annotations relevant for the `RichText`.
*/
const __experimentalGetAnnotationsForRichText = rememo((state, blockClientId, richTextIdentifier) => {
var _state$blockClientId4;
return ((_state$blockClientId4 = state?.[blockClientId]) !== null && _state$blockClientId4 !== void 0 ? _state$blockClientId4 : []).filter(annotation => {
return annotation.selector === 'range' && richTextIdentifier === annotation.richTextIdentifier;
}).map(annotation => {
@@ -791,38 +760,42 @@ const __experimentalGetAnnotationsForRichText = rememo((state, blockClientId, ri
range,
...other
} = annotation;
return { ...range,
return {
...range,
...other
};
});
}, (state, blockClientId) => {
var _state$blockClientId5;
return [(_state$blockClientId5 = state?.[blockClientId]) !== null && _state$blockClientId5 !== void 0 ? _state$blockClientId5 : EMPTY_ARRAY];
});
/**
* Returns all annotations in the editor state.
*
* @param {Object} state Editor state.
* @return {Array} All annotations currently applied.
*/
function __experimentalGetAnnotations(state) {
return Object.values(state).flat();
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/node_modules/uuid/dist/esm-browser/rng.js
;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/native.js
const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
/* harmony default export */ var esm_browser_native = ({
randomUUID
});
;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/rng.js
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
var getRandomValues;
var rnds8 = new Uint8Array(16);
let getRandomValues;
const rnds8 = new Uint8Array(16);
function rng() {
// lazy load so that environments that need to polyfill have a chance to do so
if (!getRandomValues) {
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
@@ -831,54 +804,52 @@ function rng() {
return getRandomValues(rnds8);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/node_modules/uuid/dist/esm-browser/regex.js
/* harmony default export */ var regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/node_modules/uuid/dist/esm-browser/validate.js
function validate(uuid) {
return typeof uuid === 'string' && regex.test(uuid);
}
/* harmony default export */ var esm_browser_validate = (validate);
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/node_modules/uuid/dist/esm-browser/stringify.js
;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/stringify.js
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
const byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).substr(1));
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).slice(1));
}
function stringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
function unsafeStringify(arr, offset = 0) {
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!esm_browser_validate(uuid)) {
if (!validate(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
/* harmony default export */ var esm_browser_stringify = (stringify);
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/node_modules/uuid/dist/esm-browser/v4.js
/* harmony default export */ var esm_browser_stringify = ((/* unused pure expression or super */ null && (stringify)));
;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
if (esm_browser_native.randomUUID && !buf && !options) {
return esm_browser_native.randomUUID();
}
options = options || {};
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
@@ -886,14 +857,14 @@ function v4(options, buf, offset) {
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return esm_browser_stringify(rnds);
return unsafeStringify(rnds);
}
/* harmony default export */ var esm_browser_v4 = (v4);
@@ -902,6 +873,7 @@ function v4(options, buf, offset) {
* External dependencies
*/
/**
* @typedef WPAnnotationRange
*
@@ -929,7 +901,6 @@ function v4(options, buf, offset) {
*
* @return {Object} Action object.
*/
function __experimentalAddAnnotation({
blockClientId,
richTextIdentifier = null,
@@ -946,13 +917,12 @@ function __experimentalAddAnnotation({
source,
selector
};
if (selector === 'range') {
action.range = range;
}
return action;
}
/**
* Removes an annotation with a specific ID.
*
@@ -960,13 +930,13 @@ function __experimentalAddAnnotation({
*
* @return {Object} Action object.
*/
function __experimentalRemoveAnnotation(annotationId) {
return {
type: 'ANNOTATION_REMOVE',
annotationId
};
}
/**
* Updates the range of an annotation.
*
@@ -976,7 +946,6 @@ function __experimentalRemoveAnnotation(annotationId) {
*
* @return {Object} Action object.
*/
function __experimentalUpdateAnnotationRange(annotationId, start, end) {
return {
type: 'ANNOTATION_UPDATE_RANGE',
@@ -985,6 +954,7 @@ function __experimentalUpdateAnnotationRange(annotationId, start, end) {
end
};
}
/**
* Removes all annotations of a specific source.
*
@@ -992,7 +962,6 @@ function __experimentalUpdateAnnotationRange(annotationId, start, end) {
*
* @return {Object} Action object.
*/
function __experimentalRemoveAnnotationsBySource(source) {
return {
type: 'ANNOTATION_REMOVE_SOURCE',
@@ -1005,6 +974,7 @@ function __experimentalRemoveAnnotationsBySource(source) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -1024,7 +994,6 @@ function __experimentalRemoveAnnotationsBySource(source) {
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, {
reducer: reducer,
selectors: selectors_namespaceObject,
File diff suppressed because one or more lines are too long
+81 -132
View File
@@ -43,26 +43,26 @@ function createNonceMiddleware(nonce) {
const middleware = (options, next) => {
const {
headers = {}
} = options; // If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
} = options;
// If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
for (const headerName in headers) {
if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
return next(options);
}
}
return next({ ...options,
headers: { ...headers,
return next({
...options,
headers: {
...headers,
'X-WP-Nonce': middleware.nonce
}
});
};
middleware.nonce = nonce;
return middleware;
}
/* harmony default export */ var nonce = (createNonceMiddleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/namespace-endpoint.js
@@ -72,25 +72,22 @@ function createNonceMiddleware(nonce) {
const namespaceAndEndpointMiddleware = (options, next) => {
let path = options.path;
let namespaceTrimmed, endpointTrimmed;
if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
endpointTrimmed = options.endpoint.replace(/^\//, '');
if (endpointTrimmed) {
path = namespaceTrimmed + '/' + endpointTrimmed;
} else {
path = namespaceTrimmed;
}
}
delete options.namespace;
delete options.endpoint;
return next({ ...options,
return next({
...options,
path
});
};
/* harmony default export */ var namespace_endpoint = (namespaceAndEndpointMiddleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/root-url.js
@@ -98,40 +95,36 @@ const namespaceAndEndpointMiddleware = (options, next) => {
* Internal dependencies
*/
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = rootURL => (options, next) => {
return namespace_endpoint(options, optionsWithPath => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
if (typeof path === 'string') {
apiRoot = rootURL;
if (-1 !== rootURL.indexOf('?')) {
path = path.replace('?', '&');
}
path = path.replace(/^\//, '');
path = path.replace(/^\//, ''); // API root may already include query parameter prefix if site is
// API root may already include query parameter prefix if site is
// configured to use plain permalinks.
if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
path = path.replace('?', '&');
}
url = apiRoot + path;
}
return next({ ...optionsWithPath,
return next({
...optionsWithPath,
url
});
});
};
/* harmony default export */ var root_url = (createRootURLMiddleware);
;// CONCATENATED MODULE: external ["wp","url"]
@@ -141,11 +134,11 @@ var external_wp_url_namespaceObject = window["wp"]["url"];
* WordPress dependencies
*/
/**
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
function createPreloadingMiddleware(preloadedData) {
const cache = Object.fromEntries(Object.entries(preloadedData).map(([path, data]) => [(0,external_wp_url_namespaceObject.normalizePath)(path), data]));
return (options, next) => {
@@ -153,42 +146,38 @@ function createPreloadingMiddleware(preloadedData) {
parse = true
} = options;
/** @type {string | void} */
let rawPath = options.path;
if (!rawPath && options.url) {
const {
rest_route: pathFromQuery,
...queryArgs
} = (0,external_wp_url_namespaceObject.getQueryArgs)(options.url);
if (typeof pathFromQuery === 'string') {
rawPath = (0,external_wp_url_namespaceObject.addQueryArgs)(pathFromQuery, queryArgs);
}
}
if (typeof rawPath !== 'string') {
return next(options);
}
const method = options.method || 'GET';
const path = (0,external_wp_url_namespaceObject.normalizePath)(rawPath);
if ('GET' === method && cache[path]) {
const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only used a single time.
const cacheData = cache[path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[path];
return prepareResponse(cacheData, !!parse);
} else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
const cacheData = cache[method][path]; // Unsetting the cache key ensures that the data is only used a single time.
const cacheData = cache[method][path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[method][path];
return prepareResponse(cacheData, !!parse);
}
return next(options);
};
}
/**
* This is a helper function that sends a success response.
*
@@ -196,8 +185,6 @@ function createPreloadingMiddleware(preloadedData) {
* @param {boolean} parse
* @return {Promise<any>} Promise with the response.
*/
function prepareResponse(responseData, parse) {
return Promise.resolve(parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
status: 200,
@@ -205,7 +192,6 @@ function prepareResponse(responseData, parse) {
headers: responseData.headers
}));
}
/* harmony default export */ var preloading = (createPreloadingMiddleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/fetch-all-middleware.js
@@ -213,6 +199,7 @@ function prepareResponse(responseData, parse) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -225,63 +212,59 @@ function prepareResponse(responseData, parse) {
* @param {Record<string, string | number>} queryArgs
* @return {import('../types').APIFetchOptions} The request with the modified query args
*/
const modifyQuery = ({
path,
url,
...options
}, queryArgs) => ({ ...options,
}, queryArgs) => ({
...options,
url: url && (0,external_wp_url_namespaceObject.addQueryArgs)(url, queryArgs),
path: path && (0,external_wp_url_namespaceObject.addQueryArgs)(path, queryArgs)
});
/**
* Duplicates parsing functionality from apiFetch.
*
* @param {Response} response
* @return {Promise<any>} Parsed response json.
*/
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
/**
* @param {string | null} linkHeader
* @return {{ next?: string }} The parsed link header.
*/
const parseLinkHeader = linkHeader => {
if (!linkHeader) {
return {};
}
const match = linkHeader.match(/<([^>]+)>; rel="next"/);
return match ? {
next: match[1]
} : {};
};
/**
* @param {Response} response
* @return {string | undefined} The next page URL.
*/
const getNextPageUrl = response => {
const {
next
} = parseLinkHeader(response.headers.get('link'));
return next;
};
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request contains an unbounded query.
*/
const requestContainsUnboundedQuery = options => {
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
return pathIsUnbounded || urlIsUnbounded;
};
/**
* The REST API enforces an upper limit on the per_page option. To handle large
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
@@ -289,47 +272,40 @@ const requestContainsUnboundedQuery = options => {
*
* @type {import('../types').APIFetchMiddleware}
*/
const fetchAllMiddleware = async (options, next) => {
if (options.parse === false) {
// If a consumer has opted out of parsing, do not apply middleware.
return next(options);
}
if (!requestContainsUnboundedQuery(options)) {
// If neither url nor path is requesting all items, do not apply middleware.
return next(options);
} // Retrieve requested page of results.
}
const response = await build_module({ ...modifyQuery(options, {
// Retrieve requested page of results.
const response = await build_module({
...modifyQuery(options, {
per_page: 100
}),
// Ensure headers are returned for page 1.
parse: false
});
const results = await parseResponse(response);
if (!Array.isArray(results)) {
// We have no reliable way of merging non-array results.
return results;
}
let nextPage = getNextPageUrl(response);
if (!nextPage) {
// There are no further pages to request.
return results;
} // Iteratively fetch all remaining pages until no "next" header is found.
let mergedResults =
/** @type {any[]} */
[].concat(results);
}
// Iteratively fetch all remaining pages until no "next" header is found.
let mergedResults = /** @type {any[]} */[].concat(results);
while (nextPage) {
const nextResponse = await build_module({ ...options,
const nextResponse = await build_module({
...options,
// Ensure the URL for the next page is used instead of any provided path.
path: undefined,
url: nextPage,
@@ -340,10 +316,8 @@ const fetchAllMiddleware = async (options, next) => {
mergedResults = mergedResults.concat(nextResults);
nextPage = getNextPageUrl(nextResponse);
}
return mergedResults;
};
/* harmony default export */ var fetch_all_middleware = (fetchAllMiddleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/http-v1.js
@@ -353,6 +327,7 @@ const fetchAllMiddleware = async (options, next) => {
* @type {Set<string>}
*/
const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
/**
* Default request method.
*
@@ -363,33 +338,31 @@ const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
*
* @type {string}
*/
const DEFAULT_METHOD = 'GET';
/**
* API Fetch middleware which overrides the request method for HTTP v1
* compatibility leveraging the REST API X-HTTP-Method-Override header.
*
* @type {import('../types').APIFetchMiddleware}
*/
const httpV1Middleware = (options, next) => {
const {
method = DEFAULT_METHOD
} = options;
if (OVERRIDE_METHODS.has(method.toUpperCase())) {
options = { ...options,
headers: { ...options.headers,
options = {
...options,
headers: {
...options.headers,
'X-HTTP-Method-Override': method,
'Content-Type': 'application/json'
},
method: 'POST'
};
}
return next(options);
};
/* harmony default export */ var http_v1 = (httpV1Middleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/user-locale.js
@@ -397,26 +370,23 @@ const httpV1Middleware = (options, next) => {
* WordPress dependencies
*/
/**
* @type {import('../types').APIFetchMiddleware}
*/
const userLocaleMiddleware = (options, next) => {
if (typeof options.url === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.url, '_locale')) {
options.url = (0,external_wp_url_namespaceObject.addQueryArgs)(options.url, {
_locale: 'user'
});
}
if (typeof options.path === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.path, '_locale')) {
options.path = (0,external_wp_url_namespaceObject.addQueryArgs)(options.path, {
_locale: 'user'
});
}
return next(options);
};
/* harmony default export */ var user_locale = (userLocaleMiddleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/utils/response.js
@@ -424,6 +394,7 @@ const userLocaleMiddleware = (options, next) => {
* WordPress dependencies
*/
/**
* Parses the apiFetch response.
*
@@ -432,18 +403,16 @@ const userLocaleMiddleware = (options, next) => {
*
* @return {Promise<any> | null | Response} Parsed response.
*/
const response_parseResponse = (response, shouldParseResponse = true) => {
if (shouldParseResponse) {
if (response.status === 204) {
return null;
}
return response.json ? response.json() : Promise.reject(response);
}
return response;
};
/**
* Calls the `json` function on the Response, throwing an error if the response
* doesn't have a json function or if parsing the json itself fails.
@@ -451,22 +420,19 @@ const response_parseResponse = (response, shouldParseResponse = true) => {
* @param {Response} response
* @return {Promise<any>} Parsed response.
*/
const parseJsonAndNormalizeError = response => {
const invalidJsonError = {
code: 'invalid_json',
message: (0,external_wp_i18n_namespaceObject.__)('The response is not a valid JSON response.')
};
if (!response || !response.json) {
throw invalidJsonError;
}
return response.json().catch(() => {
throw invalidJsonError;
});
};
/**
* Parses the apiFetch response properly and normalize response errors.
*
@@ -475,11 +441,10 @@ const parseJsonAndNormalizeError = response => {
*
* @return {Promise<any>} Parsed response.
*/
const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => {
return Promise.resolve(response_parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse));
};
/**
* Parses a response, throwing an error if parsing the response fails.
*
@@ -487,12 +452,10 @@ const parseResponseAndNormalizeError = (response, shouldParseResponse = true) =>
* @param {boolean} shouldParseResponse
* @return {Promise<any>} Parsed response.
*/
function parseAndThrowError(response, shouldParseResponse = true) {
if (!shouldParseResponse) {
throw response;
}
return parseJsonAndNormalizeError(response).then(error => {
const unknownError = {
code: 'unknown_error',
@@ -507,6 +470,7 @@ function parseAndThrowError(response, shouldParseResponse = true) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -516,31 +480,28 @@ function parseAndThrowError(response, shouldParseResponse = true) {
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request is for media upload.
*/
function isMediaUploadRequest(options) {
const isCreateMethod = !!options.method && options.method === 'POST';
const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
return isMediaEndpoint && isCreateMethod;
}
/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = (options, next) => {
if (!isMediaUploadRequest(options)) {
return next(options);
}
let retries = 0;
const maxRetries = 5;
/**
* @param {string} attachmentId
* @return {Promise<any>} Processed post response.
*/
const postProcess = attachmentId => {
retries++;
return next({
@@ -554,7 +515,6 @@ const mediaUploadMiddleware = (options, next) => {
if (retries < maxRetries) {
return postProcess(attachmentId);
}
next({
path: `/wp/v2/media/${attachmentId}?force=true`,
method: 'DELETE'
@@ -562,12 +522,11 @@ const mediaUploadMiddleware = (options, next) => {
return Promise.reject();
});
};
return next({ ...options,
return next({
...options,
parse: false
}).catch(response => {
const attachmentId = response.headers.get('x-wp-upload-attachment-id');
if (response.status >= 500 && response.status < 600 && attachmentId) {
return postProcess(attachmentId).catch(() => {
if (options.parse !== false) {
@@ -576,15 +535,12 @@ const mediaUploadMiddleware = (options, next) => {
message: (0,external_wp_i18n_namespaceObject.__)('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
});
}
return Promise.reject(response);
});
}
return parseAndThrowError(response, options.parse);
}).then(response => parseResponseAndNormalizeError(response, options.parse));
};
/* harmony default export */ var media_upload = (mediaUploadMiddleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/theme-preview.js
@@ -592,6 +548,7 @@ const mediaUploadMiddleware = (options, next) => {
* WordPress dependencies
*/
/**
* This appends a `wp_theme_preview` parameter to the REST API request URL if
* the admin URL contains a `theme` GET parameter.
@@ -599,23 +556,19 @@ const mediaUploadMiddleware = (options, next) => {
* @param {Record<string, any>} themePath
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
const createThemePreviewMiddleware = themePath => (options, next) => {
if (typeof options.url === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.url, 'wp_theme_preview')) {
options.url = (0,external_wp_url_namespaceObject.addQueryArgs)(options.url, {
wp_theme_preview: themePath
});
}
if (typeof options.path === 'string' && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.path, 'wp_theme_preview')) {
options.path = (0,external_wp_url_namespaceObject.addQueryArgs)(options.path, {
wp_theme_preview: themePath
});
}
return next(options);
};
/* harmony default export */ var theme_preview = (createThemePreviewMiddleware);
;// CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/index.js
@@ -623,6 +576,7 @@ const createThemePreviewMiddleware = themePath => (options, next) => {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -643,7 +597,6 @@ const createThemePreviewMiddleware = themePath => (options, next) => {
*
* @type {Record<string, string>}
*/
const DEFAULT_HEADERS = {
// The backend uses the Accept header as a condition for considering an
// incoming request as a REST request.
@@ -651,34 +604,34 @@ const DEFAULT_HEADERS = {
// See: https://core.trac.wordpress.org/ticket/44534
Accept: 'application/json, */*;q=0.1'
};
/**
* Default set of fetch option values which should be sent with every request
* unless explicitly provided through apiFetch options.
*
* @type {Object}
*/
const DEFAULT_OPTIONS = {
credentials: 'include'
};
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
/**
* @type {import('./types').APIFetchMiddleware[]}
*/
const middlewares = [user_locale, namespace_endpoint, http_v1, fetch_all_middleware];
/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
function registerMiddleware(middleware) {
middlewares.unshift(middleware);
}
/**
* Checks the status of a response, throwing the Response as an error if
* it is outside the 200 range.
@@ -686,22 +639,18 @@ function registerMiddleware(middleware) {
* @param {Response} response
* @return {Response} The response if the status is in the 200 range.
*/
const checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw response;
};
/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
/**
* @type {FetchHandler}
*/
const defaultFetchHandler = nextOptions => {
const {
url,
@@ -713,19 +662,23 @@ const defaultFetchHandler = nextOptions => {
let {
body,
headers
} = nextOptions; // Merge explicitly-provided headers with default values.
} = nextOptions;
headers = { ...DEFAULT_HEADERS,
// Merge explicitly-provided headers with default values.
headers = {
...DEFAULT_HEADERS,
...headers
}; // The `data` property is a shorthand for sending a JSON body.
};
// The `data` property is a shorthand for sending a JSON body.
if (data) {
body = JSON.stringify(data);
headers['Content-Type'] = 'application/json';
}
const responsePromise = window.fetch( // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
url || path || window.location.href, { ...DEFAULT_OPTIONS,
const responsePromise = window.fetch(
// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
url || path || window.location.href, {
...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers
@@ -734,55 +687,52 @@ const defaultFetchHandler = nextOptions => {
// Re-throw AbortError for the users to handle it themselves.
if (err && err.name === 'AbortError') {
throw err;
} // Otherwise, there is most likely no network connection.
}
// Otherwise, there is most likely no network connection.
// Unfortunately the message might depend on the browser.
throw {
code: 'fetch_error',
message: (0,external_wp_i18n_namespaceObject.__)('You are probably offline.')
};
});
};
/** @type {FetchHandler} */
let fetchHandler = defaultFetchHandler;
/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {FetchHandler} newFetchHandler The new fetch handler
*/
function setFetchHandler(newFetchHandler) {
fetchHandler = newFetchHandler;
}
/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
function apiFetch(options) {
// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
// converting `middlewares = [ m1, m2, m3 ]` into:
// ```
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
// ```
const enhancedHandler = middlewares.reduceRight((
/** @type {FetchHandler} */
next, middleware) => {
const enhancedHandler = middlewares.reduceRight(( /** @type {FetchHandler} */next, middleware) => {
return workingOptions => middleware(workingOptions, next);
}, fetchHandler);
return enhancedHandler(options).catch(error => {
if (error.code !== 'rest_cookie_invalid_nonce') {
return Promise.reject(error);
} // If the nonce is invalid, refresh it and try again.
}
return window // @ts-ignore
// If the nonce is invalid, refresh it and try again.
return window
// @ts-ignore
.fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
// @ts-ignore
apiFetch.nonceMiddleware.nonce = text;
@@ -790,7 +740,6 @@ function apiFetch(options) {
});
});
}
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;
apiFetch.createNonceMiddleware = nonce;
+151 -122
View File
@@ -36,8 +36,8 @@
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "autop": function() { return /* binding */ autop; },
/* harmony export */ "removep": function() { return /* binding */ removep; }
/* harmony export */ autop: function() { return /* binding */ autop; },
/* harmony export */ removep: function() { return /* binding */ removep; }
/* harmony export */ });
/**
* The regular expression for an HTML element.
@@ -46,34 +46,54 @@ __webpack_require__.r(__webpack_exports__);
*/
const htmlSplitRegex = (() => {
/* eslint-disable no-multi-spaces */
const comments = '!' + // Start of comment, after the <.
'(?:' + // Unroll the loop: Consume everything until --> is found.
'-(?!->)' + // Dash not followed by end of comment.
'[^\\-]*' + // Consume non-dashes.
')*' + // Loop possessively.
const comments = '!' +
// Start of comment, after the <.
'(?:' +
// Unroll the loop: Consume everything until --> is found.
'-(?!->)' +
// Dash not followed by end of comment.
'[^\\-]*' +
// Consume non-dashes.
')*' +
// Loop possessively.
'(?:-->)?'; // End of comment. If not found, match all input.
const cdata = '!\\[CDATA\\[' + // Start of comment, after the <.
'[^\\]]*' + // Consume non-].
'(?:' + // Unroll the loop: Consume everything until ]]> is found.
'](?!]>)' + // One ] not followed by end of comment.
'[^\\]]*' + // Consume non-].
')*?' + // Loop possessively.
const cdata = '!\\[CDATA\\[' +
// Start of comment, after the <.
'[^\\]]*' +
// Consume non-].
'(?:' +
// Unroll the loop: Consume everything until ]]> is found.
'](?!]>)' +
// One ] not followed by end of comment.
'[^\\]]*' +
// Consume non-].
')*?' +
// Loop possessively.
'(?:]]>)?'; // End of comment. If not found, match all input.
const escaped = '(?=' + // Is the element escaped?
'!--' + '|' + '!\\[CDATA\\[' + ')' + '((?=!-)' + // If yes, which type?
const escaped = '(?=' +
// Is the element escaped?
'!--' + '|' + '!\\[CDATA\\[' + ')' + '((?=!-)' +
// If yes, which type?
comments + '|' + cdata + ')';
const regex = '(' + // Capture the entire match.
'<' + // Find start of element.
'(' + // Conditional expression follows.
escaped + // Find end of escaped element.
'|' + // ... else ...
'[^>]*>?' + // Find end of normal element.
const regex = '(' +
// Capture the entire match.
'<' +
// Find start of element.
'(' +
// Conditional expression follows.
escaped +
// Find end of escaped element.
'|' +
// ... else ...
'[^>]*>?' +
// Find end of normal element.
')' + ')';
return new RegExp(regex);
/* eslint-enable no-multi-spaces */
})();
/**
* Separate HTML elements and comments from the text.
*
@@ -81,32 +101,26 @@ const htmlSplitRegex = (() => {
*
* @return {string[]} The formatted text.
*/
function htmlSplit(input) {
const parts = [];
let workingInput = input;
let match;
while (match = workingInput.match(htmlSplitRegex)) {
// The `match` result, when invoked on a RegExp with the `g` flag (`/foo/g`) will not include `index`.
// If the `g` flag is omitted, `index` is included.
// `htmlSplitRegex` does not have the `g` flag so we can assert it will have an index number.
// Assert `match.index` is a number.
const index =
/** @type {number} */
match.index;
const index = /** @type {number} */match.index;
parts.push(workingInput.slice(0, index));
parts.push(match[0]);
workingInput = workingInput.slice(index + match[0].length);
}
if (workingInput.length) {
parts.push(workingInput);
}
return parts;
}
/**
* Replace characters or phrases within HTML elements only.
*
@@ -115,34 +129,32 @@ function htmlSplit(input) {
*
* @return {string} The formatted text.
*/
function replaceInHtmlTags(haystack, replacePairs) {
// Find all elements.
const textArr = htmlSplit(haystack);
let changed = false; // Extract all needles.
let changed = false;
const needles = Object.keys(replacePairs); // Loop through delimiters (elements) only.
// Extract all needles.
const needles = Object.keys(replacePairs);
// Loop through delimiters (elements) only.
for (let i = 1; i < textArr.length; i += 2) {
for (let j = 0; j < needles.length; j++) {
const needle = needles[j];
if (-1 !== textArr[i].indexOf(needle)) {
textArr[i] = textArr[i].replace(new RegExp(needle, 'g'), replacePairs[needle]);
changed = true; // After one strtr() break out of the foreach loop and look at next element.
changed = true;
// After one strtr() break out of the foreach loop and look at next element.
break;
}
}
}
if (changed) {
haystack = textArr.join('');
}
return haystack;
}
/**
* Replaces double line-breaks with paragraph elements.
*
@@ -162,145 +174,159 @@ function replaceInHtmlTags(haystack, replacePairs) {
*
* @return {string} Text which has been converted into paragraph tags.
*/
function autop(text, br = true) {
const preTags = [];
if (text.trim() === '') {
return '';
} // Just to make things a little easier, pad the end.
}
// Just to make things a little easier, pad the end.
text = text + '\n';
/*
* Pre tags shouldn't be touched by autop.
* Replace pre tags with placeholders and bring them back after autop.
*/
if (text.indexOf('<pre') !== -1) {
const textParts = text.split('</pre>');
const lastText = textParts.pop();
text = '';
for (let i = 0; i < textParts.length; i++) {
const textPart = textParts[i];
const start = textPart.indexOf('<pre'); // Malformed html?
const start = textPart.indexOf('<pre');
// Malformed html?
if (start === -1) {
text += textPart;
continue;
}
const name = '<pre wp-pre-tag-' + i + '></pre>';
preTags.push([name, textPart.substr(start) + '</pre>']);
text += textPart.substr(0, start) + name;
}
text += lastText;
} // Change multiple <br>s into two line breaks, which will turn into paragraphs.
}
// Change multiple <br>s into two line breaks, which will turn into paragraphs.
text = text.replace(/<br\s*\/?>\s*<br\s*\/?>/g, '\n\n');
const allBlocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; // Add a double line break above block-level opening tags.
const allBlocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
text = text.replace(new RegExp('(<' + allBlocks + '[\\s/>])', 'g'), '\n\n$1'); // Add a double line break below block-level closing tags.
// Add a double line break above block-level opening tags.
text = text.replace(new RegExp('(<' + allBlocks + '[\\s/>])', 'g'), '\n\n$1');
text = text.replace(new RegExp('(</' + allBlocks + '>)', 'g'), '$1\n\n'); // Standardize newline characters to "\n".
// Add a double line break below block-level closing tags.
text = text.replace(new RegExp('(</' + allBlocks + '>)', 'g'), '$1\n\n');
text = text.replace(/\r\n|\r/g, '\n'); // Find newlines in all elements and add placeholders.
// Standardize newline characters to "\n".
text = text.replace(/\r\n|\r/g, '\n');
// Find newlines in all elements and add placeholders.
text = replaceInHtmlTags(text, {
'\n': ' <!-- wpnl --> '
}); // Collapse line breaks before and after <option> elements so they don't get autop'd.
});
// Collapse line breaks before and after <option> elements so they don't get autop'd.
if (text.indexOf('<option') !== -1) {
text = text.replace(/\s*<option/g, '<option');
text = text.replace(/<\/option>\s*/g, '</option>');
}
/*
* Collapse line breaks inside <object> elements, before <param> and <embed> elements
* so they don't get autop'd.
*/
if (text.indexOf('</object>') !== -1) {
text = text.replace(/(<object[^>]*>)\s*/g, '$1');
text = text.replace(/\s*<\/object>/g, '</object>');
text = text.replace(/\s*(<\/?(?:param|embed)[^>]*>)\s*/g, '$1');
}
/*
* Collapse line breaks inside <audio> and <video> elements,
* before and after <source> and <track> elements.
*/
if (text.indexOf('<source') !== -1 || text.indexOf('<track') !== -1) {
text = text.replace(/([<\[](?:audio|video)[^>\]]*[>\]])\s*/g, '$1');
text = text.replace(/\s*([<\[]\/(?:audio|video)[>\]])/g, '$1');
text = text.replace(/\s*(<(?:source|track)[^>]*>)\s*/g, '$1');
} // Collapse line breaks before and after <figcaption> elements.
}
// Collapse line breaks before and after <figcaption> elements.
if (text.indexOf('<figcaption') !== -1) {
text = text.replace(/\s*(<figcaption[^>]*>)/, '$1');
text = text.replace(/<\/figcaption>\s*/, '</figcaption>');
} // Remove more than two contiguous line breaks.
}
// Remove more than two contiguous line breaks.
text = text.replace(/\n\n+/g, '\n\n');
text = text.replace(/\n\n+/g, '\n\n'); // Split up the contents into an array of strings, separated by double line breaks.
// Split up the contents into an array of strings, separated by double line breaks.
const texts = text.split(/\n\s*\n/).filter(Boolean);
const texts = text.split(/\n\s*\n/).filter(Boolean); // Reset text prior to rebuilding.
text = ''; // Rebuild the content as a string, wrapping every bit with a <p>.
// Reset text prior to rebuilding.
text = '';
// Rebuild the content as a string, wrapping every bit with a <p>.
texts.forEach(textPiece => {
text += '<p>' + textPiece.replace(/^\n*|\n*$/g, '') + '</p>\n';
}); // Under certain strange conditions it could create a P of entirely whitespace.
});
text = text.replace(/<p>\s*<\/p>/g, ''); // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
// Under certain strange conditions it could create a P of entirely whitespace.
text = text.replace(/<p>\s*<\/p>/g, '');
text = text.replace(/<p>([^<]+)<\/(div|address|form)>/g, '<p>$1</p></$2>'); // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
// Add a closing <p> inside <div>, <address>, or <form> tag if missing.
text = text.replace(/<p>([^<]+)<\/(div|address|form)>/g, '<p>$1</p></$2>');
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // In some cases <li> may get wrapped in <p>, fix them.
// If an opening or closing block element tag is wrapped in a <p>, unwrap it.
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1');
text = text.replace(/<p>(<li.+?)<\/p>/g, '$1'); // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
// In some cases <li> may get wrapped in <p>, fix them.
text = text.replace(/<p>(<li.+?)<\/p>/g, '$1');
// If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
text = text.replace(/<p><blockquote([^>]*)>/gi, '<blockquote$1><p>');
text = text.replace(/<\/blockquote><\/p>/g, '</p></blockquote>'); // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
text = text.replace(/<\/blockquote><\/p>/g, '</p></blockquote>');
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)', 'g'), '$1'); // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
// If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)', 'g'), '$1');
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // Optionally insert line breaks.
// If an opening or closing block element tag is followed by a closing <p> tag, remove it.
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1');
// Optionally insert line breaks.
if (br) {
// Replace newlines that shouldn't be touched with a placeholder.
text = text.replace(/<(script|style).*?<\/\\1>/g, match => match[0].replace(/\n/g, '<WPPreserveNewline />')); // Normalize <br>
text = text.replace(/<(script|style).*?<\/\\1>/g, match => match[0].replace(/\n/g, '<WPPreserveNewline />'));
text = text.replace(/<br>|<br\/>/g, '<br />'); // Replace any new line characters that aren't preceded by a <br /> with a <br />.
// Normalize <br>
text = text.replace(/<br>|<br\/>/g, '<br />');
text = text.replace(/(<br \/>)?\s*\n/g, (a, b) => b ? a : '<br />\n'); // Replace newline placeholders with newlines.
// Replace any new line characters that aren't preceded by a <br /> with a <br />.
text = text.replace(/(<br \/>)?\s*\n/g, (a, b) => b ? a : '<br />\n');
// Replace newline placeholders with newlines.
text = text.replace(/<WPPreserveNewline \/>/g, '\n');
} // If a <br /> tag is after an opening or closing block tag, remove it.
}
// If a <br /> tag is after an opening or closing block tag, remove it.
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*<br />', 'g'), '$1');
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*<br />', 'g'), '$1'); // If a <br /> tag is before a subset of opening or closing block tags, remove it.
// If a <br /> tag is before a subset of opening or closing block tags, remove it.
text = text.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)/g, '$1');
text = text.replace(/\n<\/p>$/g, '</p>'); // Replace placeholder <pre> tags with their original content.
text = text.replace(/\n<\/p>$/g, '</p>');
// Replace placeholder <pre> tags with their original content.
preTags.forEach(preTag => {
const [name, original] = preTag;
text = text.replace(name, original);
}); // Restore newlines in all elements.
});
// Restore newlines in all elements.
if (-1 !== text.indexOf('<!-- wpnl -->')) {
text = text.replace(/\s?<!-- wpnl -->\s?/g, '\n');
}
return text;
}
/**
* Replaces `<p>` tags with two line breaks. "Opposite" of autop().
*
@@ -317,30 +343,27 @@ function autop(text, br = true) {
*
* @return {string} The content with stripped paragraph tags.
*/
function removep(html) {
const blocklist = 'blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure';
const blocklist1 = blocklist + '|div|p';
const blocklist2 = blocklist + '|pre';
/** @type {string[]} */
const preserve = [];
let preserveLinebreaks = false;
let preserveBr = false;
if (!html) {
return '';
} // Protect script and style tags.
}
// Protect script and style tags.
if (html.indexOf('<script') !== -1 || html.indexOf('<style') !== -1) {
html = html.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g, match => {
preserve.push(match);
return '<wp-preserve>';
});
} // Protect pre tags.
}
// Protect pre tags.
if (html.indexOf('<pre') !== -1) {
preserveLinebreaks = true;
html = html.replace(/<pre[^>]*>[\s\S]+?<\/pre>/g, a => {
@@ -348,91 +371,97 @@ function removep(html) {
a = a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-line-break>');
return a.replace(/\r?\n/g, '<wp-line-break>');
});
} // Remove line breaks but keep <br> tags inside image captions.
}
// Remove line breaks but keep <br> tags inside image captions.
if (html.indexOf('[caption') !== -1) {
preserveBr = true;
html = html.replace(/\[caption[\s\S]+?\[\/caption\]/g, a => {
return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, '');
});
} // Normalize white space characters before and after block tags.
}
// Normalize white space characters before and after block tags.
html = html.replace(new RegExp('\\s*</(' + blocklist1 + ')>\\s*', 'g'), '</$1>\n');
html = html.replace(new RegExp('\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g'), '\n<$1>'); // Mark </p> if it has any attributes.
html = html.replace(new RegExp('\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g'), '\n<$1>');
html = html.replace(/(<p [^>]+>[\s\S]*?)<\/p>/g, '$1</p#>'); // Preserve the first <p> inside a <div>.
// Mark </p> if it has any attributes.
html = html.replace(/(<p [^>]+>[\s\S]*?)<\/p>/g, '$1</p#>');
html = html.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n'); // Remove paragraph tags.
// Preserve the first <p> inside a <div>.
html = html.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n');
// Remove paragraph tags.
html = html.replace(/\s*<p>/gi, '');
html = html.replace(/\s*<\/p>\s*/gi, '\n\n'); // Normalize white space chars and remove multiple line breaks.
html = html.replace(/\s*<\/p>\s*/gi, '\n\n');
html = html.replace(/\n[\s\u00a0]+\n/g, '\n\n'); // Replace <br> tags with line breaks.
// Normalize white space chars and remove multiple line breaks.
html = html.replace(/\n[\s\u00a0]+\n/g, '\n\n');
// Replace <br> tags with line breaks.
html = html.replace(/(\s*)<br ?\/?>\s*/gi, (_, space) => {
if (space && space.indexOf('\n') !== -1) {
return '\n\n';
}
return '\n';
}); // Fix line breaks around <div>.
});
// Fix line breaks around <div>.
html = html.replace(/\s*<div/g, '\n<div');
html = html.replace(/<\/div>\s*/g, '</div>\n'); // Fix line breaks around caption shortcodes.
html = html.replace(/<\/div>\s*/g, '</div>\n');
// Fix line breaks around caption shortcodes.
html = html.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
html = html.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption'); // Pad block elements tags with a line break.
html = html.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption');
// Pad block elements tags with a line break.
html = html.replace(new RegExp('\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
html = html.replace(new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g'), '</$1>\n'); // Indent <li>, <dt> and <dd> tags.
html = html.replace(new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g'), '</$1>\n');
html = html.replace(/<((li|dt|dd)[^>]*)>/g, ' \t<$1>'); // Fix line breaks around <select> and <option>.
// Indent <li>, <dt> and <dd> tags.
html = html.replace(/<((li|dt|dd)[^>]*)>/g, ' \t<$1>');
// Fix line breaks around <select> and <option>.
if (html.indexOf('<option') !== -1) {
html = html.replace(/\s*<option/g, '\n<option');
html = html.replace(/\s*<\/select>/g, '\n</select>');
} // Pad <hr> with two line breaks.
}
// Pad <hr> with two line breaks.
if (html.indexOf('<hr') !== -1) {
html = html.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
} // Remove line breaks in <object> tags.
}
// Remove line breaks in <object> tags.
if (html.indexOf('<object') !== -1) {
html = html.replace(/<object[\s\S]+?<\/object>/g, a => {
return a.replace(/[\r\n]+/g, '');
});
} // Unmark special paragraph closing tags.
}
// Unmark special paragraph closing tags.
html = html.replace(/<\/p#>/g, '</p>\n');
html = html.replace(/<\/p#>/g, '</p>\n'); // Pad remaining <p> tags whit a line break.
html = html.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1'); // Trim.
// Pad remaining <p> tags whit a line break.
html = html.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1');
// Trim.
html = html.replace(/^\s+/, '');
html = html.replace(/[\s\u00a0]+$/, '');
if (preserveLinebreaks) {
html = html.replace(/<wp-line-break>/g, '\n');
}
if (preserveBr) {
html = html.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
} // Restore preserved tags.
}
// Restore preserved tags.
if (preserve.length) {
html = html.replace(/<wp-preserve>/g, () => {
return (
/** @type {string} */
preserve.shift()
return (/** @type {string} */preserve.shift()
);
});
}
return html;
}
+11 -13
View File
@@ -36,16 +36,17 @@
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "createBlobURL": function() { return /* binding */ createBlobURL; },
/* harmony export */ "getBlobByURL": function() { return /* binding */ getBlobByURL; },
/* harmony export */ "getBlobTypeByURL": function() { return /* binding */ getBlobTypeByURL; },
/* harmony export */ "isBlobURL": function() { return /* binding */ isBlobURL; },
/* harmony export */ "revokeBlobURL": function() { return /* binding */ revokeBlobURL; }
/* harmony export */ createBlobURL: function() { return /* binding */ createBlobURL; },
/* harmony export */ getBlobByURL: function() { return /* binding */ getBlobByURL; },
/* harmony export */ getBlobTypeByURL: function() { return /* binding */ getBlobTypeByURL; },
/* harmony export */ isBlobURL: function() { return /* binding */ isBlobURL; },
/* harmony export */ revokeBlobURL: function() { return /* binding */ revokeBlobURL; }
/* harmony export */ });
/**
* @type {Record<string, File|undefined>}
*/
const cache = {};
/**
* Create a blob URL from a file.
*
@@ -53,12 +54,12 @@ const cache = {};
*
* @return {string} The blob URL.
*/
function createBlobURL(file) {
const url = window.URL.createObjectURL(file);
cache[url] = file;
return url;
}
/**
* Retrieve a file based on a blob URL. The file must have been created by
* `createBlobURL` and not removed by `revokeBlobURL`, otherwise it will return
@@ -68,10 +69,10 @@ function createBlobURL(file) {
*
* @return {File|undefined} The file for the blob URL.
*/
function getBlobByURL(url) {
return cache[url];
}
/**
* Retrieve a blob type based on URL. The file must have been created by
* `createBlobURL` and not removed by `revokeBlobURL`, otherwise it will return
@@ -81,36 +82,33 @@ function getBlobByURL(url) {
*
* @return {string|undefined} The blob type.
*/
function getBlobTypeByURL(url) {
return getBlobByURL(url)?.type.split('/')[0]; // 0: media type , 1: file extension eg ( type: 'image/jpeg' ).
}
/**
* Remove the resource and file cache from memory.
*
* @param {string} url The blob URL.
*/
function revokeBlobURL(url) {
if (cache[url]) {
window.URL.revokeObjectURL(url);
}
delete cache[url];
}
/**
* Check whether a url is a blob url.
*
* @param {string} url The URL.
* @param {string|undefined} url The URL.
*
* @return {boolean} Is the url a blob url?
*/
function isBlobURL(url) {
if (!url || !url.indexOf) {
return false;
}
return url.indexOf('blob:') === 0;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+14058 -18837
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+6266 -7180
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+40 -71
View File
@@ -36,7 +36,7 @@
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "parse": function() { return /* binding */ parse; }
/* harmony export */ parse: function() { return /* binding */ parse; }
/* harmony export */ });
/**
* @type {string}
@@ -45,18 +45,16 @@ let document;
/**
* @type {number}
*/
let offset;
/**
* @type {ParsedBlock[]}
*/
let output;
/**
* @type {ParsedFrame[]}
*/
let stack;
/**
* @typedef {Object|null} Attributes
*/
@@ -128,8 +126,8 @@ let stack;
* @since 3.8.0
* @since 4.6.1 added optimization to prevent backtracking on attribute parsing
*/
const tokenizer = /<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g;
/**
* Constructs a block object.
*
@@ -140,7 +138,6 @@ const tokenizer = /<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?
* @param {string[]} innerContent
* @return {ParsedBlock} The block object.
*/
function Block(blockName, attrs, innerBlocks, innerHTML, innerContent) {
return {
blockName,
@@ -150,17 +147,17 @@ function Block(blockName, attrs, innerBlocks, innerHTML, innerContent) {
innerContent
};
}
/**
* Constructs a freeform block object.
*
* @param {string} innerHTML
* @return {ParsedBlock} The freeform block object.
*/
function Freeform(innerHTML) {
return Block(null, {}, [], innerHTML, [innerHTML]);
}
/**
* Constructs a frame object.
*
@@ -171,8 +168,6 @@ function Freeform(innerHTML) {
* @param {number|null} leadingHtmlStart
* @return {ParsedFrame} The frame object.
*/
function Frame(block, tokenStart, tokenLength, prevOffset, leadingHtmlStart) {
return {
block,
@@ -182,6 +177,7 @@ function Frame(block, tokenStart, tokenLength, prevOffset, leadingHtmlStart) {
leadingHtmlStart
};
}
/**
* Parser function, that converts input HTML into a block based structure.
*
@@ -259,61 +255,57 @@ function Frame(block, tokenStart, tokenLength, prevOffset, leadingHtmlStart) {
* ```
* @return {ParsedBlock[]} A block-based representation of the input HTML.
*/
const parse = doc => {
document = doc;
offset = 0;
output = [];
stack = [];
tokenizer.lastIndex = 0;
do {// twiddle our thumbs
do {
// twiddle our thumbs
} while (proceed());
return output;
};
/**
* Parses the next token in the input document.
*
* @return {boolean} Returns true when there is more tokens to parse.
*/
function proceed() {
const stackDepth = stack.length;
const next = nextToken();
const [tokenType, blockName, attrs, startOffset, tokenLength] = next; // We may have some HTML soup before the next block.
const [tokenType, blockName, attrs, startOffset, tokenLength] = next;
// We may have some HTML soup before the next block.
const leadingHtmlStart = startOffset > offset ? offset : null;
switch (tokenType) {
case 'no-more-tokens':
// If not in a block then flush output.
if (0 === stackDepth) {
addFreeform();
return false;
} // Otherwise we have a problem
}
// Otherwise we have a problem
// This is an error
// we have options
// - treat it all as freeform text
// - assume an implicit closer (easiest when not nesting)
// For the easy case we'll assume an implicit closer.
if (1 === stackDepth) {
addBlockFromStack();
return false;
} // For the nested case where it's more difficult we'll
}
// For the nested case where it's more difficult we'll
// have to assume that multiple closers are missing
// and so we'll collapse the whole stack piecewise.
while (0 < stack.length) {
addBlockFromStack();
}
return false;
case 'void-block':
// easy case is if we stumbled upon a void block
// in the top-level of the document.
@@ -321,23 +313,20 @@ function proceed() {
if (null !== leadingHtmlStart) {
output.push(Freeform(document.substr(leadingHtmlStart, startOffset - leadingHtmlStart)));
}
output.push(Block(blockName, attrs, [], '', []));
offset = startOffset + tokenLength;
return true;
} // Otherwise we found an inner block.
}
// Otherwise we found an inner block.
addInnerBlock(Block(blockName, attrs, [], '', []), startOffset, tokenLength);
offset = startOffset + tokenLength;
return true;
case 'block-opener':
// Track all newly-opened blocks on the stack.
stack.push(Frame(Block(blockName, attrs, [], '', []), startOffset, tokenLength, startOffset + tokenLength, leadingHtmlStart));
offset = startOffset + tokenLength;
return true;
case 'block-closer':
// If we're missing an opener we're in trouble
// This is an error.
@@ -348,20 +337,18 @@ function proceed() {
// - give up and close out the document.
addFreeform();
return false;
} // If we're not nesting then this is easy - close the block.
}
// If we're not nesting then this is easy - close the block.
if (1 === stackDepth) {
addBlockFromStack(startOffset);
offset = startOffset + tokenLength;
return true;
} // Otherwise we're nested and we have to close out the current
}
// Otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent.
const stackTop =
/** @type {ParsedFrame} */
stack.pop();
const stackTop = /** @type {ParsedFrame} */stack.pop();
const html = document.substr(stackTop.prevOffset, startOffset - stackTop.prevOffset);
stackTop.block.innerHTML += html;
stackTop.block.innerContent.push(html);
@@ -369,13 +356,13 @@ function proceed() {
addInnerBlock(stackTop.block, stackTop.tokenStart, stackTop.tokenLength, startOffset + tokenLength);
offset = startOffset + tokenLength;
return true;
default:
// This is an error.
addFreeform();
return false;
}
}
/**
* Parse JSON if valid, otherwise return null
*
@@ -386,8 +373,6 @@ function proceed() {
* @param {string} input JSON input string to parse
* @return {Object|null} parsed JSON if valid
*/
function parseJSON(input) {
try {
return JSON.parse(input);
@@ -395,13 +380,12 @@ function parseJSON(input) {
return null;
}
}
/**
* Finds the next token in the document.
*
* @return {Token} The next matched token.
*/
function nextToken() {
// Aye the magic
// we're using a single RegExp to tokenize the block comment delimiters
@@ -409,55 +393,50 @@ function nextToken() {
// block opener and a block closer is the leading `/` before `wp:` (and
// a closer has no attributes). we can trap them both and process the
// match back in JavaScript to see which one it was.
const matches = tokenizer.exec(document); // We have no more tokens.
const matches = tokenizer.exec(document);
// We have no more tokens.
if (null === matches) {
return ['no-more-tokens', '', null, 0, 0];
}
const startedAt = matches.index;
const [match, closerMatch, namespaceMatch, nameMatch, attrsMatch
/* Internal/unused. */
,, voidMatch] = matches;
const [match, closerMatch, namespaceMatch, nameMatch, attrsMatch /* Internal/unused. */,, voidMatch] = matches;
const length = match.length;
const isCloser = !!closerMatch;
const isVoid = !!voidMatch;
const namespace = namespaceMatch || 'core/';
const name = namespace + nameMatch;
const hasAttrs = !!attrsMatch;
const attrs = hasAttrs ? parseJSON(attrsMatch) : {}; // This state isn't allowed
// This is an error.
const attrs = hasAttrs ? parseJSON(attrsMatch) : {};
if (isCloser && (isVoid || hasAttrs)) {// We can ignore them since they don't hurt anything
// This state isn't allowed
// This is an error.
if (isCloser && (isVoid || hasAttrs)) {
// We can ignore them since they don't hurt anything
// we may warn against this at some point or reject it.
}
if (isVoid) {
return ['void-block', name, attrs, startedAt, length];
}
if (isCloser) {
return ['block-closer', name, null, startedAt, length];
}
return ['block-opener', name, attrs, startedAt, length];
}
/**
* Adds a freeform block to the output.
*
* @param {number} [rawLength]
*/
function addFreeform(rawLength) {
const length = rawLength ? rawLength : document.length - offset;
if (0 === length) {
return;
}
output.push(Freeform(document.substr(offset, length)));
}
/**
* Adds inner block to the parent block.
*
@@ -466,48 +445,38 @@ function addFreeform(rawLength) {
* @param {number} tokenLength
* @param {number} [lastOffset]
*/
function addInnerBlock(block, tokenStart, tokenLength, lastOffset) {
const parent = stack[stack.length - 1];
parent.block.innerBlocks.push(block);
const html = document.substr(parent.prevOffset, tokenStart - parent.prevOffset);
if (html) {
parent.block.innerHTML += html;
parent.block.innerContent.push(html);
}
parent.block.innerContent.push(null);
parent.prevOffset = lastOffset ? lastOffset : tokenStart + tokenLength;
}
/**
* Adds block from the stack to the output.
*
* @param {number} [endOffset]
*/
function addBlockFromStack(endOffset) {
const {
block,
leadingHtmlStart,
prevOffset,
tokenStart
} =
/** @type {ParsedFrame} */
stack.pop();
} = /** @type {ParsedFrame} */stack.pop();
const html = endOffset ? document.substr(prevOffset, endOffset - prevOffset) : document.substr(prevOffset);
if (html) {
block.innerHTML += html;
block.innerContent.push(html);
}
if (null !== leadingHtmlStart) {
output.push(Freeform(document.substr(leadingHtmlStart, tokenStart - leadingHtmlStart)));
}
output.push(block);
}
+1508 -1616
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+320 -97
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+26139 -21733
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+579 -528
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+227 -113
View File
@@ -39,7 +39,7 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"privateApis": function() { return /* reexport */ privateApis; }
privateApis: function() { return /* reexport */ privateApis; }
});
;// CONCATENATED MODULE: external ["wp","commands"]
@@ -52,7 +52,6 @@ var external_wp_element_namespaceObject = window["wp"]["element"];
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
@@ -65,20 +64,52 @@ const plus = (0,external_wp_element_namespaceObject.createElement)(external_wp_p
}));
/* harmony default export */ var library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/external.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/symbol.js
/**
* WordPress dependencies
*/
const external = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
const symbol = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z"
d: "M21.3 10.8l-5.6-5.6c-.7-.7-1.8-.7-2.5 0l-5.6 5.6c-.7.7-.7 1.8 0 2.5l5.6 5.6c.3.3.8.5 1.2.5s.9-.2 1.2-.5l5.6-5.6c.8-.7.8-1.9.1-2.5zm-1 1.4l-5.6 5.6c-.1.1-.3.1-.4 0l-5.6-5.6c-.1-.1-.1-.3 0-.4l5.6-5.6s.1-.1.2-.1.1 0 .2.1l5.6 5.6c.1.1.1.3 0 .4zm-16.6-.4L10 5.5l-1-1-6.3 6.3c-.7.7-.7 1.8 0 2.5L9 19.5l1.1-1.1-6.3-6.3c-.2 0-.2-.2-.1-.3z"
}));
/* harmony default export */ var library_external = (external);
/* harmony default export */ var library_symbol = (symbol);
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: external ["wp","router"]
var external_wp_router_namespaceObject = window["wp"]["router"];
;// CONCATENATED MODULE: external ["wp","coreData"]
var external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/hooks.js
/**
* WordPress dependencies
*/
function useIsTemplatesAccessible() {
return (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_coreData_namespaceObject.store).canUser('read', 'templates'), []);
}
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"]
var 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 know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.', '@wordpress/core-commands');
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/admin-navigation-commands.js
/**
@@ -87,7 +118,22 @@ const external = (0,external_wp_element_namespaceObject.createElement)(external_
/**
* Internal dependencies
*/
const {
useHistory
} = unlock(external_wp_router_namespaceObject.privateApis);
function useAdminNavigationCommands() {
const history = useHistory();
const isTemplatesAccessible = useIsTemplatesAccessible();
const isBlockBasedTheme = useIsBlockBasedTheme();
const isSiteEditor = (0,external_wp_url_namespaceObject.getPath)(window.location.href)?.includes('site-editor.php');
(0,external_wp_commands_namespaceObject.useCommand)({
name: 'core/add-new-post',
label: (0,external_wp_i18n_namespaceObject.__)('Add new post'),
@@ -106,21 +152,30 @@ function useAdminNavigationCommands() {
});
(0,external_wp_commands_namespaceObject.useCommand)({
name: 'core/manage-reusable-blocks',
label: (0,external_wp_i18n_namespaceObject.__)('Manage all of my patterns'),
callback: () => {
document.location.href = 'edit.php?post_type=wp_block';
},
icon: library_external
label: (0,external_wp_i18n_namespaceObject.__)('Patterns'),
icon: library_symbol,
callback: ({
close
}) => {
if (isTemplatesAccessible && isBlockBasedTheme) {
const args = {
path: '/patterns'
};
if (isSiteEditor) {
history.push(args);
} else {
document.location = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
}
close();
} else {
document.location.href = 'edit.php?post_type=wp_block';
}
}
});
}
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","coreData"]
var external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/post.js
/**
* WordPress dependencies
*/
@@ -135,7 +190,6 @@ const post = (0,external_wp_element_namespaceObject.createElement)(external_wp_p
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/page.js
/**
* WordPress dependencies
*/
@@ -150,7 +204,6 @@ const page = (0,external_wp_element_namespaceObject.createElement)(external_wp_p
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/layout.js
/**
* WordPress dependencies
*/
@@ -165,7 +218,6 @@ const layout = (0,external_wp_element_namespaceObject.createElement)(external_wp
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/symbol-filled.js
/**
* WordPress dependencies
*/
@@ -180,7 +232,6 @@ const symbolFilled = (0,external_wp_element_namespaceObject.createElement)(exter
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/navigation.js
/**
* WordPress dependencies
*/
@@ -195,7 +246,6 @@ const navigation = (0,external_wp_element_namespaceObject.createElement)(externa
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/styles.js
/**
* WordPress dependencies
*/
@@ -208,21 +258,26 @@ const styles = (0,external_wp_element_namespaceObject.createElement)(external_wp
}));
/* harmony default export */ var library_styles = (styles);
;// CONCATENATED MODULE: external ["wp","router"]
var external_wp_router_namespaceObject = window["wp"]["router"];
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: external ["wp","privateApis"]
var 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 know using unstable features means my plugin or theme will inevitably break on the next WordPress release.', '@wordpress/core-commands');
;// 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) {
return [];
}
if (!search) {
return records;
}
const priority = [];
const nonPriority = [];
for (let i = 0; i < records.length; i++) {
const record = records[i];
if (record?.title?.raw?.toLowerCase()?.includes(search?.toLowerCase())) {
priority.push(record);
} else {
nonPriority.push(record);
}
}
return priority.concat(nonPriority);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/core-commands/build-module/site-editor-navigation-commands.js
/**
@@ -236,13 +291,16 @@ const {
/**
* Internal dependencies
*/
const {
useHistory
useHistory: site_editor_navigation_commands_useHistory,
useLocation
} = unlock(external_wp_router_namespaceObject.privateApis);
const icons = {
post: library_post,
@@ -250,12 +308,11 @@ const icons = {
wp_template: library_layout,
wp_template_part: symbol_filled
};
const getNavigationCommandLoaderPerPostType = postType => function useNavigationCommandLoader({
search
}) {
const history = useHistory();
const supportsSearch = !['wp_template', 'wp_template_part'].includes(postType);
const history = site_editor_navigation_commands_useHistory();
const isBlockBasedTheme = useIsBlockBasedTheme();
const {
records,
isLoading
@@ -263,30 +320,47 @@ const getNavigationCommandLoaderPerPostType = postType => function useNavigation
const {
getEntityRecords
} = select(external_wp_coreData_namespaceObject.store);
const query = supportsSearch ? {
const query = {
search: !!search ? search : undefined,
per_page: 10,
orderby: search ? 'relevance' : 'date',
status: ['publish', 'future', 'draft', 'pending', 'private']
} : {
per_page: -1
};
return {
records: getEntityRecords('postType', postType, query),
isLoading: !select(external_wp_coreData_namespaceObject.store).hasFinishedResolution('getEntityRecords', ['postType', postType, query])
};
}, [supportsSearch, search]);
}, [search]);
const commands = (0,external_wp_element_namespaceObject.useMemo)(() => {
return (records !== null && records !== void 0 ? records : []).slice(0, 10).map(record => {
return (records !== null && records !== void 0 ? records : []).map(record => {
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)'),
icon: icons[postType]
};
if (postType === 'post' || postType === 'page' && !isBlockBasedTheme) {
return {
...command,
callback: ({
close
}) => {
const args = {
post: record.id,
action: 'edit'
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('post.php', args);
document.location = targetUrl;
close();
}
};
}
const isSiteEditor = (0,external_wp_url_namespaceObject.getPath)(window.location.href)?.includes('site-editor.php');
const extraArgs = isSiteEditor ? {
canvas: (0,external_wp_url_namespaceObject.getQueryArg)(window.location.href, 'canvas')
} : {};
return {
name: postType + '-' + record.id,
searchLabel: record.title?.rendered + ' ' + record.id,
label: record.title?.rendered ? record.title?.rendered : (0,external_wp_i18n_namespaceObject.__)('(no title)'),
icon: icons[postType],
...command,
callback: ({
close
}) => {
@@ -296,37 +370,109 @@ const getNavigationCommandLoaderPerPostType = postType => function useNavigation
...extraArgs
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
};
});
}, [records, history]);
}, [records, isBlockBasedTheme, history]);
return {
commands,
isLoading
};
};
const getNavigationCommandLoaderPerTemplate = templateType => function useNavigationCommandLoader({
search
}) {
const history = site_editor_navigation_commands_useHistory();
const location = useLocation();
const isPatternsPage = location?.params?.path === '/patterns' || location?.params?.postType === 'wp_block';
const didAccessPatternsPage = !!location?.params?.didAccessPatternsPage;
const isBlockBasedTheme = useIsBlockBasedTheme();
const {
records,
isLoading
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEntityRecords
} = select(external_wp_coreData_namespaceObject.store);
const query = {
per_page: -1
};
return {
records: getEntityRecords('postType', templateType, query),
isLoading: !select(external_wp_coreData_namespaceObject.store).hasFinishedResolution('getEntityRecords', ['postType', templateType, query])
};
}, []);
/*
* wp_template and wp_template_part endpoints do not support per_page or orderby parameters.
* We need to sort the results based on the search query to avoid removing relevant
* records below using .slice().
*/
const orderedRecords = (0,external_wp_element_namespaceObject.useMemo)(() => {
return orderEntityRecordsBySearch(records, search).slice(0, 10);
}, [records, search]);
const commands = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!isBlockBasedTheme && !templateType === 'wp_template_part') {
return [];
}
return orderedRecords.map(record => {
const isSiteEditor = (0,external_wp_url_namespaceObject.getPath)(window.location.href)?.includes('site-editor.php');
const extraArgs = isSiteEditor ? {
canvas: (0,external_wp_url_namespaceObject.getQueryArg)(window.location.href, 'canvas')
} : {};
return {
name: templateType + '-' + record.id,
searchLabel: record.title?.rendered + ' ' + record.id,
label: record.title?.rendered ? record.title?.rendered : (0,external_wp_i18n_namespaceObject.__)('(no title)'),
icon: icons[templateType],
callback: ({
close
}) => {
const args = {
postType: templateType,
postId: record.id,
didAccessPatternsPage: !isBlockBasedTheme && (isPatternsPage || didAccessPatternsPage) ? 1 : undefined,
...extraArgs
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
};
});
}, [isBlockBasedTheme, orderedRecords, history]);
return {
commands,
isLoading
};
};
const usePageNavigationCommandLoader = getNavigationCommandLoaderPerPostType('page');
const usePostNavigationCommandLoader = getNavigationCommandLoaderPerPostType('post');
const useTemplateNavigationCommandLoader = getNavigationCommandLoaderPerPostType('wp_template');
const useTemplatePartNavigationCommandLoader = getNavigationCommandLoaderPerPostType('wp_template_part');
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 isTemplatesAccessible = useIsTemplatesAccessible();
const isBlockBasedTheme = useIsBlockBasedTheme();
const commands = (0,external_wp_element_namespaceObject.useMemo)(() => {
const result = [];
if (!isTemplatesAccessible || !isBlockBasedTheme) {
return result;
}
result.push({
name: 'core/edit-site/open-navigation',
label: (0,external_wp_i18n_namespaceObject.__)('Open navigation'),
label: (0,external_wp_i18n_namespaceObject.__)('Navigation'),
icon: library_navigation,
callback: ({
close
@@ -335,40 +481,17 @@ function useSiteEditorBasicNavigationCommands() {
path: '/navigation'
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
});
result.push({
name: 'core/edit-site/open-pages',
label: (0,external_wp_i18n_namespaceObject.__)('Open pages'),
icon: library_page,
callback: ({
close
}) => {
const args = {
path: '/page'
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
});
result.push({
name: 'core/edit-site/open-style-variations',
label: (0,external_wp_i18n_namespaceObject.__)('Open style variations'),
name: 'core/edit-site/open-styles',
label: (0,external_wp_i18n_namespaceObject.__)('Styles'),
icon: library_styles,
callback: ({
close
@@ -377,19 +500,36 @@ function useSiteEditorBasicNavigationCommands() {
path: '/wp_global_styles'
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
});
result.push({
name: 'core/edit-site/open-pages',
label: (0,external_wp_i18n_namespaceObject.__)('Pages'),
icon: library_page,
callback: ({
close
}) => {
const args = {
path: '/page'
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
});
result.push({
name: 'core/edit-site/open-templates',
label: (0,external_wp_i18n_namespaceObject.__)('Open templates'),
label: (0,external_wp_i18n_namespaceObject.__)('Templates'),
icon: library_layout,
callback: ({
close
@@ -398,45 +538,21 @@ function useSiteEditorBasicNavigationCommands() {
path: '/wp_template'
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
});
result.push({
name: 'core/edit-site/open-template-parts',
label: (0,external_wp_i18n_namespaceObject.__)('Open library'),
icon: symbol_filled,
callback: ({
close
}) => {
const args = {
path: '/patterns'
};
const targetUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', args);
if (isSiteEditor) {
history.push(args);
} else {
document.location = targetUrl;
}
close();
}
});
return result;
}, [history, isSiteEditor]);
}, [history, isSiteEditor, isTemplatesAccessible, isBlockBasedTheme]);
return {
commands,
isLoading: false
};
}
function useSiteEditorNavigationCommands() {
(0,external_wp_commands_namespaceObject.useCommandLoader)({
name: 'core/edit-site/navigate-pages',
@@ -468,12 +584,10 @@ function useSiteEditorNavigationCommands() {
function useCommands() {
useAdminNavigationCommands();
useSiteEditorNavigationCommands();
}
const privateApis = {};
lock(privateApis, {
useCommands
File diff suppressed because one or more lines are too long
+1203 -1183
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+11 -14
View File
@@ -51,12 +51,12 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"__unstableAwaitPromise": function() { return /* binding */ __unstableAwaitPromise; },
"apiFetch": function() { return /* binding */ apiFetch; },
"controls": function() { return /* binding */ controls; },
"dispatch": function() { return /* binding */ dispatch; },
"select": function() { return /* binding */ build_module_select; },
"syncSelect": function() { return /* binding */ syncSelect; }
__unstableAwaitPromise: function() { return /* binding */ __unstableAwaitPromise; },
apiFetch: function() { return /* binding */ apiFetch; },
controls: function() { return /* binding */ controls; },
dispatch: function() { return /* binding */ dispatch; },
select: function() { return /* binding */ build_module_select; },
syncSelect: function() { return /* binding */ syncSelect; }
});
;// CONCATENATED MODULE: external ["wp","apiFetch"]
@@ -74,7 +74,6 @@ var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external
/**
* Dispatches a control action for triggering an api fetch call.
*
@@ -100,6 +99,7 @@ function apiFetch(request) {
request
};
}
/**
* Control for resolving a selector in a registered data store.
* Alias for the `resolveSelect` built-in control in the `@wordpress/data` package.
@@ -108,7 +108,6 @@ function apiFetch(request) {
* @param selectorName The selector name.
* @param args Arguments passed without change to the `@wordpress/data` control.
*/
function build_module_select(storeNameOrDescriptor, selectorName, ...args) {
external_wp_deprecated_default()('`select` control in `@wordpress/data-controls`', {
since: '5.7',
@@ -116,6 +115,7 @@ function build_module_select(storeNameOrDescriptor, selectorName, ...args) {
});
return external_wp_data_namespaceObject.controls.resolveSelect(storeNameOrDescriptor, selectorName, ...args);
}
/**
* Control for calling a selector in a registered data store.
* Alias for the `select` built-in control in the `@wordpress/data` package.
@@ -124,7 +124,6 @@ function build_module_select(storeNameOrDescriptor, selectorName, ...args) {
* @param selectorName The selector name.
* @param args Arguments passed without change to the `@wordpress/data` control.
*/
function syncSelect(storeNameOrDescriptor, selectorName, ...args) {
external_wp_deprecated_default()('`syncSelect` control in `@wordpress/data-controls`', {
since: '5.7',
@@ -132,6 +131,7 @@ function syncSelect(storeNameOrDescriptor, selectorName, ...args) {
});
return external_wp_data_namespaceObject.controls.select(storeNameOrDescriptor, selectorName, ...args);
}
/**
* Control for dispatching an action in a registered data store.
* Alias for the `dispatch` control in the `@wordpress/data` package.
@@ -140,7 +140,6 @@ function syncSelect(storeNameOrDescriptor, selectorName, ...args) {
* @param actionName The action name.
* @param args Arguments passed without change to the `@wordpress/data` control.
*/
function dispatch(storeNameOrDescriptor, actionName, ...args) {
external_wp_deprecated_default()('`dispatch` control in `@wordpress/data-controls`', {
since: '5.7',
@@ -148,6 +147,7 @@ function dispatch(storeNameOrDescriptor, actionName, ...args) {
});
return external_wp_data_namespaceObject.controls.dispatch(storeNameOrDescriptor, actionName, ...args);
}
/**
* Dispatches a control action for awaiting on a promise to be resolved.
*
@@ -167,13 +167,13 @@ function dispatch(storeNameOrDescriptor, actionName, ...args) {
*
* @return {Object} The control descriptor.
*/
const __unstableAwaitPromise = function (promise) {
return {
type: 'AWAIT_PROMISE',
promise
};
};
/**
* The default export is what you use to register the controls with your custom
* store.
@@ -201,18 +201,15 @@ const __unstableAwaitPromise = function (promise) {
* @return {Object} An object for registering the default controls with the
* store.
*/
const controls = {
AWAIT_PROMISE: ({
promise
}) => promise,
API_FETCH({
request
}) {
return external_wp_apiFetch_default()(request);
}
};
(window.wp = window.wp || {}).dataControls = __webpack_exports__;
+600 -449
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
File diff suppressed because one or more lines are too long
+76 -100
View File
File diff suppressed because one or more lines are too long
+3 -3
View File
File diff suppressed because one or more lines are too long
+8 -6
View File
@@ -38,14 +38,15 @@ var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
* WordPress dependencies
*/
/**
* Object map tracking messages which have been logged, for use in ensuring a
* message is only logged once.
*
* @type {Record<string, true | undefined>}
*/
const logged = Object.create(null);
/**
* Logs a message to notify developers about a deprecated feature.
*
@@ -73,7 +74,6 @@ const logged = Object.create(null);
* // Logs: 'Eating meat is deprecated since version 2019.01.01 and will be removed from the earth in version 2020.01.01. Please use vegetables instead. Note: You may find it beneficial to transition gradually.'
* ```
*/
function deprecated(feature, options = {}) {
const {
since,
@@ -89,11 +89,13 @@ function deprecated(feature, options = {}) {
const useInsteadMessage = alternative ? ` Please use ${alternative} instead.` : '';
const linkMessage = link ? ` See: ${link}` : '';
const hintMessage = hint ? ` Note: ${hint}` : '';
const message = `${feature} is deprecated${sinceMessage}${versionMessage}.${useInsteadMessage}${linkMessage}${hintMessage}`; // Skip if already logged.
const message = `${feature} is deprecated${sinceMessage}${versionMessage}.${useInsteadMessage}${linkMessage}${hintMessage}`;
// Skip if already logged.
if (message in logged) {
return;
}
/**
* Fires whenever a deprecated feature is encountered
*
@@ -107,13 +109,13 @@ function deprecated(feature, options = {}) {
* @param {?string} options.hint Additional message to help transition away from the deprecated feature.
* @param {?string} message Message sent to console.warn
*/
(0,external_wp_hooks_namespaceObject.doAction)('deprecated', feature, options, message);
(0,external_wp_hooks_namespaceObject.doAction)('deprecated', feature, options, message); // eslint-disable-next-line no-console
// eslint-disable-next-line no-console
console.warn(message);
logged[message] = true;
}
/** @typedef {import('utility-types').NonUndefined<Parameters<typeof deprecated>[1]>} DeprecatedOptions */
(window.wp = window.wp || {}).deprecated = __webpack_exports__["default"];
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4 -4
View File
@@ -60,14 +60,14 @@ function domReady(callback) {
if (typeof document === 'undefined') {
return;
}
if (document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly.
if (document.readyState === 'complete' ||
// DOMContentLoaded + Images/Styles/etc loaded, so we call directly.
document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly.
) {
return void callback();
} // DOMContentLoaded has not fired yet, delay callback until then.
}
// DOMContentLoaded has not fired yet, delay callback until then.
document.addEventListener('DOMContentLoaded', callback);
}
+237 -336
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
File diff suppressed because one or more lines are too long
+1032 -1322
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+17460 -4187
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+359 -545
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+1552 -2284
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+110 -191
View File
@@ -87,50 +87,50 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"Children": function() { return /* reexport */ external_React_namespaceObject.Children; },
"Component": function() { return /* reexport */ external_React_namespaceObject.Component; },
"Fragment": function() { return /* reexport */ external_React_namespaceObject.Fragment; },
"Platform": function() { return /* reexport */ platform; },
"RawHTML": function() { return /* reexport */ RawHTML; },
"StrictMode": function() { return /* reexport */ external_React_namespaceObject.StrictMode; },
"Suspense": function() { return /* reexport */ external_React_namespaceObject.Suspense; },
"cloneElement": function() { return /* reexport */ external_React_namespaceObject.cloneElement; },
"concatChildren": function() { return /* reexport */ concatChildren; },
"createContext": function() { return /* reexport */ external_React_namespaceObject.createContext; },
"createElement": function() { return /* reexport */ external_React_namespaceObject.createElement; },
"createInterpolateElement": function() { return /* reexport */ create_interpolate_element; },
"createPortal": function() { return /* reexport */ external_ReactDOM_.createPortal; },
"createRef": function() { return /* reexport */ external_React_namespaceObject.createRef; },
"createRoot": function() { return /* reexport */ client/* createRoot */.s; },
"findDOMNode": function() { return /* reexport */ external_ReactDOM_.findDOMNode; },
"flushSync": function() { return /* reexport */ external_ReactDOM_.flushSync; },
"forwardRef": function() { return /* reexport */ external_React_namespaceObject.forwardRef; },
"hydrate": function() { return /* reexport */ external_ReactDOM_.hydrate; },
"hydrateRoot": function() { return /* reexport */ client/* hydrateRoot */.a; },
"isEmptyElement": function() { return /* reexport */ isEmptyElement; },
"isValidElement": function() { return /* reexport */ external_React_namespaceObject.isValidElement; },
"lazy": function() { return /* reexport */ external_React_namespaceObject.lazy; },
"memo": function() { return /* reexport */ external_React_namespaceObject.memo; },
"render": function() { return /* reexport */ external_ReactDOM_.render; },
"renderToString": function() { return /* reexport */ serialize; },
"startTransition": function() { return /* reexport */ external_React_namespaceObject.startTransition; },
"switchChildrenNodeName": function() { return /* reexport */ switchChildrenNodeName; },
"unmountComponentAtNode": function() { return /* reexport */ external_ReactDOM_.unmountComponentAtNode; },
"useCallback": function() { return /* reexport */ external_React_namespaceObject.useCallback; },
"useContext": function() { return /* reexport */ external_React_namespaceObject.useContext; },
"useDebugValue": function() { return /* reexport */ external_React_namespaceObject.useDebugValue; },
"useDeferredValue": function() { return /* reexport */ external_React_namespaceObject.useDeferredValue; },
"useEffect": function() { return /* reexport */ external_React_namespaceObject.useEffect; },
"useId": function() { return /* reexport */ external_React_namespaceObject.useId; },
"useImperativeHandle": function() { return /* reexport */ external_React_namespaceObject.useImperativeHandle; },
"useInsertionEffect": function() { return /* reexport */ external_React_namespaceObject.useInsertionEffect; },
"useLayoutEffect": function() { return /* reexport */ external_React_namespaceObject.useLayoutEffect; },
"useMemo": function() { return /* reexport */ external_React_namespaceObject.useMemo; },
"useReducer": function() { return /* reexport */ external_React_namespaceObject.useReducer; },
"useRef": function() { return /* reexport */ external_React_namespaceObject.useRef; },
"useState": function() { return /* reexport */ external_React_namespaceObject.useState; },
"useSyncExternalStore": function() { return /* reexport */ external_React_namespaceObject.useSyncExternalStore; },
"useTransition": function() { return /* reexport */ external_React_namespaceObject.useTransition; }
Children: function() { return /* reexport */ external_React_namespaceObject.Children; },
Component: function() { return /* reexport */ external_React_namespaceObject.Component; },
Fragment: function() { return /* reexport */ external_React_namespaceObject.Fragment; },
Platform: function() { return /* reexport */ platform; },
RawHTML: function() { return /* reexport */ RawHTML; },
StrictMode: function() { return /* reexport */ external_React_namespaceObject.StrictMode; },
Suspense: function() { return /* reexport */ external_React_namespaceObject.Suspense; },
cloneElement: function() { return /* reexport */ external_React_namespaceObject.cloneElement; },
concatChildren: function() { return /* reexport */ concatChildren; },
createContext: function() { return /* reexport */ external_React_namespaceObject.createContext; },
createElement: function() { return /* reexport */ external_React_namespaceObject.createElement; },
createInterpolateElement: function() { return /* reexport */ create_interpolate_element; },
createPortal: function() { return /* reexport */ external_ReactDOM_.createPortal; },
createRef: function() { return /* reexport */ external_React_namespaceObject.createRef; },
createRoot: function() { return /* reexport */ client/* createRoot */.s; },
findDOMNode: function() { return /* reexport */ external_ReactDOM_.findDOMNode; },
flushSync: function() { return /* reexport */ external_ReactDOM_.flushSync; },
forwardRef: function() { return /* reexport */ external_React_namespaceObject.forwardRef; },
hydrate: function() { return /* reexport */ external_ReactDOM_.hydrate; },
hydrateRoot: function() { return /* reexport */ client/* hydrateRoot */.a; },
isEmptyElement: function() { return /* reexport */ isEmptyElement; },
isValidElement: function() { return /* reexport */ external_React_namespaceObject.isValidElement; },
lazy: function() { return /* reexport */ external_React_namespaceObject.lazy; },
memo: function() { return /* reexport */ external_React_namespaceObject.memo; },
render: function() { return /* reexport */ external_ReactDOM_.render; },
renderToString: function() { return /* reexport */ serialize; },
startTransition: function() { return /* reexport */ external_React_namespaceObject.startTransition; },
switchChildrenNodeName: function() { return /* reexport */ switchChildrenNodeName; },
unmountComponentAtNode: function() { return /* reexport */ external_ReactDOM_.unmountComponentAtNode; },
useCallback: function() { return /* reexport */ external_React_namespaceObject.useCallback; },
useContext: function() { return /* reexport */ external_React_namespaceObject.useContext; },
useDebugValue: function() { return /* reexport */ external_React_namespaceObject.useDebugValue; },
useDeferredValue: function() { return /* reexport */ external_React_namespaceObject.useDeferredValue; },
useEffect: function() { return /* reexport */ external_React_namespaceObject.useEffect; },
useId: function() { return /* reexport */ external_React_namespaceObject.useId; },
useImperativeHandle: function() { return /* reexport */ external_React_namespaceObject.useImperativeHandle; },
useInsertionEffect: function() { return /* reexport */ external_React_namespaceObject.useInsertionEffect; },
useLayoutEffect: function() { return /* reexport */ external_React_namespaceObject.useLayoutEffect; },
useMemo: function() { return /* reexport */ external_React_namespaceObject.useMemo; },
useReducer: function() { return /* reexport */ external_React_namespaceObject.useReducer; },
useRef: function() { return /* reexport */ external_React_namespaceObject.useRef; },
useState: function() { return /* reexport */ external_React_namespaceObject.useState; },
useSyncExternalStore: function() { return /* reexport */ external_React_namespaceObject.useSyncExternalStore; },
useTransition: function() { return /* reexport */ external_React_namespaceObject.useTransition; }
});
;// CONCATENATED MODULE: external "React"
@@ -140,9 +140,11 @@ var external_React_namespaceObject = window["React"];
* Internal dependencies
*/
/** @typedef {import('./react').WPElement} WPElement */
let indoc, offset, output, stack;
/**
* Matches tags in the localized string
*
@@ -158,8 +160,8 @@ let indoc, offset, output, stack;
*
* @type {RegExp}
*/
const tokenizer = /<(\/)?(\w+)\s*(\/)?>/g;
/**
* The stack frame tracking parse progress.
*
@@ -199,7 +201,6 @@ const tokenizer = /<(\/)?(\w+)\s*(\/)?>/g;
*
* @return {Frame} The stack frame tracking parse progress.
*/
function createFrame(element, tokenStart, tokenLength, prevOffset, leadingTextStart) {
return {
element,
@@ -210,6 +211,7 @@ function createFrame(element, tokenStart, tokenLength, prevOffset, leadingTextSt
children: []
};
}
/**
* This function creates an interpolated element from a passed in string with
* specific tags matching how the string should be converted to an element via
@@ -237,24 +239,21 @@ function createFrame(element, tokenStart, tokenLength, prevOffset, leadingTextSt
* @throws {TypeError}
* @return {WPElement} A wp element.
*/
const createInterpolateElement = (interpolatedString, conversionMap) => {
indoc = interpolatedString;
offset = 0;
output = [];
stack = [];
tokenizer.lastIndex = 0;
if (!isValidConversionMap(conversionMap)) {
throw new TypeError('The conversionMap provided is not valid. It must be an object with values that are WPElements');
}
do {// twiddle our thumbs
do {
// twiddle our thumbs
} while (proceed(conversionMap));
return (0,external_React_namespaceObject.createElement)(external_React_namespaceObject.Fragment, null, ...output);
};
/**
* Validate conversion map.
*
@@ -267,13 +266,12 @@ const createInterpolateElement = (interpolatedString, conversionMap) => {
*
* @return {boolean} True means the map is valid.
*/
const isValidConversionMap = conversionMap => {
const isObject = typeof conversionMap === 'object';
const values = isObject && Object.values(conversionMap);
return isObject && values.length && values.every(element => (0,external_React_namespaceObject.isValidElement)(element));
};
/**
* This is the iterator over the matches in the string.
*
@@ -283,19 +281,15 @@ const isValidConversionMap = conversionMap => {
*
* @return {boolean} true for continuing to iterate, false for finished.
*/
function proceed(conversionMap) {
const next = nextToken();
const [tokenType, name, startOffset, tokenLength] = next;
const stackDepth = stack.length;
const leadingTextStart = startOffset > offset ? offset : null;
if (!conversionMap[name]) {
addText();
return false;
}
switch (tokenType) {
case 'no-more-tokens':
if (stackDepth !== 0) {
@@ -305,41 +299,36 @@ function proceed(conversionMap) {
} = stack.pop();
output.push(indoc.substr(stackLeadingText, tokenStart));
}
addText();
return false;
case 'self-closed':
if (0 === stackDepth) {
if (null !== leadingTextStart) {
output.push(indoc.substr(leadingTextStart, startOffset - leadingTextStart));
}
output.push(conversionMap[name]);
offset = startOffset + tokenLength;
return true;
} // Otherwise we found an inner element.
}
// Otherwise we found an inner element.
addChild(createFrame(conversionMap[name], startOffset, tokenLength));
offset = startOffset + tokenLength;
return true;
case 'opener':
stack.push(createFrame(conversionMap[name], startOffset, tokenLength, startOffset + tokenLength, leadingTextStart));
offset = startOffset + tokenLength;
return true;
case 'closer':
// If we're not nesting then this is easy - close the block.
if (1 === stackDepth) {
closeOuterElement(startOffset);
offset = startOffset + tokenLength;
return true;
} // Otherwise we're nested and we have to close out the current
}
// Otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent.
const stackTop = stack.pop();
const text = indoc.substr(stackTop.prevOffset, startOffset - stackTop.prevOffset);
stackTop.children.push(text);
@@ -349,12 +338,12 @@ function proceed(conversionMap) {
addChild(frame);
offset = startOffset + tokenLength;
return true;
default:
addText();
return false;
}
}
/**
* Grabs the next token match in the string and returns it's details.
*
@@ -362,29 +351,24 @@ function proceed(conversionMap) {
*
* @return {Array} An array of details for the token matched.
*/
function nextToken() {
const matches = tokenizer.exec(indoc); // We have no more tokens.
const matches = tokenizer.exec(indoc);
// We have no more tokens.
if (null === matches) {
return ['no-more-tokens'];
}
const startedAt = matches.index;
const [match, isClosing, name, isSelfClosed] = matches;
const length = match.length;
if (isSelfClosed) {
return ['self-closed', name, startedAt, length];
}
if (isClosing) {
return ['closer', name, startedAt, length];
}
return ['opener', name, startedAt, length];
}
/**
* Pushes text extracted from the indoc string to the output stack given the
* current rawLength value and offset (if rawLength is provided ) or the
@@ -392,17 +376,14 @@ function nextToken() {
*
* @private
*/
function addText() {
const length = indoc.length - offset;
if (0 === length) {
return;
}
output.push(indoc.substr(offset, length));
}
/**
* Pushes a child element to the associated parent element's children for the
* parent currently active in the stack.
@@ -412,8 +393,6 @@ function addText() {
* @param {Frame} frame The Frame containing the child element and it's
* token information.
*/
function addChild(frame) {
const {
element,
@@ -424,14 +403,13 @@ function addChild(frame) {
} = frame;
const parent = stack[stack.length - 1];
const text = indoc.substr(parent.prevOffset, tokenStart - parent.prevOffset);
if (text) {
parent.children.push(text);
}
parent.children.push((0,external_React_namespaceObject.cloneElement)(element, null, ...children));
parent.prevOffset = prevOffset ? prevOffset : tokenStart + tokenLength;
}
/**
* This is called for closing tags. It creates the element currently active in
* the stack.
@@ -444,8 +422,6 @@ function addChild(frame) {
* helps capture any remaining nested text nodes in
* the element.
*/
function closeOuterElement(endOffset) {
const {
element,
@@ -455,18 +431,14 @@ function closeOuterElement(endOffset) {
children
} = stack.pop();
const text = endOffset ? indoc.substr(prevOffset, endOffset - prevOffset) : indoc.substr(prevOffset);
if (text) {
children.push(text);
}
if (null !== leadingTextStart) {
output.push(indoc.substr(leadingTextStart, tokenStart - leadingTextStart));
}
output.push((0,external_React_namespaceObject.cloneElement)(element, null, ...children));
}
/* harmony default export */ var create_interpolate_element = (createInterpolateElement);
;// CONCATENATED MODULE: ./node_modules/@wordpress/element/build-module/react.js
@@ -475,6 +447,7 @@ function closeOuterElement(endOffset) {
*/
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
/**
* Object containing a React element.
*
@@ -686,7 +659,6 @@ function closeOuterElement(endOffset) {
*
* @return {Array} The concatenated value.
*/
function concatChildren(...childrenArguments) {
return childrenArguments.reduce((accumulator, children, i) => {
external_React_namespaceObject.Children.forEach(children, (child, j) => {
@@ -695,12 +667,12 @@ function concatChildren(...childrenArguments) {
key: [i, j].join()
});
}
accumulator.push(child);
});
return accumulator;
}, []);
}
/**
* Switches the nodeName of all the elements in the children object.
*
@@ -709,7 +681,6 @@ function concatChildren(...childrenArguments) {
*
* @return {?Object} The updated children object.
*/
function switchChildrenNodeName(children, nodeName) {
return children && external_React_namespaceObject.Children.map(children, (elt, index) => {
if (typeof elt?.valueOf() === 'string') {
@@ -717,7 +688,6 @@ function switchChildrenNodeName(children, nodeName) {
key: index
}, elt);
}
const {
children: childrenProp,
...props
@@ -739,6 +709,7 @@ var client = __webpack_require__(4470);
*/
/**
* Creates a portal into which a component can be rendered.
*
@@ -804,7 +775,6 @@ var client = __webpack_require__(4470);
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/element/build-module/utils.js
/**
* Checks if the provided WP element is empty.
@@ -816,11 +786,9 @@ const isEmptyElement = element => {
if (typeof element === 'number') {
return false;
}
if (typeof element?.valueOf() === 'string' || Array.isArray(element)) {
return !element.length;
}
return !element;
};
@@ -857,7 +825,6 @@ const Platform = {
* } );
* ```
*/
/* harmony default export */ var platform = (Platform);
;// CONCATENATED MODULE: ./node_modules/is-plain-object/dist/is-plain-object.mjs
@@ -1193,7 +1160,7 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object") throw new TypeError("Object expected.");
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
@@ -1372,6 +1339,7 @@ var external_wp_escapeHtml_namespaceObject = window["wp"]["escapeHtml"];
* Internal dependencies
*/
/** @typedef {{children: string} & import('react').ComponentPropsWithoutRef<'div'>} RawHTMLProps */
/**
@@ -1386,20 +1354,21 @@ var external_wp_escapeHtml_namespaceObject = window["wp"]["escapeHtml"];
*
* @return {JSX.Element} Dangerously-rendering component.
*/
function RawHTML({
children,
...props
}) {
let rawHtml = ''; // Cast children as an array, and concatenate each element if it is a string.
let rawHtml = '';
// Cast children as an array, and concatenate each element if it is a string.
external_React_namespaceObject.Children.toArray(children).forEach(child => {
if (typeof child === 'string' && child.trim() !== '') {
rawHtml += child;
}
}); // The `div` wrapper will be stripped by the `renderElement` serializer in
// `./serialize.js` unless there are non-children props present.
});
// The `div` wrapper will be stripped by the `renderElement` serializer in
// `./serialize.js` unless there are non-children props present.
return (0,external_React_namespaceObject.createElement)('div', {
dangerouslySetInnerHTML: {
__html: rawHtml
@@ -1441,6 +1410,7 @@ function RawHTML({
*/
/**
* WordPress dependencies
*/
@@ -1461,20 +1431,21 @@ const {
const ForwardRef = (0,external_React_namespaceObject.forwardRef)(() => {
return null;
});
/**
* Valid attribute types.
*
* @type {Set<string>}
*/
const ATTRIBUTES_TYPES = new Set(['string', 'boolean', 'number']);
/**
* Element tags which can be self-closing.
*
* @type {Set<string>}
*/
const SELF_CLOSING_TAGS = new Set(['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
/**
* Boolean attributes are attributes whose presence as being assigned is
* meaningful, even if only empty.
@@ -1490,8 +1461,8 @@ const SELF_CLOSING_TAGS = new Set(['area', 'base', 'br', 'col', 'command', 'embe
*
* @type {Set<string>}
*/
const BOOLEAN_ATTRIBUTES = new Set(['allowfullscreen', 'allowpaymentrequest', 'allowusermedia', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled', 'download', 'formnovalidate', 'hidden', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline', 'readonly', 'required', 'reversed', 'selected', 'typemustmatch']);
/**
* Enumerated attributes are attributes which must be of a specific value form.
* Like boolean attributes, these are meaningful if specified, even if not of a
@@ -1512,8 +1483,8 @@ const BOOLEAN_ATTRIBUTES = new Set(['allowfullscreen', 'allowpaymentrequest', 'a
*
* @type {Set<string>}
*/
const ENUMERATED_ATTRIBUTES = new Set(['autocapitalize', 'autocomplete', 'charset', 'contenteditable', 'crossorigin', 'decoding', 'dir', 'draggable', 'enctype', 'formenctype', 'formmethod', 'http-equiv', 'inputmode', 'kind', 'method', 'preload', 'scope', 'shape', 'spellcheck', 'translate', 'type', 'wrap']);
/**
* Set of CSS style properties which support assignment of unitless numbers.
* Used in rendering of style properties, where `px` unit is assumed unless
@@ -1532,8 +1503,8 @@ const ENUMERATED_ATTRIBUTES = new Set(['autocapitalize', 'autocomplete', 'charse
*
* @type {Set<string>}
*/
const CSS_PROPERTIES_SUPPORTS_UNITLESS = new Set(['animation', 'animationIterationCount', 'baselineShift', 'borderImageOutset', 'borderImageSlice', 'borderImageWidth', 'columnCount', 'cx', 'cy', 'fillOpacity', 'flexGrow', 'flexShrink', 'floodOpacity', 'fontWeight', 'gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart', 'lineHeight', 'opacity', 'order', 'orphans', 'r', 'rx', 'ry', 'shapeImageThreshold', 'stopOpacity', 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'tabSize', 'widows', 'x', 'y', 'zIndex', 'zoom']);
/**
* Returns true if the specified string is prefixed by one of an array of
* possible prefixes.
@@ -1543,10 +1514,10 @@ const CSS_PROPERTIES_SUPPORTS_UNITLESS = new Set(['animation', 'animationIterati
*
* @return {boolean} Whether string has prefix.
*/
function hasPrefix(string, prefixes) {
return prefixes.some(prefix => string.indexOf(prefix) === 0);
}
/**
* Returns true if the given prop name should be ignored in attributes
* serialization, or false otherwise.
@@ -1555,10 +1526,10 @@ function hasPrefix(string, prefixes) {
*
* @return {boolean} Whether attribute should be ignored.
*/
function isInternalAttribute(attribute) {
return 'key' === attribute || 'children' === attribute;
}
/**
* Returns the normal form of the element's attribute value for HTML.
*
@@ -1567,14 +1538,11 @@ function isInternalAttribute(attribute) {
*
* @return {*} Normalized attribute value.
*/
function getNormalAttributeValue(attribute, value) {
switch (attribute) {
case 'style':
return renderStyle(value);
}
return value;
}
/**
@@ -1583,34 +1551,33 @@ function getNormalAttributeValue(attribute, value) {
*
* List from: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute.
*/
const SVG_ATTRIBUTE_WITH_DASHES_LIST = ['accentHeight', 'alignmentBaseline', 'arabicForm', 'baselineShift', 'capHeight', 'clipPath', 'clipRule', 'colorInterpolation', 'colorInterpolationFilters', 'colorProfile', 'colorRendering', 'dominantBaseline', 'enableBackground', 'fillOpacity', 'fillRule', 'floodColor', 'floodOpacity', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'glyphName', 'glyphOrientationHorizontal', 'glyphOrientationVertical', 'horizAdvX', 'horizOriginX', 'imageRendering', 'letterSpacing', 'lightingColor', 'markerEnd', 'markerMid', 'markerStart', 'overlinePosition', 'overlineThickness', 'paintOrder', 'panose1', 'pointerEvents', 'renderingIntent', 'shapeRendering', 'stopColor', 'stopOpacity', 'strikethroughPosition', 'strikethroughThickness', 'strokeDasharray', 'strokeDashoffset', 'strokeLinecap', 'strokeLinejoin', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'textAnchor', 'textDecoration', 'textRendering', 'underlinePosition', 'underlineThickness', 'unicodeBidi', 'unicodeRange', 'unitsPerEm', 'vAlphabetic', 'vHanging', 'vIdeographic', 'vMathematical', 'vectorEffect', 'vertAdvY', 'vertOriginX', 'vertOriginY', 'wordSpacing', 'writingMode', 'xmlnsXlink', 'xHeight'].reduce((map, attribute) => {
// The keys are lower-cased for more robust lookup.
map[attribute.toLowerCase()] = attribute;
return map;
}, {});
/**
* This is a map of all case-sensitive SVG attributes. Map(lowercase key => proper case attribute).
* The keys are lower-cased for more robust lookup.
* Note that this list only contains attributes that contain at least one capital letter.
* Lowercase attributes don't need mapping, since we lowercase all attributes by default.
*/
const CASE_SENSITIVE_SVG_ATTRIBUTES = ['allowReorder', 'attributeName', 'attributeType', 'autoReverse', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', 'contentScriptType', 'contentStyleType', 'diffuseConstant', 'edgeMode', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant', 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget', 'xChannelSelector', 'yChannelSelector'].reduce((map, attribute) => {
// The keys are lower-cased for more robust lookup.
map[attribute.toLowerCase()] = attribute;
return map;
}, {});
/**
* This is a map of all SVG attributes that have colons.
* Keys are lower-cased and stripped of their colons for more robust lookup.
*/
const SVG_ATTRIBUTES_WITH_COLONS = ['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns:xlink'].reduce((map, attribute) => {
map[attribute.replace(':', '').toLowerCase()] = attribute;
return map;
}, {});
/**
* Returns the normal form of the element's attribute name for HTML.
*
@@ -1618,18 +1585,14 @@ const SVG_ATTRIBUTES_WITH_COLONS = ['xlink:actuate', 'xlink:arcrole', 'xlink:hre
*
* @return {string} Normalized attribute name.
*/
function getNormalAttributeName(attribute) {
switch (attribute) {
case 'htmlFor':
return 'for';
case 'className':
return 'class';
}
const attributeLowerCase = attribute.toLowerCase();
if (CASE_SENSITIVE_SVG_ATTRIBUTES[attributeLowerCase]) {
return CASE_SENSITIVE_SVG_ATTRIBUTES[attributeLowerCase];
} else if (SVG_ATTRIBUTE_WITH_DASHES_LIST[attributeLowerCase]) {
@@ -1637,9 +1600,9 @@ function getNormalAttributeName(attribute) {
} else if (SVG_ATTRIBUTES_WITH_COLONS[attributeLowerCase]) {
return SVG_ATTRIBUTES_WITH_COLONS[attributeLowerCase];
}
return attributeLowerCase;
}
/**
* Returns the normal form of the style property name for HTML.
*
@@ -1651,19 +1614,16 @@ function getNormalAttributeName(attribute) {
*
* @return {string} Normalized property name.
*/
function getNormalStylePropertyName(property) {
if (property.startsWith('--')) {
return property;
}
if (hasPrefix(property, ['ms', 'O', 'Moz', 'Webkit'])) {
return '-' + paramCase(property);
}
return paramCase(property);
}
/**
* Returns the normal form of the style property value for HTML. Appends a
* default pixel unit if numeric, not a unitless property, and not zero.
@@ -1673,15 +1633,13 @@ function getNormalStylePropertyName(property) {
*
* @return {*} Normalized property value.
*/
function getNormalStylePropertyValue(property, value) {
if (typeof value === 'number' && 0 !== value && !CSS_PROPERTIES_SUPPORTS_UNITLESS.has(property)) {
return value + 'px';
}
return value;
}
/**
* Serializes a React element to string.
*
@@ -1691,74 +1649,60 @@ function getNormalStylePropertyValue(property, value) {
*
* @return {string} Serialized element.
*/
function renderElement(element, context, legacyContext = {}) {
if (null === element || undefined === element || false === element) {
return '';
}
if (Array.isArray(element)) {
return renderChildren(element, context, legacyContext);
}
switch (typeof element) {
case 'string':
return (0,external_wp_escapeHtml_namespaceObject.escapeHTML)(element);
case 'number':
return element.toString();
}
const {
type,
props
} =
/** @type {{type?: any, props?: any}} */
} = /** @type {{type?: any, props?: any}} */
element;
switch (type) {
case external_React_namespaceObject.StrictMode:
case external_React_namespaceObject.Fragment:
return renderChildren(props.children, context, legacyContext);
case RawHTML:
const {
children,
...wrapperProps
} = props;
return renderNativeComponent(!Object.keys(wrapperProps).length ? null : 'div', { ...wrapperProps,
return renderNativeComponent(!Object.keys(wrapperProps).length ? null : 'div', {
...wrapperProps,
dangerouslySetInnerHTML: {
__html: children
}
}, context, legacyContext);
}
switch (typeof type) {
case 'string':
return renderNativeComponent(type, props, context, legacyContext);
case 'function':
if (type.prototype && typeof type.prototype.render === 'function') {
return renderComponent(type, props, context, legacyContext);
}
return renderElement(type(props, legacyContext), context, legacyContext);
}
switch (type && type.$$typeof) {
case Provider.$$typeof:
return renderChildren(props.children, props.value, legacyContext);
case Consumer.$$typeof:
return renderElement(props.children(context || type._currentValue), context, legacyContext);
case ForwardRef.$$typeof:
return renderElement(type.render(props), context, legacyContext);
}
return '';
}
/**
* Serializes a native component type to string.
*
@@ -1770,10 +1714,8 @@ function renderElement(element, context, legacyContext = {}) {
*
* @return {string} Serialized element.
*/
function renderNativeComponent(type, props, context, legacyContext = {}) {
let content = '';
if (type === 'textarea' && props.hasOwnProperty('value')) {
// Textarea children can be assigned as value prop. If it is, render in
// place of children. Ensure to omit so it is not assigned as attribute
@@ -1790,19 +1732,16 @@ function renderNativeComponent(type, props, context, legacyContext = {}) {
} else if (typeof props.children !== 'undefined') {
content = renderChildren(props.children, context, legacyContext);
}
if (!type) {
return content;
}
const attributes = renderAttributes(props);
if (SELF_CLOSING_TAGS.has(type)) {
return '<' + type + attributes + '/>';
}
return '<' + type + attributes + '>' + content + '</' + type + '>';
}
/** @typedef {import('./react').WPComponent} WPComponent */
/**
@@ -1815,25 +1754,20 @@ function renderNativeComponent(type, props, context, legacyContext = {}) {
*
* @return {string} Serialized element
*/
function renderComponent(Component, props, context, legacyContext = {}) {
const instance = new
/** @type {import('react').ComponentClass} */
const instance = new /** @type {import('react').ComponentClass} */
Component(props, legacyContext);
if (typeof // Ignore reason: Current prettier reformats parens and mangles type assertion
if (typeof
// Ignore reason: Current prettier reformats parens and mangles type assertion
// prettier-ignore
/** @type {{getChildContext?: () => unknown}} */
instance.getChildContext === 'function') {
Object.assign(legacyContext,
/** @type {{getChildContext?: () => unknown}} */
instance.getChildContext());
Object.assign(legacyContext, /** @type {{getChildContext?: () => unknown}} */instance.getChildContext());
}
const html = renderElement(instance.render(), context, legacyContext);
return html;
}
/**
* Serializes an array of children to string.
*
@@ -1843,18 +1777,16 @@ function renderComponent(Component, props, context, legacyContext = {}) {
*
* @return {string} Serialized children.
*/
function renderChildren(children, context, legacyContext = {}) {
let result = '';
children = Array.isArray(children) ? children : [children];
for (let i = 0; i < children.length; i++) {
const child = children[i];
result += renderElement(child, context, legacyContext);
}
return result;
}
/**
* Renders a props object as a string of HTML attributes.
*
@@ -1862,57 +1794,51 @@ function renderChildren(children, context, legacyContext = {}) {
*
* @return {string} Attributes string.
*/
function renderAttributes(props) {
let result = '';
for (const key in props) {
const attribute = getNormalAttributeName(key);
if (!(0,external_wp_escapeHtml_namespaceObject.isValidAttributeName)(attribute)) {
continue;
}
let value = getNormalAttributeValue(key, props[key]);
let value = getNormalAttributeValue(key, props[key]); // If value is not of serializeable type, skip.
// If value is not of serializeable type, skip.
if (!ATTRIBUTES_TYPES.has(typeof value)) {
continue;
} // Don't render internal attribute names.
}
// Don't render internal attribute names.
if (isInternalAttribute(key)) {
continue;
}
const isBooleanAttribute = BOOLEAN_ATTRIBUTES.has(attribute);
const isBooleanAttribute = BOOLEAN_ATTRIBUTES.has(attribute); // Boolean attribute should be omitted outright if its value is false.
// Boolean attribute should be omitted outright if its value is false.
if (isBooleanAttribute && value === false) {
continue;
}
const isMeaningfulAttribute = isBooleanAttribute || hasPrefix(key, ['data-', 'aria-']) || ENUMERATED_ATTRIBUTES.has(attribute);
const isMeaningfulAttribute = isBooleanAttribute || hasPrefix(key, ['data-', 'aria-']) || ENUMERATED_ATTRIBUTES.has(attribute); // Only write boolean value as attribute if meaningful.
// Only write boolean value as attribute if meaningful.
if (typeof value === 'boolean' && !isMeaningfulAttribute) {
continue;
}
result += ' ' + attribute;
result += ' ' + attribute; // Boolean attributes should write attribute name, but without value.
// Boolean attributes should write attribute name, but without value.
// Mere presence of attribute name is effective truthiness.
if (isBooleanAttribute) {
continue;
}
if (typeof value === 'string') {
value = (0,external_wp_escapeHtml_namespaceObject.escapeAttribute)(value);
}
result += '="' + value + '"';
}
return result;
}
/**
* Renders a style object as a string attribute value.
*
@@ -1920,33 +1846,26 @@ function renderAttributes(props) {
*
* @return {string} Style attribute value.
*/
function renderStyle(style) {
// Only generate from object, e.g. tolerate string value.
if (!isPlainObject(style)) {
return style;
}
let result;
for (const property in style) {
const value = style[property];
if (null === value || undefined === value) {
continue;
}
if (result) {
result += ';';
} else {
result = '';
}
const normalName = getNormalStylePropertyName(property);
const normalValue = getNormalStylePropertyValue(property, value);
result += normalName + ':' + normalValue;
}
return result;
}
/* harmony default export */ var serialize = (renderElement);
+15 -15
View File
@@ -39,13 +39,13 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"escapeAmpersand": function() { return /* binding */ escapeAmpersand; },
"escapeAttribute": function() { return /* binding */ escapeAttribute; },
"escapeEditableHTML": function() { return /* binding */ escapeEditableHTML; },
"escapeHTML": function() { return /* binding */ escapeHTML; },
"escapeLessThan": function() { return /* binding */ escapeLessThan; },
"escapeQuotationMark": function() { return /* binding */ escapeQuotationMark; },
"isValidAttributeName": function() { return /* binding */ isValidAttributeName; }
escapeAmpersand: function() { return /* binding */ escapeAmpersand; },
escapeAttribute: function() { return /* binding */ escapeAttribute; },
escapeEditableHTML: function() { return /* binding */ escapeEditableHTML; },
escapeHTML: function() { return /* binding */ escapeHTML; },
escapeLessThan: function() { return /* binding */ escapeLessThan; },
escapeQuotationMark: function() { return /* binding */ escapeQuotationMark; },
isValidAttributeName: function() { return /* binding */ isValidAttributeName; }
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/escape-html/build-module/escape-greater.js
@@ -70,6 +70,7 @@ function __unstableEscapeGreaterThan(value) {
* Internal dependencies
*/
/**
* Regular expression matching invalid attribute names.
*
@@ -81,8 +82,8 @@ function __unstableEscapeGreaterThan(value) {
*
* @type {RegExp}
*/
const REGEXP_INVALID_ATTRIBUTE_NAME = /[\u007F-\u009F "'>/="\uFDD0-\uFDEF]/;
/**
* Returns a string with ampersands escaped. Note that this is an imperfect
* implementation, where only ampersands which do not appear as a pattern of
@@ -97,10 +98,10 @@ const REGEXP_INVALID_ATTRIBUTE_NAME = /[\u007F-\u009F "'>/="\uFDD0-\uFDEF]/;
*
* @return {string} Escaped string.
*/
function escapeAmpersand(value) {
return value.replace(/&(?!([a-z0-9]+|#[0-9]+|#x[a-f0-9]+);)/gi, '&amp;');
}
/**
* Returns a string with quotation marks replaced.
*
@@ -108,10 +109,10 @@ function escapeAmpersand(value) {
*
* @return {string} Escaped string.
*/
function escapeQuotationMark(value) {
return value.replace(/"/g, '&quot;');
}
/**
* Returns a string with less-than sign replaced.
*
@@ -119,10 +120,10 @@ function escapeQuotationMark(value) {
*
* @return {string} Escaped string.
*/
function escapeLessThan(value) {
return value.replace(/</g, '&lt;');
}
/**
* Returns an escaped attribute value.
*
@@ -143,10 +144,10 @@ function escapeLessThan(value) {
*
* @return {string} Escaped attribute value.
*/
function escapeAttribute(value) {
return __unstableEscapeGreaterThan(escapeQuotationMark(escapeAmpersand(value)));
}
/**
* Returns an escaped HTML element value.
*
@@ -159,10 +160,10 @@ function escapeAttribute(value) {
*
* @return {string} Escaped HTML element value.
*/
function escapeHTML(value) {
return escapeLessThan(escapeAmpersand(value));
}
/**
* Returns an escaped Editable HTML element value. This is different from
* `escapeHTML`, because for editable HTML, ALL ampersands must be escaped in
@@ -172,10 +173,10 @@ function escapeHTML(value) {
*
* @return {string} Escaped HTML element value.
*/
function escapeEditableHTML(value) {
return escapeLessThan(value.replace(/&/g, '&amp;'));
}
/**
* Returns true if the given attribute name is valid, or false otherwise.
*
@@ -183,7 +184,6 @@ function escapeEditableHTML(value) {
*
* @return {boolean} Whether attribute is valid.
*/
function isValidAttributeName(name) {
return !REGEXP_INVALID_ATTRIBUTE_NAME.test(name);
}
+171 -333
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+47 -88
View File
@@ -39,26 +39,26 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"actions": function() { return /* binding */ actions; },
"addAction": function() { return /* binding */ addAction; },
"addFilter": function() { return /* binding */ addFilter; },
"applyFilters": function() { return /* binding */ applyFilters; },
"createHooks": function() { return /* reexport */ build_module_createHooks; },
"currentAction": function() { return /* binding */ currentAction; },
"currentFilter": function() { return /* binding */ currentFilter; },
"defaultHooks": function() { return /* binding */ defaultHooks; },
"didAction": function() { return /* binding */ didAction; },
"didFilter": function() { return /* binding */ didFilter; },
"doAction": function() { return /* binding */ doAction; },
"doingAction": function() { return /* binding */ doingAction; },
"doingFilter": function() { return /* binding */ doingFilter; },
"filters": function() { return /* binding */ filters; },
"hasAction": function() { return /* binding */ hasAction; },
"hasFilter": function() { return /* binding */ hasFilter; },
"removeAction": function() { return /* binding */ removeAction; },
"removeAllActions": function() { return /* binding */ removeAllActions; },
"removeAllFilters": function() { return /* binding */ removeAllFilters; },
"removeFilter": function() { return /* binding */ removeFilter; }
actions: function() { return /* binding */ actions; },
addAction: function() { return /* binding */ addAction; },
addFilter: function() { return /* binding */ addFilter; },
applyFilters: function() { return /* binding */ applyFilters; },
createHooks: function() { return /* reexport */ build_module_createHooks; },
currentAction: function() { return /* binding */ currentAction; },
currentFilter: function() { return /* binding */ currentFilter; },
defaultHooks: function() { return /* binding */ defaultHooks; },
didAction: function() { return /* binding */ didAction; },
didFilter: function() { return /* binding */ didFilter; },
doAction: function() { return /* binding */ doAction; },
doingAction: function() { return /* binding */ doingAction; },
doingFilter: function() { return /* binding */ doingFilter; },
filters: function() { return /* binding */ filters; },
hasAction: function() { return /* binding */ hasAction; },
hasFilter: function() { return /* binding */ hasFilter; },
removeAction: function() { return /* binding */ removeAction; },
removeAllActions: function() { return /* binding */ removeAllActions; },
removeAllFilters: function() { return /* binding */ removeAllFilters; },
removeFilter: function() { return /* binding */ removeFilter; }
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/validateNamespace.js
@@ -76,16 +76,13 @@ function validateNamespace(namespace) {
console.error('The namespace must be a non-empty string.');
return false;
}
if (!/^[a-zA-Z][a-zA-Z0-9_.\-\/]*$/.test(namespace)) {
// eslint-disable-next-line no-console
console.error('The namespace can only contain numbers, letters, dashes, periods, underscores and slashes.');
return false;
}
return true;
}
/* harmony default export */ var build_module_validateNamespace = (validateNamespace);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/validateHookName.js
@@ -104,22 +101,18 @@ function validateHookName(hookName) {
console.error('The hook name must be a non-empty string.');
return false;
}
if (/^__/.test(hookName)) {
// eslint-disable-next-line no-console
console.error('The hook name cannot begin with `__`.');
return false;
}
if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(hookName)) {
// eslint-disable-next-line no-console
console.error('The hook name can only contain numbers, letters, dashes, periods and underscores.');
return false;
}
return true;
}
/* harmony default export */ var build_module_validateHookName = (validateHookName);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createAddHook.js
@@ -128,6 +121,7 @@ function validateHookName(hookName) {
*/
/**
* @callback AddHook
*
@@ -147,63 +141,55 @@ function validateHookName(hookName) {
*
* @return {AddHook} Function that adds a new hook.
*/
function createAddHook(hooks, storeKey) {
return function addHook(hookName, namespace, callback, priority = 10) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
if (!build_module_validateNamespace(namespace)) {
return;
}
if ('function' !== typeof callback) {
// eslint-disable-next-line no-console
console.error('The hook callback must be a function.');
return;
} // Validate numeric priority
}
// Validate numeric priority
if ('number' !== typeof priority) {
// eslint-disable-next-line no-console
console.error('If specified, the hook priority must be a number.');
return;
}
const handler = {
callback,
priority,
namespace
};
if (hooksStore[hookName]) {
// Find the correct insert index of the new hook.
const handlers = hooksStore[hookName].handlers;
/** @type {number} */
let i;
for (i = handlers.length; i > 0; i--) {
if (priority >= handlers[i - 1].priority) {
break;
}
}
if (i === handlers.length) {
// If append, operate via direct assignment.
handlers[i] = handler;
} else {
// Otherwise, insert before index via splice.
handlers.splice(i, 0, handler);
} // We may also be currently executing this hook. If the callback
}
// We may also be currently executing this hook. If the callback
// we're adding would come after the current callback, there's no
// problem; otherwise we need to increase the execution index of
// any other runs by 1 to account for the added element.
hooksStore.__current.forEach(hookInfo => {
if (hookInfo.name === hookName && hookInfo.currentIndex >= i) {
hookInfo.currentIndex++;
@@ -216,13 +202,11 @@ function createAddHook(hooks, storeKey) {
runs: 0
};
}
if (hookName !== 'hookAdded') {
hooks.doAction('hookAdded', hookName, namespace, callback, priority);
}
};
}
/* harmony default export */ var build_module_createAddHook = (createAddHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createRemoveHook.js
@@ -231,6 +215,7 @@ function createAddHook(hooks, storeKey) {
*/
/**
* @callback RemoveHook
* Removes the specified callback (or all callbacks) from the hook with a given hookName
@@ -255,26 +240,21 @@ function createAddHook(hooks, storeKey) {
*
* @return {RemoveHook} Function that removes hooks.
*/
function createRemoveHook(hooks, storeKey, removeAll = false) {
return function removeHook(hookName, namespace) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
if (!removeAll && !build_module_validateNamespace(namespace)) {
return;
} // Bail if no hooks exist by this name.
}
// Bail if no hooks exist by this name.
if (!hooksStore[hookName]) {
return 0;
}
let handlersRemoved = 0;
if (removeAll) {
handlersRemoved = hooksStore[hookName].handlers.length;
hooksStore[hookName] = {
@@ -284,16 +264,15 @@ function createRemoveHook(hooks, storeKey, removeAll = false) {
} else {
// Try to find the specified callback to remove.
const handlers = hooksStore[hookName].handlers;
for (let i = handlers.length - 1; i >= 0; i--) {
if (handlers[i].namespace === namespace) {
handlers.splice(i, 1);
handlersRemoved++; // This callback may also be part of a hook that is
handlersRemoved++;
// This callback may also be part of a hook that is
// currently executing. If the callback we're removing
// comes after the current callback, there's no problem;
// otherwise we need to decrease the execution index of any
// other runs by 1 to account for the removed element.
hooksStore.__current.forEach(hookInfo => {
if (hookInfo.name === hookName && hookInfo.currentIndex >= i) {
hookInfo.currentIndex--;
@@ -302,15 +281,12 @@ function createRemoveHook(hooks, storeKey, removeAll = false) {
}
}
}
if (hookName !== 'hookRemoved') {
hooks.doAction('hookRemoved', hookName, namespace);
}
return handlersRemoved;
};
}
/* harmony default export */ var build_module_createRemoveHook = (createRemoveHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createHasHook.js
@@ -325,7 +301,6 @@ function createRemoveHook(hooks, storeKey, removeAll = false) {
*
* @return {boolean} Whether there are handlers that are attached to the given hook.
*/
/**
* Returns a function which, when invoked, will return whether any handlers are
* attached to a particular hook.
@@ -338,16 +313,15 @@ function createRemoveHook(hooks, storeKey, removeAll = false) {
*/
function createHasHook(hooks, storeKey) {
return function hasHook(hookName, namespace) {
const hooksStore = hooks[storeKey]; // Use the namespace if provided.
const hooksStore = hooks[storeKey];
// Use the namespace if provided.
if ('undefined' !== typeof namespace) {
return hookName in hooksStore && hooksStore[hookName].handlers.some(hook => hook.namespace === namespace);
}
return hookName in hooksStore;
};
}
/* harmony default export */ var build_module_createHasHook = (createHasHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createRunHook.js
@@ -361,54 +335,45 @@ function createHasHook(hooks, storeKey) {
* @param {boolean} [returnFirstArg=false] Whether each hook callback is expected to
* return its first argument.
*
* @return {(hookName:string, ...args: unknown[]) => unknown} Function that runs hook callbacks.
* @return {(hookName:string, ...args: unknown[]) => undefined|unknown} Function that runs hook callbacks.
*/
function createRunHook(hooks, storeKey, returnFirstArg = false) {
return function runHooks(hookName, ...args) {
const hooksStore = hooks[storeKey];
if (!hooksStore[hookName]) {
hooksStore[hookName] = {
handlers: [],
runs: 0
};
}
hooksStore[hookName].runs++;
const handlers = hooksStore[hookName].handlers; // The following code is stripped from production builds.
const handlers = hooksStore[hookName].handlers;
// The following code is stripped from production builds.
if (false) {}
if (!handlers || !handlers.length) {
return returnFirstArg ? args[0] : undefined;
}
const hookInfo = {
name: hookName,
currentIndex: 0
};
hooksStore.__current.push(hookInfo);
while (hookInfo.currentIndex < handlers.length) {
const handler = handlers[hookInfo.currentIndex];
const result = handler.callback.apply(null, args);
if (returnFirstArg) {
args[0] = result;
}
hookInfo.currentIndex++;
}
hooksStore.__current.pop();
if (returnFirstArg) {
return args[0];
}
return undefined;
};
}
/* harmony default export */ var build_module_createRunHook = (createRunHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createCurrentHook.js
@@ -425,12 +390,10 @@ function createRunHook(hooks, storeKey, returnFirstArg = false) {
function createCurrentHook(hooks, storeKey) {
return function currentHook() {
var _hooksStore$__current;
const hooksStore = hooks[storeKey];
return (_hooksStore$__current = hooksStore.__current[hooksStore.__current.length - 1]?.name) !== null && _hooksStore$__current !== void 0 ? _hooksStore$__current : null;
};
}
/* harmony default export */ var build_module_createCurrentHook = (createCurrentHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createDoingHook.js
@@ -456,17 +419,17 @@ function createCurrentHook(hooks, storeKey) {
*/
function createDoingHook(hooks, storeKey) {
return function doingHook(hookName) {
const hooksStore = hooks[storeKey]; // If the hookName was not passed, check for any current hook.
const hooksStore = hooks[storeKey];
// If the hookName was not passed, check for any current hook.
if ('undefined' === typeof hookName) {
return 'undefined' !== typeof hooksStore.__current[0];
} // Return the __current hook.
}
// Return the __current hook.
return hooksStore.__current[0] ? hookName === hooksStore.__current[0].name : false;
};
}
/* harmony default export */ var build_module_createDoingHook = (createDoingHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createDidHook.js
@@ -474,6 +437,7 @@ function createDoingHook(hooks, storeKey) {
* Internal dependencies
*/
/**
* @callback DidHook
*
@@ -493,19 +457,15 @@ function createDoingHook(hooks, storeKey) {
*
* @return {DidHook} Function that returns a hook's call count.
*/
function createDidHook(hooks, storeKey) {
return function didHook(hookName) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
return hooksStore[hookName] && hooksStore[hookName].runs ? hooksStore[hookName].runs : 0;
};
}
/* harmony default export */ var build_module_createDidHook = (createDidHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createHooks.js
@@ -519,6 +479,7 @@ function createDidHook(hooks, storeKey) {
/**
* Internal class for constructing hooks. Use `createHooks()` function
*
@@ -526,14 +487,13 @@ function createDidHook(hooks, storeKey) {
*
* @private
*/
class _Hooks {
constructor() {
/** @type {import('.').Store} actions */
this.actions = Object.create(null);
this.actions.__current = [];
/** @type {import('.').Store} filters */
/** @type {import('.').Store} filters */
this.filters = Object.create(null);
this.filters.__current = [];
this.addAction = build_module_createAddHook(this, 'actions');
@@ -553,8 +513,8 @@ class _Hooks {
this.didAction = build_module_createDidHook(this, 'actions');
this.didFilter = build_module_createDidHook(this, 'filters');
}
}
/** @typedef {_Hooks} Hooks */
/**
@@ -562,11 +522,9 @@ class _Hooks {
*
* @return {Hooks} A Hooks instance.
*/
function createHooks() {
return new _Hooks();
}
/* harmony default export */ var build_module_createHooks = (createHooks);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/index.js
@@ -574,6 +532,7 @@ function createHooks() {
* Internal dependencies
*/
/** @typedef {(...args: any[])=>any} Callback */
/**
+6 -10
View File
@@ -36,10 +36,11 @@
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "decodeEntities": function() { return /* binding */ decodeEntities; }
/* harmony export */ decodeEntities: function() { return /* binding */ decodeEntities; }
/* harmony export */ });
/** @type {HTMLTextAreaElement} */
let _decodeTextArea;
/**
* Decodes the HTML entities from a given string.
*
@@ -53,15 +54,13 @@ let _decodeTextArea;
*
* @return {string} The decoded string.
*/
function decodeEntities(html) {
// Not a string, or no entities to decode.
if ('string' !== typeof html || -1 === html.indexOf('&')) {
return html;
} // Create a textarea for decoding entities, that we can reuse.
}
// Create a textarea for decoding entities, that we can reuse.
if (undefined === _decodeTextArea) {
if (document.implementation && document.implementation.createHTMLDocument) {
_decodeTextArea = document.implementation.createHTMLDocument('').createElement('textarea');
@@ -69,10 +68,10 @@ function decodeEntities(html) {
_decodeTextArea = document.createElement('textarea');
}
}
_decodeTextArea.innerHTML = html;
const decoded = _decodeTextArea.textContent;
_decodeTextArea.innerHTML = '';
/**
* Cast to string, HTMLTextAreaElement should always have `string` textContent.
*
@@ -90,10 +89,7 @@ function decodeEntities(html) {
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
*/
return (
/** @type {string} */
decoded
return (/** @type {string} */decoded
);
}
+84 -153
View File
@@ -317,19 +317,19 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"__": function() { return /* reexport */ __; },
"_n": function() { return /* reexport */ _n; },
"_nx": function() { return /* reexport */ _nx; },
"_x": function() { return /* reexport */ _x; },
"createI18n": function() { return /* reexport */ createI18n; },
"defaultI18n": function() { return /* reexport */ default_i18n; },
"getLocaleData": function() { return /* reexport */ getLocaleData; },
"hasTranslation": function() { return /* reexport */ hasTranslation; },
"isRTL": function() { return /* reexport */ isRTL; },
"resetLocaleData": function() { return /* reexport */ resetLocaleData; },
"setLocaleData": function() { return /* reexport */ setLocaleData; },
"sprintf": function() { return /* reexport */ sprintf_sprintf; },
"subscribe": function() { return /* reexport */ subscribe; }
__: function() { return /* reexport */ __; },
_n: function() { return /* reexport */ _n; },
_nx: function() { return /* reexport */ _nx; },
_x: function() { return /* reexport */ _x; },
createI18n: function() { return /* reexport */ createI18n; },
defaultI18n: function() { return /* reexport */ default_i18n; },
getLocaleData: function() { return /* reexport */ getLocaleData; },
hasTranslation: function() { return /* reexport */ hasTranslation; },
isRTL: function() { return /* reexport */ isRTL; },
resetLocaleData: function() { return /* reexport */ resetLocaleData; },
setLocaleData: function() { return /* reexport */ setLocaleData; },
sprintf: function() { return /* reexport */ sprintf_sprintf; },
subscribe: function() { return /* reexport */ subscribe; }
});
;// CONCATENATED MODULE: ./node_modules/memize/dist/index.js
@@ -503,6 +503,7 @@ var sprintf_default = /*#__PURE__*/__webpack_require__.n(sprintf);
*/
/**
* Log to console, once per message; or more precisely, per referentially equal
* argument set. Because Jed throws errors, we log these to the console instead
@@ -510,7 +511,6 @@ var sprintf_default = /*#__PURE__*/__webpack_require__.n(sprintf);
*
* @param {...*} args Arguments to pass to `console.error`
*/
const logErrorOnce = memize(console.error); // eslint-disable-line no-console
/**
@@ -524,7 +524,6 @@ const logErrorOnce = memize(console.error); // eslint-disable-line no-console
*
* @return {string} The formatted string.
*/
function sprintf_sprintf(format, ...args) {
try {
return sprintf_default().sprintf(format, ...args);
@@ -532,7 +531,6 @@ function sprintf_sprintf(format, ...args) {
if (error instanceof Error) {
logErrorOnce('sprintf error: \n\n' + error.toString());
}
return format;
}
}
@@ -1046,6 +1044,7 @@ Tannin.prototype.dcnpgettext = function( domain, context, singular, plural, n )
* External dependencies
*/
/**
* @typedef {Record<string,any>} LocaleData
*/
@@ -1056,22 +1055,21 @@ Tannin.prototype.dcnpgettext = function( domain, context, singular, plural, n )
*
* @type {LocaleData}
*/
const DEFAULT_LOCALE_DATA = {
'': {
/** @param {number} n */
plural_forms(n) {
return n === 1 ? 0 : 1;
}
}
};
/*
* Regular expression that matches i18n hooks like `i18n.gettext`, `i18n.ngettext`,
* `i18n.gettext_domain` or `i18n.ngettext_with_context` or `i18n.has_translation`.
*/
const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
/**
* @typedef {(domain?: string) => LocaleData} GetLocaleData
*
@@ -1080,7 +1078,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see http://messageformat.github.io/Jed/
*/
/**
* @typedef {(data?: LocaleData, domain?: string) => void} SetLocaleData
*
@@ -1090,7 +1087,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see http://messageformat.github.io/Jed/
*/
/**
* @typedef {(data?: LocaleData, domain?: string) => void} AddLocaleData
*
@@ -1100,7 +1096,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see http://messageformat.github.io/Jed/
*/
/**
* @typedef {(data?: LocaleData, domain?: string) => void} ResetLocaleData
*
@@ -1109,22 +1104,17 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see http://messageformat.github.io/Jed/
*/
/** @typedef {() => void} SubscribeCallback */
/** @typedef {() => void} UnsubscribeCallback */
/**
* @typedef {(callback: SubscribeCallback) => UnsubscribeCallback} Subscribe
*
* Subscribes to changes of locale data
*/
/**
* @typedef {(domain?: string) => string} GetFilterDomain
* Retrieve the domain to use when calling domain-specific filters.
*/
/**
* @typedef {(text: string, domain?: string) => string} __
*
@@ -1132,7 +1122,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see https://developer.wordpress.org/reference/functions/__/
*/
/**
* @typedef {(text: string, context: string, domain?: string) => string} _x
*
@@ -1140,7 +1129,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see https://developer.wordpress.org/reference/functions/_x/
*/
/**
* @typedef {(single: string, plural: string, number: number, domain?: string) => string} _n
*
@@ -1149,7 +1137,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see https://developer.wordpress.org/reference/functions/_n/
*/
/**
* @typedef {(single: string, plural: string, number: number, context: string, domain?: string) => string} _nx
*
@@ -1158,7 +1145,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @see https://developer.wordpress.org/reference/functions/_nx/
*/
/**
* @typedef {() => boolean} IsRtl
*
@@ -1169,13 +1155,11 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
* language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages,
* including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`).
*/
/**
* @typedef {(single: string, context?: string, domain?: string) => boolean} HasTranslation
*
* Check if there is a translation for a given string in singular form.
*/
/** @typedef {import('@wordpress/hooks').Hooks} Hooks */
/**
@@ -1211,7 +1195,6 @@ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/;
*
* @return {I18n} I18n instance.
*/
const createI18n = (initialData, initialDomain, hooks) => {
/**
* The underlying instance of Tannin to which exported functions interface.
@@ -1220,78 +1203,80 @@ const createI18n = (initialData, initialDomain, hooks) => {
*/
const tannin = new Tannin({});
const listeners = new Set();
const notifyListeners = () => {
listeners.forEach(listener => listener());
};
/**
* Subscribe to changes of locale data.
*
* @param {SubscribeCallback} callback Subscription callback.
* @return {UnsubscribeCallback} Unsubscribe callback.
*/
const subscribe = callback => {
listeners.add(callback);
return () => listeners.delete(callback);
};
/** @type {GetLocaleData} */
const getLocaleData = (domain = 'default') => tannin.data[domain];
/**
* @param {LocaleData} [data]
* @param {string} [domain]
*/
const doSetLocaleData = (data, domain = 'default') => {
tannin.data[domain] = { ...tannin.data[domain],
tannin.data[domain] = {
...tannin.data[domain],
...data
}; // Populate default domain configuration (supported locale date which omits
};
// Populate default domain configuration (supported locale date which omits
// a plural forms expression).
tannin.data[domain][''] = { ...DEFAULT_LOCALE_DATA[''],
tannin.data[domain][''] = {
...DEFAULT_LOCALE_DATA[''],
...tannin.data[domain]?.['']
}; // Clean up cached plural forms functions cache as it might be updated.
};
// Clean up cached plural forms functions cache as it might be updated.
delete tannin.pluralForms[domain];
};
/** @type {SetLocaleData} */
const setLocaleData = (data, domain) => {
doSetLocaleData(data, domain);
notifyListeners();
};
/** @type {AddLocaleData} */
const addLocaleData = (data, domain = 'default') => {
tannin.data[domain] = { ...tannin.data[domain],
tannin.data[domain] = {
...tannin.data[domain],
...data,
// Populate default domain configuration (supported locale date which omits
// a plural forms expression).
'': { ...DEFAULT_LOCALE_DATA[''],
'': {
...DEFAULT_LOCALE_DATA[''],
...tannin.data[domain]?.[''],
...data?.['']
}
}; // Clean up cached plural forms functions cache as it might be updated.
};
// Clean up cached plural forms functions cache as it might be updated.
delete tannin.pluralForms[domain];
notifyListeners();
};
/** @type {ResetLocaleData} */
const resetLocaleData = (data, domain) => {
// Reset all current Tannin locale data.
tannin.data = {}; // Reset cached plural forms functions cache.
tannin.data = {};
// Reset cached plural forms functions cache.
tannin.pluralForms = {};
setLocaleData(data, domain);
};
/**
* Wrapper for Tannin's `dcnpgettext`. Populates default locale data if not
* otherwise previously assigned.
@@ -1307,29 +1292,24 @@ const createI18n = (initialData, initialDomain, hooks) => {
*
* @return {string} The translated string.
*/
const dcnpgettext = (domain = 'default', context, single, plural, number) => {
if (!tannin.data[domain]) {
// Use `doSetLocaleData` to set silently, without notifying listeners.
doSetLocaleData(undefined, domain);
}
return tannin.dcnpgettext(domain, context, single, plural, number);
};
/** @type {GetFilterDomain} */
const getFilterDomain = (domain = 'default') => domain;
/** @type {__} */
const __ = (text, domain) => {
let translation = dcnpgettext(domain, undefined, text);
if (!hooks) {
return translation;
}
/**
* Filters text with its translation.
*
@@ -1337,29 +1317,20 @@ const createI18n = (initialData, initialDomain, hooks) => {
* @param {string} text Text to translate.
* @param {string} domain Text domain. Unique identifier for retrieving translated strings.
*/
translation =
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.gettext', translation, text, domain);
return (
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.gettext_' + getFilterDomain(domain), translation, text, domain)
translation = /** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.gettext', translation, text, domain);
return (/** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.gettext_' + getFilterDomain(domain), translation, text, domain)
);
};
/** @type {_x} */
const _x = (text, context, domain) => {
let translation = dcnpgettext(domain, context, text);
if (!hooks) {
return translation;
}
/**
* Filters text with its translation based on context information.
*
@@ -1368,29 +1339,20 @@ const createI18n = (initialData, initialDomain, hooks) => {
* @param {string} context Context information for the translators.
* @param {string} domain Text domain. Unique identifier for retrieving translated strings.
*/
translation =
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.gettext_with_context', translation, text, context, domain);
return (
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.gettext_with_context_' + getFilterDomain(domain), translation, text, context, domain)
translation = /** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.gettext_with_context', translation, text, context, domain);
return (/** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.gettext_with_context_' + getFilterDomain(domain), translation, text, context, domain)
);
};
/** @type {_n} */
const _n = (single, plural, number, domain) => {
let translation = dcnpgettext(domain, undefined, single, plural, number);
if (!hooks) {
return translation;
}
/**
* Filters the singular or plural form of a string.
*
@@ -1400,29 +1362,20 @@ const createI18n = (initialData, initialDomain, hooks) => {
* @param {string} number The number to compare against to use either the singular or plural form.
* @param {string} domain Text domain. Unique identifier for retrieving translated strings.
*/
translation =
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.ngettext', translation, single, plural, number, domain);
return (
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.ngettext_' + getFilterDomain(domain), translation, single, plural, number, domain)
translation = /** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.ngettext', translation, single, plural, number, domain);
return (/** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.ngettext_' + getFilterDomain(domain), translation, single, plural, number, domain)
);
};
/** @type {_nx} */
const _nx = (single, plural, number, context, domain) => {
let translation = dcnpgettext(domain, context, single, plural, number);
if (!hooks) {
return translation;
}
/**
* Filters the singular or plural form of a string with gettext context.
*
@@ -1433,33 +1386,22 @@ const createI18n = (initialData, initialDomain, hooks) => {
* @param {string} context Context information for the translators.
* @param {string} domain Text domain. Unique identifier for retrieving translated strings.
*/
translation =
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.ngettext_with_context', translation, single, plural, number, context, domain);
return (
/** @type {string} */
/** @type {*} */
hooks.applyFilters('i18n.ngettext_with_context_' + getFilterDomain(domain), translation, single, plural, number, context, domain)
translation = /** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.ngettext_with_context', translation, single, plural, number, context, domain);
return (/** @type {string} */
/** @type {*} */hooks.applyFilters('i18n.ngettext_with_context_' + getFilterDomain(domain), translation, single, plural, number, context, domain)
);
};
/** @type {IsRtl} */
const isRTL = () => {
return 'rtl' === _x('ltr', 'text direction');
};
/** @type {HasTranslation} */
const hasTranslation = (single, context, domain) => {
const key = context ? context + '\u0004' + single : single;
let result = !!tannin.data?.[domain !== null && domain !== void 0 ? domain : 'default']?.[key];
if (hooks) {
/**
* Filters the presence of a translation in the locale data.
@@ -1469,25 +1411,16 @@ const createI18n = (initialData, initialDomain, hooks) => {
* @param {string} context Context information for the translators.
* @param {string} domain Text domain. Unique identifier for retrieving translated strings.
*/
result =
/** @type { boolean } */
/** @type {*} */
hooks.applyFilters('i18n.has_translation', result, single, context, domain);
result =
/** @type { boolean } */
/** @type {*} */
hooks.applyFilters('i18n.has_translation_' + getFilterDomain(domain), result, single, context, domain);
result = /** @type { boolean } */
/** @type {*} */hooks.applyFilters('i18n.has_translation', result, single, context, domain);
result = /** @type { boolean } */
/** @type {*} */hooks.applyFilters('i18n.has_translation_' + getFilterDomain(domain), result, single, context, domain);
}
return result;
};
if (initialData) {
setLocaleData(initialData, initialDomain);
}
if (hooks) {
/**
* @param {string} hookName
@@ -1497,11 +1430,9 @@ const createI18n = (initialData, initialDomain, hooks) => {
notifyListeners();
}
};
hooks.addAction('hookAdded', 'core/i18n', onHookAddedOrRemoved);
hooks.addAction('hookRemoved', 'core/i18n', onHookAddedOrRemoved);
}
return {
getLocaleData,
setLocaleData,
@@ -1524,17 +1455,18 @@ var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
* Internal dependencies
*/
/**
* WordPress dependencies
*/
const i18n = createI18n(undefined, undefined, external_wp_hooks_namespaceObject.defaultHooks);
/**
* Default, singleton instance of `I18n`.
*/
/* harmony default export */ var default_i18n = (i18n);
/*
* Comments in this file are duplicated from ./i18n due to
* https://github.com/WordPress/gutenberg/pull/20318#issuecomment-590837722
@@ -1554,8 +1486,8 @@ const i18n = createI18n(undefined, undefined, external_wp_hooks_namespaceObject.
* @param {string} [domain] Domain for which to get the data.
* @return {LocaleData} Locale data.
*/
const getLocaleData = i18n.getLocaleData.bind(i18n);
/**
* Merges locale data into the Tannin instance by domain. Accepts data in a
* Jed-formatted JSON object shape.
@@ -1565,8 +1497,8 @@ const getLocaleData = i18n.getLocaleData.bind(i18n);
* @param {LocaleData} [data] Locale data configuration.
* @param {string} [domain] Domain for which configuration applies.
*/
const setLocaleData = i18n.setLocaleData.bind(i18n);
/**
* Resets all current Tannin instance locale data and sets the specified
* locale data for the domain. Accepts data in a Jed-formatted JSON object shape.
@@ -1576,16 +1508,16 @@ const setLocaleData = i18n.setLocaleData.bind(i18n);
* @param {LocaleData} [data] Locale data configuration.
* @param {string} [domain] Domain for which configuration applies.
*/
const resetLocaleData = i18n.resetLocaleData.bind(i18n);
/**
* Subscribes to changes of locale data
*
* @param {SubscribeCallback} callback Subscription callback
* @return {UnsubscribeCallback} Unsubscribe callback
*/
const subscribe = i18n.subscribe.bind(i18n);
/**
* Retrieve the translation of text.
*
@@ -1596,8 +1528,8 @@ const subscribe = i18n.subscribe.bind(i18n);
*
* @return {string} Translated text.
*/
const __ = i18n.__.bind(i18n);
/**
* Retrieve translated string with gettext context.
*
@@ -1609,8 +1541,8 @@ const __ = i18n.__.bind(i18n);
*
* @return {string} Translated context string without pipe.
*/
const _x = i18n._x.bind(i18n);
/**
* Translates and retrieves the singular or plural form based on the supplied
* number.
@@ -1625,8 +1557,8 @@ const _x = i18n._x.bind(i18n);
*
* @return {string} The translated singular or plural form.
*/
const _n = i18n._n.bind(i18n);
/**
* Translates and retrieves the singular or plural form based on the supplied
* number, with gettext context.
@@ -1642,8 +1574,8 @@ const _n = i18n._n.bind(i18n);
*
* @return {string} The translated singular or plural form.
*/
const _nx = i18n._nx.bind(i18n);
/**
* Check if current locale is RTL.
*
@@ -1654,8 +1586,8 @@ const _nx = i18n._nx.bind(i18n);
*
* @return {boolean} Whether locale is RTL.
*/
const isRTL = i18n.isRTL.bind(i18n);
/**
* Check if there is a translation for a given string (in singular form).
*
@@ -1664,7 +1596,6 @@ const isRTL = i18n.isRTL.bind(i18n);
* @param {string} [domain] Domain to retrieve the translated text.
* @return {boolean} Whether the translation exists or not.
*/
const hasTranslation = i18n.hasTranslation.bind(i18n);
;// CONCATENATED MODULE: ./node_modules/@wordpress/i18n/build-module/index.js
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+5 -15
View File
@@ -40,8 +40,8 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": function() { return /* binding */ isShallowEqual; },
"isShallowEqualArrays": function() { return /* reexport */ isShallowEqualArrays; },
"isShallowEqualObjects": function() { return /* reexport */ isShallowEqualObjects; }
isShallowEqualArrays: function() { return /* reexport */ isShallowEqualArrays; },
isShallowEqualObjects: function() { return /* reexport */ isShallowEqualObjects; }
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/is-shallow-equal/build-module/objects.js
@@ -57,21 +57,17 @@ function isShallowEqualObjects(a, b) {
if (a === b) {
return true;
}
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
let i = 0;
while (i < aKeys.length) {
const key = aKeys[i];
const aValue = a[key];
if ( // In iterating only the keys of the first object after verifying
if (
// In iterating only the keys of the first object after verifying
// equal lengths, account for the case that an explicit `undefined`
// value in the first is implicitly undefined in the second.
//
@@ -79,10 +75,8 @@ function isShallowEqualObjects(a, b) {
aValue === undefined && !b.hasOwnProperty(key) || aValue !== b[key]) {
return false;
}
i++;
}
return true;
}
@@ -99,17 +93,14 @@ function isShallowEqualArrays(a, b) {
if (a === b) {
return true;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0, len = a.length; i < len; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
@@ -121,6 +112,7 @@ function isShallowEqualArrays(a, b) {
/**
* @typedef {Record<string, any>} ComparableObject
*/
@@ -134,7 +126,6 @@ function isShallowEqualArrays(a, b) {
*
* @return {boolean} Whether the two values are shallow equal.
*/
function isShallowEqual(a, b) {
if (a && b) {
if (a.constructor === Object && b.constructor === Object) {
@@ -143,7 +134,6 @@ function isShallowEqual(a, b) {
return isShallowEqualArrays(a, b);
}
}
return a === b;
}
+369 -53
View File
@@ -39,31 +39,31 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"ShortcutProvider": function() { return /* reexport */ ShortcutProvider; },
"__unstableUseShortcutEventMatch": function() { return /* reexport */ useShortcutEventMatch; },
"store": function() { return /* reexport */ store; },
"useShortcut": function() { return /* reexport */ useShortcut; }
ShortcutProvider: function() { return /* reexport */ ShortcutProvider; },
__unstableUseShortcutEventMatch: function() { return /* reexport */ useShortcutEventMatch; },
store: function() { return /* reexport */ store; },
useShortcut: function() { return /* reexport */ useShortcut; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/keyboard-shortcuts/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"registerShortcut": function() { return registerShortcut; },
"unregisterShortcut": function() { return unregisterShortcut; }
registerShortcut: function() { return registerShortcut; },
unregisterShortcut: function() { return unregisterShortcut; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/keyboard-shortcuts/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"getAllShortcutKeyCombinations": function() { return getAllShortcutKeyCombinations; },
"getAllShortcutRawKeyCombinations": function() { return getAllShortcutRawKeyCombinations; },
"getCategoryShortcuts": function() { return getCategoryShortcuts; },
"getShortcutAliases": function() { return getShortcutAliases; },
"getShortcutDescription": function() { return getShortcutDescription; },
"getShortcutKeyCombination": function() { return getShortcutKeyCombination; },
"getShortcutRepresentation": function() { return getShortcutRepresentation; }
getAllShortcutKeyCombinations: function() { return getAllShortcutKeyCombinations; },
getAllShortcutRawKeyCombinations: function() { return getAllShortcutRawKeyCombinations; },
getCategoryShortcuts: function() { return getCategoryShortcuts; },
getShortcutAliases: function() { return getShortcutAliases; },
getShortcutDescription: function() { return getShortcutDescription; },
getShortcutKeyCombination: function() { return getShortcutKeyCombination; },
getShortcutRepresentation: function() { return getShortcutRepresentation; }
});
;// CONCATENATED MODULE: external ["wp","data"]
@@ -80,7 +80,8 @@ var external_wp_data_namespaceObject = window["wp"]["data"];
function reducer(state = {}, action) {
switch (action.type) {
case 'REGISTER_SHORTCUT':
return { ...state,
return {
...state,
[action.name]: {
category: action.category,
keyCombination: action.keyCombination,
@@ -88,7 +89,6 @@ function reducer(state = {}, action) {
description: action.description
}
};
case 'UNREGISTER_SHORTCUT':
const {
[action.name]: actionName,
@@ -96,10 +96,8 @@ function reducer(state = {}, action) {
} = state;
return remainingState;
}
return state;
}
/* harmony default export */ var store_reducer = (reducer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/store/actions.js
@@ -131,6 +129,44 @@ function reducer(state = {}, action) {
*
* @param {WPShortcutConfig} config Shortcut config.
*
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect, useDispatch } from '@wordpress/data';
* import { useEffect } from '@wordpress/element';
* import { __ } from '@wordpress/i18n';
*
* const ExampleComponent = () => {
* const { registerShortcut } = useDispatch( keyboardShortcutsStore );
*
* useEffect( () => {
* registerShortcut( {
* name: 'custom/my-custom-shortcut',
* category: 'my-category',
* description: __( 'My custom shortcut' ),
* keyCombination: {
* modifier: 'primary',
* character: 'j',
* },
* } );
* }, [] );
*
* const shortcut = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getShortcutKeyCombination(
* 'custom/my-custom-shortcut'
* ),
* []
* );
*
* return shortcut ? (
* <p>{ __( 'Shortcut is registered.' ) }</p>
* ) : (
* <p>{ __( 'Shortcut is not registered.' ) }</p>
* );
* };
*```
* @return {Object} action.
*/
function registerShortcut({
@@ -149,14 +185,44 @@ function registerShortcut({
description
};
}
/**
* Returns an action object used to unregister a keyboard shortcut.
*
* @param {string} name Shortcut name.
*
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect, useDispatch } from '@wordpress/data';
* import { useEffect } from '@wordpress/element';
* import { __ } from '@wordpress/i18n';
*
* const ExampleComponent = () => {
* const { unregisterShortcut } = useDispatch( keyboardShortcutsStore );
*
* useEffect( () => {
* unregisterShortcut( 'core/edit-post/next-region' );
* }, [] );
*
* const shortcut = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getShortcutKeyCombination(
* 'core/edit-post/next-region'
* ),
* []
* );
*
* return shortcut ? (
* <p>{ __( 'Shortcut is not unregistered.' ) }</p>
* ) : (
* <p>{ __( 'Shortcut is unregistered.' ) }</p>
* );
* };
*```
* @return {Object} action.
*/
function unregisterShortcut(name) {
return {
type: 'UNREGISTER_SHORTCUT',
@@ -469,6 +535,7 @@ var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
* External dependencies
*/
/**
* WordPress dependencies
*/
@@ -484,8 +551,8 @@ var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
*
* @type {Array<any>}
*/
const EMPTY_ARRAY = [];
/**
* Shortcut formatting methods.
*
@@ -493,12 +560,12 @@ const EMPTY_ARRAY = [];
* @property {WPKeycodeHandlerByModifier} rawShortcut Raw shortcut formatting.
* @property {WPKeycodeHandlerByModifier} ariaLabel ARIA label formatting.
*/
const FORMATTING_METHODS = {
display: external_wp_keycodes_namespaceObject.displayShortcut,
raw: external_wp_keycodes_namespaceObject.rawShortcut,
ariaLabel: external_wp_keycodes_namespaceObject.shortcutAriaLabel
};
/**
* Returns a string representing the key combination.
*
@@ -508,27 +575,58 @@ const FORMATTING_METHODS = {
*
* @return {string?} Shortcut representation.
*/
function getKeyCombinationRepresentation(shortcut, representation) {
if (!shortcut) {
return null;
}
return shortcut.modifier ? FORMATTING_METHODS[representation][shortcut.modifier](shortcut.character) : shortcut.character;
}
/**
* Returns the main key combination for a given shortcut name.
*
* @param {Object} state Global state.
* @param {string} name Shortcut name.
*
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect } from '@wordpress/data';
* import { createInterpolateElement } from '@wordpress/element';
* import { sprintf } from '@wordpress/i18n';
* const ExampleComponent = () => {
* const {character, modifier} = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getShortcutKeyCombination(
* 'core/edit-post/next-region'
* ),
* []
* );
*
* return (
* <div>
* { createInterpolateElement(
* sprintf(
* 'Character: <code>%s</code> / Modifier: <code>%s</code>',
* character,
* modifier
* ),
* {
* code: <code />,
* }
* ) }
* </div>
* );
* };
*```
*
* @return {WPShortcutKeyCombination?} Key combination.
*/
function getShortcutKeyCombination(state, name) {
return state[name] ? state[name].keyCombination : null;
}
/**
* Returns a string representing the main key combination for a given shortcut name.
*
@@ -536,62 +634,263 @@ function getShortcutKeyCombination(state, name) {
* @param {string} name Shortcut name.
* @param {keyof FORMATTING_METHODS} representation Type of representation
* (display, raw, ariaLabel).
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect } from '@wordpress/data';
* import { sprintf } from '@wordpress/i18n';
*
* const ExampleComponent = () => {
* const {display, raw, ariaLabel} = useSelect(
* ( select ) =>{
* return {
* display: select( keyboardShortcutsStore ).getShortcutRepresentation('core/edit-post/next-region' ),
* raw: select( keyboardShortcutsStore ).getShortcutRepresentation('core/edit-post/next-region','raw' ),
* ariaLabel: select( keyboardShortcutsStore ).getShortcutRepresentation('core/edit-post/next-region', 'ariaLabel')
* }
* },
* []
* );
*
* return (
* <ul>
* <li>{ sprintf( 'display string: %s', display ) }</li>
* <li>{ sprintf( 'raw string: %s', raw ) }</li>
* <li>{ sprintf( 'ariaLabel string: %s', ariaLabel ) }</li>
* </ul>
* );
* };
*```
*
* @return {string?} Shortcut representation.
*/
function getShortcutRepresentation(state, name, representation = 'display') {
const shortcut = getShortcutKeyCombination(state, name);
return getKeyCombinationRepresentation(shortcut, representation);
}
/**
* Returns the shortcut description given its name.
*
* @param {Object} state Global state.
* @param {string} name Shortcut name.
*
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect } from '@wordpress/data';
* import { __ } from '@wordpress/i18n';
* const ExampleComponent = () => {
* const shortcutDescription = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getShortcutDescription( 'core/edit-post/next-region' ),
* []
* );
*
* return shortcutDescription ? (
* <div>{ shortcutDescription }</div>
* ) : (
* <div>{ __( 'No description.' ) }</div>
* );
* };
*```
* @return {string?} Shortcut description.
*/
function getShortcutDescription(state, name) {
return state[name] ? state[name].description : null;
}
/**
* Returns the aliases for a given shortcut name.
*
* @param {Object} state Global state.
* @param {string} name Shortcut name.
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect } from '@wordpress/data';
* import { createInterpolateElement } from '@wordpress/element';
* import { sprintf } from '@wordpress/i18n';
* const ExampleComponent = () => {
* const shortcutAliases = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getShortcutAliases(
* 'core/edit-post/next-region'
* ),
* []
* );
*
* return (
* shortcutAliases.length > 0 && (
* <ul>
* { shortcutAliases.map( ( { character, modifier }, index ) => (
* <li key={ index }>
* { createInterpolateElement(
* sprintf(
* 'Character: <code>%s</code> / Modifier: <code>%s</code>',
* character,
* modifier
* ),
* {
* code: <code />,
* }
* ) }
* </li>
* ) ) }
* </ul>
* )
* );
* };
*```
*
* @return {WPShortcutKeyCombination[]} Key combinations.
*/
function getShortcutAliases(state, name) {
return state[name] && state[name].aliases ? state[name].aliases : EMPTY_ARRAY;
}
/**
* Returns the shortcuts that include aliases for a given shortcut name.
*
* @param {Object} state Global state.
* @param {string} name Shortcut name.
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect } from '@wordpress/data';
* import { createInterpolateElement } from '@wordpress/element';
* import { sprintf } from '@wordpress/i18n';
*
* const ExampleComponent = () => {
* const allShortcutKeyCombinations = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getAllShortcutKeyCombinations(
* 'core/edit-post/next-region'
* ),
* []
* );
*
* return (
* allShortcutKeyCombinations.length > 0 && (
* <ul>
* { allShortcutKeyCombinations.map(
* ( { character, modifier }, index ) => (
* <li key={ index }>
* { createInterpolateElement(
* sprintf(
* 'Character: <code>%s</code> / Modifier: <code>%s</code>',
* character,
* modifier
* ),
* {
* code: <code />,
* }
* ) }
* </li>
* )
* ) }
* </ul>
* )
* );
* };
*```
*
* @return {WPShortcutKeyCombination[]} Key combinations.
*/
const getAllShortcutKeyCombinations = rememo((state, name) => {
return [getShortcutKeyCombination(state, name), ...getShortcutAliases(state, name)].filter(Boolean);
}, (state, name) => [state[name]]);
/**
* Returns the raw representation of all the keyboard combinations of a given shortcut name.
*
* @param {Object} state Global state.
* @param {string} name Shortcut name.
*
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect } from '@wordpress/data';
* import { createInterpolateElement } from '@wordpress/element';
* import { sprintf } from '@wordpress/i18n';
*
* const ExampleComponent = () => {
* const allShortcutRawKeyCombinations = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getAllShortcutRawKeyCombinations(
* 'core/edit-post/next-region'
* ),
* []
* );
*
* return (
* allShortcutRawKeyCombinations.length > 0 && (
* <ul>
* { allShortcutRawKeyCombinations.map(
* ( shortcutRawKeyCombination, index ) => (
* <li key={ index }>
* { createInterpolateElement(
* sprintf(
* ' <code>%s</code>',
* shortcutRawKeyCombination
* ),
* {
* code: <code />,
* }
* ) }
* </li>
* )
* ) }
* </ul>
* )
* );
* };
*```
*
* @return {string[]} Shortcuts.
*/
const getAllShortcutRawKeyCombinations = rememo((state, name) => {
return getAllShortcutKeyCombinations(state, name).map(combination => getKeyCombinationRepresentation(combination, 'raw'));
}, (state, name) => [state[name]]);
/**
* Returns the shortcut names list for a given category name.
*
* @param {Object} state Global state.
* @param {string} name Category name.
* @example
*
*```js
* import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const categoryShortcuts = useSelect(
* ( select ) =>
* select( keyboardShortcutsStore ).getCategoryShortcuts(
* 'block'
* ),
* []
* );
*
* return (
* categoryShortcuts.length > 0 && (
* <ul>
* { categoryShortcuts.map( ( categoryShortcut ) => (
* <li key={ categoryShortcut }>{ categoryShortcut }</li>
* ) ) }
* </ul>
* )
* );
* };
*```
* @return {string[]} Shortcut names.
*/
const getCategoryShortcuts = rememo((state, categoryName) => {
return Object.entries(state).filter(([, shortcut]) => shortcut.category === categoryName).map(([name]) => name);
}, state => [state]);
@@ -601,14 +900,15 @@ const getCategoryShortcuts = rememo((state, categoryName) => {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const STORE_NAME = 'core/keyboard-shortcuts';
/**
* Store definition for the keyboard shortcuts namespace.
*
@@ -616,7 +916,6 @@ const STORE_NAME = 'core/keyboard-shortcuts';
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, {
reducer: store_reducer,
actions: actions_namespaceObject,
@@ -632,6 +931,7 @@ var external_wp_element_namespaceObject = window["wp"]["element"];
*/
/**
* Internal dependencies
*/
@@ -643,11 +943,11 @@ var external_wp_element_namespaceObject = window["wp"]["element"];
* @return {Function} A function to check if a keyboard event matches a
* predefined shortcut combination.
*/
function useShortcutEventMatch() {
const {
getAllShortcutKeyCombinations
} = (0,external_wp_data_namespaceObject.useSelect)(store);
/**
* A function to check if a keyboard event matches a predefined shortcut
* combination.
@@ -657,7 +957,6 @@ function useShortcutEventMatch() {
*
* @return {boolean} True if the event matches any shortcuts, false if not.
*/
function isMatch(name, event) {
return getAllShortcutKeyCombinations(name).some(({
modifier,
@@ -666,7 +965,6 @@ function useShortcutEventMatch() {
return external_wp_keycodes_namespaceObject.isKeyboardEvent[modifier](event, character);
});
}
return isMatch;
}
@@ -675,13 +973,33 @@ function useShortcutEventMatch() {
* WordPress dependencies
*/
const context = (0,external_wp_element_namespaceObject.createContext)();
const globalShortcuts = new Set();
const globalListener = event => {
for (const keyboardShortcut of globalShortcuts) {
keyboardShortcut(event);
}
};
const context = (0,external_wp_element_namespaceObject.createContext)({
add: shortcut => {
if (globalShortcuts.size === 0) {
document.addEventListener('keydown', globalListener);
}
globalShortcuts.add(shortcut);
},
delete: shortcut => {
globalShortcuts.delete(shortcut);
if (globalShortcuts.size === 0) {
document.removeEventListener('keydown', globalListener);
}
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/hooks/use-shortcut.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -696,71 +1014,69 @@ const context = (0,external_wp_element_namespaceObject.createContext)();
* @param {Object} options Shortcut options.
* @param {boolean} options.isDisabled Whether to disable to shortut.
*/
function useShortcut(name, callback, {
isDisabled
isDisabled = false
} = {}) {
const shortcuts = (0,external_wp_element_namespaceObject.useContext)(context);
const isMatch = useShortcutEventMatch();
const callbackRef = (0,external_wp_element_namespaceObject.useRef)();
callbackRef.current = callback;
(0,external_wp_element_namespaceObject.useEffect)(() => {
callbackRef.current = callback;
}, [callback]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isDisabled) {
return;
}
function _callback(event) {
if (isMatch(name, event)) {
callbackRef.current(event);
}
}
shortcuts.current.add(_callback);
shortcuts.add(_callback);
return () => {
shortcuts.current.delete(_callback);
shortcuts.delete(_callback);
};
}, [name, isDisabled]);
}, [name, isDisabled, shortcuts]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/components/shortcut-provider.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
Provider
} = context;
/**
* Handles callbacks added to context by `useShortcut`.
* Adding a provider allows to register contextual shortcuts
* that are only active when a certain part of the UI is focused.
*
* @param {Object} props Props to pass to `div`.
*
* @return {import('@wordpress/element').WPElement} Component.
*/
function ShortcutProvider(props) {
const keyboardShortcuts = (0,external_wp_element_namespaceObject.useRef)(new Set());
const [keyboardShortcuts] = (0,external_wp_element_namespaceObject.useState)(() => new Set());
function onKeyDown(event) {
if (props.onKeyDown) props.onKeyDown(event);
for (const keyboardShortcut of keyboardShortcuts.current) {
for (const keyboardShortcut of keyboardShortcuts) {
keyboardShortcut(event);
}
}
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (0,external_wp_element_namespaceObject.createElement)(Provider, {
value: keyboardShortcuts
}, (0,external_wp_element_namespaceObject.createElement)("div", { ...props,
}, (0,external_wp_element_namespaceObject.createElement)("div", {
...props,
onKeyDown: onKeyDown
}));
/* eslint-enable jsx-a11y/no-static-element-interactions */
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
!function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(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,{ShortcutProvider:function(){return O},__unstableUseShortcutEventMatch:function(){return E},store:function(){return C},useShortcut:function(){return D}});var n={};e.r(n),e.d(n,{registerShortcut:function(){return u},unregisterShortcut:function(){return i}});var r={};e.r(r),e.d(r,{getAllShortcutKeyCombinations:function(){return b},getAllShortcutRawKeyCombinations:function(){return m},getCategoryShortcuts:function(){return R},getShortcutAliases:function(){return w},getShortcutDescription:function(){return v},getShortcutKeyCombination:function(){return g},getShortcutRepresentation:function(){return S}});var o=window.wp.data;var a=function(e={},t){switch(t.type){case"REGISTER_SHORTCUT":return{...e,[t.name]:{category:t.category,keyCombination:t.keyCombination,aliases:t.aliases,description:t.description}};case"UNREGISTER_SHORTCUT":const{[t.name]:n,...r}=e;return r}return e};function u({name:e,category:t,description:n,keyCombination:r,aliases:o}){return{type:"REGISTER_SHORTCUT",name:e,category:t,keyCombination:r,aliases:o,description:n}}function i(e){return{type:"UNREGISTER_SHORTCUT",name:e}}var c={};function s(e){return[e]}function l(e,t,n){var r;if(e.length!==t.length)return!1;for(r=n;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function f(e,t){var n,r=t||s;function o(){n=new WeakMap}function a(){var t,o,a,u,i,s=arguments.length;for(u=new Array(s),a=0;a<s;a++)u[a]=arguments[a];for(t=function(e){var t,r,o,a,u,i=n,s=!0;for(t=0;t<e.length;t++){if(!(u=r=e[t])||"object"!=typeof u){s=!1;break}i.has(r)?i=i.get(r):(o=new WeakMap,i.set(r,o),i=o)}return i.has(c)||((a=function(){var e={clear:function(){e.head=null}};return e}()).isUniqueByDependants=s,i.set(c,a)),i.get(c)}(i=r.apply(null,u)),t.isUniqueByDependants||(t.lastDependants&&!l(i,t.lastDependants,0)&&t.clear(),t.lastDependants=i),o=t.head;o;){if(l(o.args,u,1))return o!==t.head&&(o.prev.next=o.next,o.next&&(o.next.prev=o.prev),o.next=t.head,o.prev=null,t.head.prev=o,t.head=o),o.val;o=o.next}return o={val:e.apply(null,u)},u[0]=null,o.args=u,t.head&&(t.head.prev=o,o.next=t.head),t.head=o,o.val}return a.getDependants=r,a.clear=o,o(),a}var d=window.wp.keycodes;const p=[],y={display:d.displayShortcut,raw:d.rawShortcut,ariaLabel:d.shortcutAriaLabel};function h(e,t){return e?e.modifier?y[t][e.modifier](e.character):e.character:null}function g(e,t){return e[t]?e[t].keyCombination:null}function S(e,t,n="display"){return h(g(e,t),n)}function v(e,t){return e[t]?e[t].description:null}function w(e,t){return e[t]&&e[t].aliases?e[t].aliases:p}const b=f(((e,t)=>[g(e,t),...w(e,t)].filter(Boolean)),((e,t)=>[e[t]])),m=f(((e,t)=>b(e,t).map((e=>h(e,"raw")))),((e,t)=>[e[t]])),R=f(((e,t)=>Object.entries(e).filter((([,e])=>e.category===t)).map((([e])=>e))),(e=>[e])),C=(0,o.createReduxStore)("core/keyboard-shortcuts",{reducer:a,actions:n,selectors:r});(0,o.register)(C);var T=window.wp.element;function E(){const{getAllShortcutKeyCombinations:e}=(0,o.useSelect)(C);return function(t,n){return e(t).some((({modifier:e,character:t})=>d.isKeyboardEvent[e](n,t)))}}const k=(0,T.createContext)();function D(e,t,{isDisabled:n}={}){const r=(0,T.useContext)(k),o=E(),a=(0,T.useRef)();a.current=t,(0,T.useEffect)((()=>{if(!n)return r.current.add(t),()=>{r.current.delete(t)};function t(t){o(e,t)&&a.current(t)}}),[e,n])}const{Provider:x}=k;function O(e){const t=(0,T.useRef)(new Set);return(0,T.createElement)(x,{value:t},(0,T.createElement)("div",{...e,onKeyDown:function(n){e.onKeyDown&&e.onKeyDown(n);for(const e of t.current)e(n)}}))}(window.wp=window.wp||{}).keyboardShortcuts=t}();
!function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(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,{ShortcutProvider:function(){return K},__unstableUseShortcutEventMatch:function(){return T},store:function(){return E},useShortcut:function(){return O}});var n={};e.r(n),e.d(n,{registerShortcut:function(){return i},unregisterShortcut:function(){return u}});var r={};e.r(r),e.d(r,{getAllShortcutKeyCombinations:function(){return m},getAllShortcutRawKeyCombinations:function(){return b},getCategoryShortcuts:function(){return C},getShortcutAliases:function(){return w},getShortcutDescription:function(){return g},getShortcutKeyCombination:function(){return v},getShortcutRepresentation:function(){return S}});var o=window.wp.data;var a=function(e={},t){switch(t.type){case"REGISTER_SHORTCUT":return{...e,[t.name]:{category:t.category,keyCombination:t.keyCombination,aliases:t.aliases,description:t.description}};case"UNREGISTER_SHORTCUT":const{[t.name]:n,...r}=e;return r}return e};function i({name:e,category:t,description:n,keyCombination:r,aliases:o}){return{type:"REGISTER_SHORTCUT",name:e,category:t,keyCombination:r,aliases:o,description:n}}function u(e){return{type:"UNREGISTER_SHORTCUT",name:e}}var c={};function s(e){return[e]}function l(e,t,n){var r;if(e.length!==t.length)return!1;for(r=n;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function d(e,t){var n,r=t||s;function o(){n=new WeakMap}function a(){var t,o,a,i,u,s=arguments.length;for(i=new Array(s),a=0;a<s;a++)i[a]=arguments[a];for(t=function(e){var t,r,o,a,i,u=n,s=!0;for(t=0;t<e.length;t++){if(!(i=r=e[t])||"object"!=typeof i){s=!1;break}u.has(r)?u=u.get(r):(o=new WeakMap,u.set(r,o),u=o)}return u.has(c)||((a=function(){var e={clear:function(){e.head=null}};return e}()).isUniqueByDependants=s,u.set(c,a)),u.get(c)}(u=r.apply(null,i)),t.isUniqueByDependants||(t.lastDependants&&!l(u,t.lastDependants,0)&&t.clear(),t.lastDependants=u),o=t.head;o;){if(l(o.args,i,1))return o!==t.head&&(o.prev.next=o.next,o.next&&(o.next.prev=o.prev),o.next=t.head,o.prev=null,t.head.prev=o,t.head=o),o.val;o=o.next}return o={val:e.apply(null,i)},i[0]=null,o.args=i,t.head&&(t.head.prev=o,o.next=t.head),t.head=o,o.val}return a.getDependants=r,a.clear=o,o(),a}var f=window.wp.keycodes;const p=[],y={display:f.displayShortcut,raw:f.rawShortcut,ariaLabel:f.shortcutAriaLabel};function h(e,t){return e?e.modifier?y[t][e.modifier](e.character):e.character:null}function v(e,t){return e[t]?e[t].keyCombination:null}function S(e,t,n="display"){return h(v(e,t),n)}function g(e,t){return e[t]?e[t].description:null}function w(e,t){return e[t]&&e[t].aliases?e[t].aliases:p}const m=d(((e,t)=>[v(e,t),...w(e,t)].filter(Boolean)),((e,t)=>[e[t]])),b=d(((e,t)=>m(e,t).map((e=>h(e,"raw")))),((e,t)=>[e[t]])),C=d(((e,t)=>Object.entries(e).filter((([,e])=>e.category===t)).map((([e])=>e))),(e=>[e])),E=(0,o.createReduxStore)("core/keyboard-shortcuts",{reducer:a,actions:n,selectors:r});(0,o.register)(E);var R=window.wp.element;function T(){const{getAllShortcutKeyCombinations:e}=(0,o.useSelect)(E);return function(t,n){return e(t).some((({modifier:e,character:t})=>f.isKeyboardEvent[e](n,t)))}}const k=new Set,D=e=>{for(const t of k)t(e)},x=(0,R.createContext)({add:e=>{0===k.size&&document.addEventListener("keydown",D),k.add(e)},delete:e=>{k.delete(e),0===k.size&&document.removeEventListener("keydown",D)}});function O(e,t,{isDisabled:n=!1}={}){const r=(0,R.useContext)(x),o=T(),a=(0,R.useRef)();(0,R.useEffect)((()=>{a.current=t}),[t]),(0,R.useEffect)((()=>{if(!n)return r.add(t),()=>{r.delete(t)};function t(t){o(e,t)&&a.current(t)}}),[e,n,r])}const{Provider:U}=x;function K(e){const[t]=(0,R.useState)((()=>new Set));return(0,R.createElement)(U,{value:t},(0,R.createElement)("div",{...e,onKeyDown:function(n){e.onKeyDown&&e.onKeyDown(n);for(const e of t)e(n)}}))}(window.wp=window.wp||{}).keyboardShortcuts=t}();
+78 -125
View File
@@ -39,33 +39,33 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"ALT": function() { return /* binding */ ALT; },
"BACKSPACE": function() { return /* binding */ BACKSPACE; },
"COMMAND": function() { return /* binding */ COMMAND; },
"CTRL": function() { return /* binding */ CTRL; },
"DELETE": function() { return /* binding */ DELETE; },
"DOWN": function() { return /* binding */ DOWN; },
"END": function() { return /* binding */ END; },
"ENTER": function() { return /* binding */ ENTER; },
"ESCAPE": function() { return /* binding */ ESCAPE; },
"F10": function() { return /* binding */ F10; },
"HOME": function() { return /* binding */ HOME; },
"LEFT": function() { return /* binding */ LEFT; },
"PAGEDOWN": function() { return /* binding */ PAGEDOWN; },
"PAGEUP": function() { return /* binding */ PAGEUP; },
"RIGHT": function() { return /* binding */ RIGHT; },
"SHIFT": function() { return /* binding */ SHIFT; },
"SPACE": function() { return /* binding */ SPACE; },
"TAB": function() { return /* binding */ TAB; },
"UP": function() { return /* binding */ UP; },
"ZERO": function() { return /* binding */ ZERO; },
"displayShortcut": function() { return /* binding */ displayShortcut; },
"displayShortcutList": function() { return /* binding */ displayShortcutList; },
"isAppleOS": function() { return /* reexport */ isAppleOS; },
"isKeyboardEvent": function() { return /* binding */ isKeyboardEvent; },
"modifiers": function() { return /* binding */ modifiers; },
"rawShortcut": function() { return /* binding */ rawShortcut; },
"shortcutAriaLabel": function() { return /* binding */ shortcutAriaLabel; }
ALT: function() { return /* binding */ ALT; },
BACKSPACE: function() { return /* binding */ BACKSPACE; },
COMMAND: function() { return /* binding */ COMMAND; },
CTRL: function() { return /* binding */ CTRL; },
DELETE: function() { return /* binding */ DELETE; },
DOWN: function() { return /* binding */ DOWN; },
END: function() { return /* binding */ END; },
ENTER: function() { return /* binding */ ENTER; },
ESCAPE: function() { return /* binding */ ESCAPE; },
F10: function() { return /* binding */ F10; },
HOME: function() { return /* binding */ HOME; },
LEFT: function() { return /* binding */ LEFT; },
PAGEDOWN: function() { return /* binding */ PAGEDOWN; },
PAGEUP: function() { return /* binding */ PAGEUP; },
RIGHT: function() { return /* binding */ RIGHT; },
SHIFT: function() { return /* binding */ SHIFT; },
SPACE: function() { return /* binding */ SPACE; },
TAB: function() { return /* binding */ TAB; },
UP: function() { return /* binding */ UP; },
ZERO: function() { return /* binding */ ZERO; },
displayShortcut: function() { return /* binding */ displayShortcut; },
displayShortcutList: function() { return /* binding */ displayShortcutList; },
isAppleOS: function() { return /* reexport */ isAppleOS; },
isKeyboardEvent: function() { return /* binding */ isKeyboardEvent; },
modifiers: function() { return /* binding */ modifiers; },
rawShortcut: function() { return /* binding */ rawShortcut; },
shortcutAriaLabel: function() { return /* binding */ shortcutAriaLabel; }
});
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.mjs
@@ -365,7 +365,7 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object") throw new TypeError("Object expected.");
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
@@ -556,10 +556,8 @@ function isAppleOS(_window = null) {
if (typeof window === 'undefined') {
return false;
}
_window = window;
}
const {
platform
} = _window.navigator;
@@ -582,6 +580,7 @@ function isAppleOS(_window = null) {
* External dependencies
*/
/**
* WordPress dependencies
*/
@@ -610,7 +609,6 @@ function isAppleOS(_window = null) {
*
* @typedef {(character: string, isApple?: () => boolean) => T} WPKeyHandler
*/
/** @typedef {(event: import('react').KeyboardEvent<HTMLElement> | KeyboardEvent, character: string, isApple?: () => boolean) => boolean} WPEventKeyHandler */
/** @typedef {( isApple: () => boolean ) => WPModifierPart[]} WPModifier */
@@ -618,104 +616,104 @@ function isAppleOS(_window = null) {
/**
* Keycode for BACKSPACE key.
*/
const BACKSPACE = 8;
/**
* Keycode for TAB key.
*/
const TAB = 9;
/**
* Keycode for ENTER key.
*/
const ENTER = 13;
/**
* Keycode for ESCAPE key.
*/
const ESCAPE = 27;
/**
* Keycode for SPACE key.
*/
const SPACE = 32;
/**
* Keycode for PAGEUP key.
*/
const PAGEUP = 33;
/**
* Keycode for PAGEDOWN key.
*/
const PAGEDOWN = 34;
/**
* Keycode for END key.
*/
const END = 35;
/**
* Keycode for HOME key.
*/
const HOME = 36;
/**
* Keycode for LEFT key.
*/
const LEFT = 37;
/**
* Keycode for UP key.
*/
const UP = 38;
/**
* Keycode for RIGHT key.
*/
const RIGHT = 39;
/**
* Keycode for DOWN key.
*/
const DOWN = 40;
/**
* Keycode for DELETE key.
*/
const DELETE = 46;
/**
* Keycode for F10 key.
*/
const F10 = 121;
/**
* Keycode for ALT key.
*/
const ALT = 'alt';
/**
* Keycode for CTRL key.
*/
const CTRL = 'ctrl';
/**
* Keycode for COMMAND/META key.
*/
const COMMAND = 'meta';
/**
* Keycode for SHIFT key.
*/
const SHIFT = 'shift';
/**
* Keycode for ZERO key.
*/
const ZERO = 48;
/**
* Map the values of an object with a specified callback and return the result object.
*
@@ -726,18 +724,16 @@ const ZERO = 48;
*
* @return {any} Active modifier constants.
*/
function mapValues(object, mapFn) {
return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, mapFn(value)]));
}
/**
* Object that contains functions that return the available modifier
* depending on platform.
*
* @type {WPModifierHandler< ( isApple: () => boolean ) => WPModifierPart[]>}
*/
const modifiers = {
primary: _isApple => _isApple() ? [COMMAND] : [CTRL],
primaryShift: _isApple => _isApple() ? [SHIFT, COMMAND] : [CTRL, SHIFT],
@@ -751,6 +747,7 @@ const modifiers = {
shiftAlt: () => [SHIFT, ALT],
undefined: () => []
};
/**
* An object that contains functions to get raw shortcuts.
*
@@ -766,17 +763,13 @@ const modifiers = {
* @type {WPModifierHandler<WPKeyHandler<string>>} Keyed map of functions to raw
* shortcuts.
*/
const rawShortcut = mapValues(modifiers, (
/** @type {WPModifier} */
modifier) => {
return (
/** @type {WPKeyHandler<string>} */
(character, _isApple = isAppleOS) => {
const rawShortcut = mapValues(modifiers, ( /** @type {WPModifier} */modifier) => {
return (/** @type {WPKeyHandler<string>} */(character, _isApple = isAppleOS) => {
return [...modifier(_isApple), character.toLowerCase()].join('+');
}
);
});
/**
* Return an array of the parts of a keyboard shortcut chord for display.
*
@@ -790,15 +783,9 @@ modifier) => {
* @type {WPModifierHandler<WPKeyHandler<string[]>>} Keyed map of functions to
* shortcut sequences.
*/
const displayShortcutList = mapValues(modifiers, (
/** @type {WPModifier} */
modifier) => {
return (
/** @type {WPKeyHandler<string[]>} */
(character, _isApple = isAppleOS) => {
const displayShortcutList = mapValues(modifiers, ( /** @type {WPModifier} */modifier) => {
return (/** @type {WPKeyHandler<string[]>} */(character, _isApple = isAppleOS) => {
const isApple = _isApple();
const replacementKeyMap = {
[ALT]: isApple ? '⌥' : 'Alt',
[CTRL]: isApple ? '⌃' : 'Ctrl',
@@ -808,20 +795,17 @@ modifier) => {
};
const modifierKeys = modifier(_isApple).reduce((accumulator, key) => {
var _replacementKeyMap$ke;
const replacementKey = (_replacementKeyMap$ke = replacementKeyMap[key]) !== null && _replacementKeyMap$ke !== void 0 ? _replacementKeyMap$ke : key; // If on the Mac, adhere to platform convention and don't show plus between keys.
const replacementKey = (_replacementKeyMap$ke = replacementKeyMap[key]) !== null && _replacementKeyMap$ke !== void 0 ? _replacementKeyMap$ke : key;
// If on the Mac, adhere to platform convention and don't show plus between keys.
if (isApple) {
return [...accumulator, replacementKey];
}
return [...accumulator, replacementKey, '+'];
},
/** @type {string[]} */
[]); // Symbols (~`,.) are removed by the default regular expression,
}, /** @type {string[]} */[]);
// Symbols (~`,.) are removed by the default regular expression,
// so override the rule to allow symbols used for shortcuts.
// see: https://github.com/blakeembrey/change-case#options
const capitalizedCharacter = capitalCase(character, {
stripRegexp: /[^A-Z0-9~`,\.\\\-]/gi
});
@@ -829,6 +813,7 @@ modifier) => {
}
);
});
/**
* An object that contains functions to display shortcuts.
*
@@ -842,15 +827,11 @@ modifier) => {
* @type {WPModifierHandler<WPKeyHandler<string>>} Keyed map of functions to
* display shortcuts.
*/
const displayShortcut = mapValues(displayShortcutList, (
/** @type {WPKeyHandler<string[]>} */
shortcutList) => {
return (
/** @type {WPKeyHandler<string>} */
(character, _isApple = isAppleOS) => shortcutList(character, _isApple).join('')
const displayShortcut = mapValues(displayShortcutList, ( /** @type {WPKeyHandler<string[]>} */shortcutList) => {
return (/** @type {WPKeyHandler<string>} */(character, _isApple = isAppleOS) => shortcutList(character, _isApple).join('')
);
});
/**
* An object that contains functions to return an aria label for a keyboard
* shortcut.
@@ -865,43 +846,32 @@ shortcutList) => {
* @type {WPModifierHandler<WPKeyHandler<string>>} Keyed map of functions to
* shortcut ARIA labels.
*/
const shortcutAriaLabel = mapValues(modifiers, (
/** @type {WPModifier} */
modifier) => {
return (
/** @type {WPKeyHandler<string>} */
(character, _isApple = isAppleOS) => {
const shortcutAriaLabel = mapValues(modifiers, ( /** @type {WPModifier} */modifier) => {
return (/** @type {WPKeyHandler<string>} */(character, _isApple = isAppleOS) => {
const isApple = _isApple();
/** @type {Record<string,string>} */
const replacementKeyMap = {
[SHIFT]: 'Shift',
[COMMAND]: isApple ? 'Command' : 'Control',
[CTRL]: 'Control',
[ALT]: isApple ? 'Option' : 'Alt',
/* translators: comma as in the character ',' */
',': (0,external_wp_i18n_namespaceObject.__)('Comma'),
/* translators: period as in the character '.' */
'.': (0,external_wp_i18n_namespaceObject.__)('Period'),
/* translators: backtick as in the character '`' */
'`': (0,external_wp_i18n_namespaceObject.__)('Backtick'),
/* translators: tilde as in the character '~' */
'~': (0,external_wp_i18n_namespaceObject.__)('Tilde')
};
return [...modifier(_isApple), character].map(key => {
var _replacementKeyMap$ke2;
return capitalCase((_replacementKeyMap$ke2 = replacementKeyMap[key]) !== null && _replacementKeyMap$ke2 !== void 0 ? _replacementKeyMap$ke2 : key);
}).join(isApple ? ' ' : ' + ');
}
);
});
/**
* From a given KeyboardEvent, returns an array of active modifier constants for
* the event.
@@ -910,15 +880,12 @@ modifier) => {
*
* @return {Array<WPModifierPart>} Active modifier constants.
*/
function getEventModifiers(event) {
return (
/** @type {WPModifierPart[]} */
[ALT, CTRL, COMMAND, SHIFT].filter(key => event[
/** @type {'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey'} */
return (/** @type {WPModifierPart[]} */[ALT, CTRL, COMMAND, SHIFT].filter(key => event[/** @type {'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey'} */
`${key}Key`])
);
}
/**
* An object that contains functions to check if a keyboard event matches a
* predefined shortcut combination.
@@ -933,18 +900,11 @@ function getEventModifiers(event) {
* @type {WPModifierHandler<WPEventKeyHandler>} Keyed map of functions
* to match events.
*/
const isKeyboardEvent = mapValues(modifiers, (
/** @type {WPModifier} */
getModifiers) => {
return (
/** @type {WPEventKeyHandler} */
(event, character, _isApple = isAppleOS) => {
const isKeyboardEvent = mapValues(modifiers, ( /** @type {WPModifier} */getModifiers) => {
return (/** @type {WPEventKeyHandler} */(event, character, _isApple = isAppleOS) => {
const mods = getModifiers(_isApple);
const eventMods = getEventModifiers(event);
/** @type {Record<string,string>} */
const replacementWithShiftKeyMap = {
Comma: ',',
Backslash: '\\',
@@ -954,37 +914,30 @@ getModifiers) => {
};
const modsDiff = mods.filter(mod => !eventMods.includes(mod));
const eventModsDiff = eventMods.filter(mod => !mods.includes(mod));
if (modsDiff.length > 0 || eventModsDiff.length > 0) {
return false;
}
let key = event.key.toLowerCase();
if (!character) {
return mods.includes(
/** @type {WPModifierPart} */
key);
return mods.includes( /** @type {WPModifierPart} */key);
}
if (event.altKey && character.length === 1) {
key = String.fromCharCode(event.keyCode).toLowerCase();
} // `event.key` returns the value of the key pressed, taking into the state of
}
// `event.key` returns the value of the key pressed, taking into the state of
// modifier keys such as `Shift`. If the shift key is pressed, a different
// value may be returned depending on the keyboard layout. It is necessary to
// convert to the physical key value that don't take into account keyboard
// layout or modifier key state.
if (event.shiftKey && character.length === 1 && replacementWithShiftKeyMap[event.code]) {
key = replacementWithShiftKeyMap[event.code];
} // For backwards compatibility.
}
// For backwards compatibility.
if (character === 'del') {
character = 'delete';
}
return key === character.toLowerCase();
}
);
+16 -44
View File
@@ -350,7 +350,7 @@ function __classPrivateFieldIn(state, receiver) {
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object") throw new TypeError("Object expected.");
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
@@ -536,9 +536,10 @@ var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_w
function download(fileName, content, contentType) {
const file = new window.Blob([content], {
type: contentType
}); // IE11 can't use the click to download technique
// we use a specific IE11 technique instead.
});
// IE11 can't use the click to download technique
// we use a specific IE11 technique instead.
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, fileName);
} else {
@@ -551,20 +552,19 @@ function download(fileName, content, contentType) {
document.body.removeChild(a);
}
}
/**
* Reads the textual content of the given file.
*
* @param {File} file File.
* @return {Promise<string>} Content of the file.
*/
function readTextFile(file) {
const reader = new window.FileReader();
return new Promise(resolve => {
reader.onload = () => {
resolve(reader.result);
};
reader.readAsText(file);
});
}
@@ -574,6 +574,7 @@ function readTextFile(file) {
* External dependencies
*/
/**
* WordPress dependencies
*/
@@ -589,7 +590,6 @@ function readTextFile(file) {
*
* @param {number} id
*/
async function exportReusableBlock(id) {
const postType = await external_wp_apiFetch_default()({
path: `/wp/v2/types/wp_block`
@@ -609,7 +609,6 @@ async function exportReusableBlock(id) {
const fileName = paramCase(title) + '.json';
download(fileName, fileContent, 'application/json');
}
/* harmony default export */ var utils_export = (exportReusableBlock);
;// CONCATENATED MODULE: external ["wp","compose"]
@@ -621,6 +620,7 @@ var external_wp_components_namespaceObject = window["wp"]["components"];
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -632,21 +632,17 @@ var external_wp_components_namespaceObject = window["wp"]["components"];
* @param {File} file File.
* @return {Promise} Promise returning the imported reusable block.
*/
async function importReusableBlock(file) {
const fileContent = await readTextFile(file);
let parsedContent;
try {
parsedContent = JSON.parse(fileContent);
} catch (e) {
throw new Error('Invalid JSON file');
}
if (parsedContent.__file !== 'wp_block' || !parsedContent.title || !parsedContent.content || typeof parsedContent.title !== 'string' || typeof parsedContent.content !== 'string' || parsedContent.syncStatus && typeof parsedContent.syncStatus !== 'string') {
throw new Error('Invalid Pattern JSON file');
throw new Error('Invalid pattern JSON file');
}
const postType = await external_wp_apiFetch_default()({
path: `/wp/v2/types/wp_block`
});
@@ -664,12 +660,10 @@ async function importReusableBlock(file) {
});
return reusableBlock;
}
/* harmony default export */ var utils_import = (importReusableBlock);
;// CONCATENATED MODULE: ./node_modules/@wordpress/list-reusable-blocks/build-module/components/import-form/index.js
/**
* WordPress dependencies
*/
@@ -677,12 +671,11 @@ async function importReusableBlock(file) {
/**
* Internal dependencies
*/
function ImportForm({
instanceId,
onUpload
@@ -692,19 +685,15 @@ function ImportForm({
const [isLoading, setIsLoading] = (0,external_wp_element_namespaceObject.useState)(false);
const [error, setError] = (0,external_wp_element_namespaceObject.useState)(null);
const [file, setFile] = (0,external_wp_element_namespaceObject.useState)(null);
const onChangeFile = event => {
setFile(event.target.files[0]);
setError(null);
};
const onSubmit = event => {
event.preventDefault();
if (!file) {
return;
}
setIsLoading({
isLoading: true
});
@@ -712,38 +701,30 @@ function ImportForm({
if (!formRef) {
return;
}
setIsLoading(false);
onUpload(reusableBlock);
}).catch(errors => {
if (!formRef) {
return;
}
let uiMessage;
switch (errors.message) {
case 'Invalid JSON file':
uiMessage = (0,external_wp_i18n_namespaceObject.__)('Invalid JSON file');
break;
case 'Invalid Pattern JSON file':
uiMessage = (0,external_wp_i18n_namespaceObject.__)('Invalid Pattern JSON file');
case 'Invalid pattern JSON file':
uiMessage = (0,external_wp_i18n_namespaceObject.__)('Invalid pattern JSON file');
break;
default:
uiMessage = (0,external_wp_i18n_namespaceObject.__)('Unknown error');
}
setIsLoading(false);
setError(uiMessage);
});
};
const onDismissError = () => {
setError(null);
};
return (0,external_wp_element_namespaceObject.createElement)("form", {
className: "list-reusable-blocks-import-form",
onSubmit: onSubmit,
@@ -766,24 +747,21 @@ function ImportForm({
className: "list-reusable-blocks-import-form__button"
}, (0,external_wp_i18n_namespaceObject._x)('Import', 'button label')));
}
/* harmony default export */ var import_form = ((0,external_wp_compose_namespaceObject.withInstanceId)(ImportForm));
;// CONCATENATED MODULE: ./node_modules/@wordpress/list-reusable-blocks/build-module/components/import-dropdown/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ImportDropdown({
onUpload
}) {
@@ -807,53 +785,47 @@ function ImportDropdown({
})
});
}
/* harmony default export */ var import_dropdown = (ImportDropdown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/list-reusable-blocks/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Setup Export Links.
// Setup Export Links.
document.body.addEventListener('click', event => {
if (!event.target.classList.contains('wp-list-reusable-blocks__export')) {
return;
}
event.preventDefault();
utils_export(event.target.dataset.id);
}); // Setup Import Form.
});
// Setup Import Form.
document.addEventListener('DOMContentLoaded', () => {
const button = document.querySelector('.page-title-action');
if (!button) {
return;
}
const showNotice = () => {
const notice = document.createElement('div');
notice.className = 'notice notice-success is-dismissible';
notice.innerHTML = `<p>${(0,external_wp_i18n_namespaceObject.__)('Pattern imported successfully!')}</p>`;
const headerEnd = document.querySelector('.wp-header-end');
if (!headerEnd) {
return;
}
headerEnd.parentNode.insertBefore(notice, headerEnd);
};
const container = document.createElement('div');
container.className = 'list-reusable-blocks__container';
button.parentNode.insertBefore(container, button);
File diff suppressed because one or more lines are too long
+98 -139
View File
@@ -51,8 +51,8 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"MediaUpload": function() { return /* reexport */ media_upload; },
"uploadMedia": function() { return /* reexport */ uploadMedia; }
MediaUpload: function() { return /* reexport */ media_upload; },
uploadMedia: function() { return /* reexport */ uploadMedia; }
});
;// CONCATENATED MODULE: external ["wp","element"]
@@ -66,12 +66,12 @@ var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
const DEFAULT_EMPTY_GALLERY = [];
/**
* Prepares the Featured Image toolbars and frames.
*
* @return {window.wp.media.view.MediaFrame.Select} The default media workflow.
*/
const getFeaturedImageMediaFrame = () => {
const {
wp
@@ -89,7 +89,6 @@ const getFeaturedImageMediaFrame = () => {
state: this.options.state
});
},
/**
* Handle the edit state requirements of selected media item.
*
@@ -100,13 +99,14 @@ const getFeaturedImageMediaFrame = () => {
const view = new wp.media.view.EditImage({
model: selection.single(),
controller: this
}).render(); // Set the view to the EditImage frame using the selected image.
}).render();
this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
// Set the view to the EditImage frame using the selected image.
this.content.set(view);
// After bringing in the frame, load the actual editor via an ajax call.
view.loadEditor();
},
/**
* Create the default states.
*
@@ -121,13 +121,12 @@ const getFeaturedImageMediaFrame = () => {
}
});
};
/**
* Prepares the Gallery toolbars and frames.
*
* @return {window.wp.media.view.MediaFrame.Post} The default media workflow.
*/
const getGalleryDetailsMediaFrame = () => {
const {
wp
@@ -139,7 +138,6 @@ const getGalleryDetailsMediaFrame = () => {
* @class GalleryDetailsMediaFrame
* @class
*/
return wp.media.view.MediaFrame.Post.extend({
/**
* Set up gallery toolbar.
@@ -158,25 +156,23 @@ const getGalleryDetailsMediaFrame = () => {
requires: {
library: true
},
/**
* @fires wp.media.controller.State#update
*/
click() {
const controller = this.controller,
state = controller.state();
state = controller.state();
controller.close();
state.trigger('update', state.get('library')); // Restore and reset the default state.
state.trigger('update', state.get('library'));
// Restore and reset the default state.
controller.setState(controller.options.state);
controller.reset();
}
}
}
}));
},
/**
* Handle the edit state requirements of selected media item.
*
@@ -187,13 +183,14 @@ const getGalleryDetailsMediaFrame = () => {
const view = new wp.media.view.EditImage({
model: selection.single(),
controller: this
}).render(); // Set the view to the EditImage frame using the selected image.
}).render();
this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
// Set the view to the EditImage frame using the selected image.
this.content.set(view);
// After bringing in the frame, load the actual editor via an ajax call.
view.loadEditor();
},
/**
* Create the default states.
*
@@ -225,21 +222,19 @@ const getGalleryDetailsMediaFrame = () => {
}), new wp.media.controller.GalleryAdd()]);
}
});
}; // The media library image object contains numerous attributes
};
// The media library image object contains numerous attributes
// we only need this set to display the image in the library.
const slimImageObject = img => {
const attrSet = ['sizes', 'mime', 'type', 'subtype', 'id', 'url', 'alt', 'link', 'caption'];
return attrSet.reduce((result, key) => {
if (img?.hasOwnProperty(key)) {
result[key] = img[key];
}
return result;
}, {});
};
const getAttachmentsCollection = ids => {
const {
wp
@@ -253,7 +248,6 @@ const getAttachmentsCollection = ids => {
type: 'image'
});
};
class MediaUpload extends external_wp_element_namespaceObject.Component {
constructor({
allowedTypes,
@@ -272,7 +266,6 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
const {
wp
} = window;
if (gallery) {
this.buildAndSetGalleryFrame();
} else {
@@ -280,27 +273,21 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
title,
multiple
};
if (!!allowedTypes) {
frameConfig.library = {
type: allowedTypes
};
}
this.frame = wp.media(frameConfig);
}
if (modalClass) {
this.frame.$el.addClass(modalClass);
}
if (unstableFeaturedImageFlow) {
this.buildAndSetFeatureImageFrame();
}
this.initializeListeners();
}
initializeListeners() {
// When an image is selected in the media frame...
this.frame.on('select', this.onSelect);
@@ -308,47 +295,43 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
this.frame.on('open', this.onOpen);
this.frame.on('close', this.onClose);
}
/**
* Sets the Gallery frame and initializes listeners.
*
* @return {void}
*/
buildAndSetGalleryFrame() {
const {
addToGallery = false,
allowedTypes,
multiple = false,
value = DEFAULT_EMPTY_GALLERY
} = this.props; // If the value did not changed there is no need to rebuild the frame,
// we can continue to use the existing one.
} = this.props;
// If the value did not changed there is no need to rebuild the frame,
// we can continue to use the existing one.
if (value === this.lastGalleryValue) {
return;
}
const {
wp
} = window;
this.lastGalleryValue = value; // If a frame already existed remove it.
this.lastGalleryValue = value;
// If a frame already existed remove it.
if (this.frame) {
this.frame.remove();
}
let currentState;
if (addToGallery) {
currentState = 'gallery-library';
} else {
currentState = value && value.length ? 'gallery-edit' : 'gallery';
}
if (!this.GalleryDetailsMediaFrame) {
this.GalleryDetailsMediaFrame = getGalleryDetailsMediaFrame();
}
const attachments = getAttachmentsCollection(value);
const selection = new wp.media.model.Selection(attachments.models, {
props: attachments.props.toJSON(),
@@ -364,13 +347,12 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
wp.media.frame = this.frame;
this.initializeListeners();
}
/**
* Initializes the Media Library requirements for the featured image flow.
*
* @return {void}
*/
buildAndSetFeatureImageFrame() {
const {
wp
@@ -389,11 +371,9 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
});
wp.media.frame = this.frame;
}
componentWillUnmount() {
this.frame.remove();
}
onUpdate(selections) {
const {
onSelect,
@@ -401,28 +381,24 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
} = this.props;
const state = this.frame.state();
const selectedImages = selections || state.get('selection');
if (!selectedImages || !selectedImages.models.length) {
return;
}
if (multiple) {
onSelect(selectedImages.models.map(model => slimImageObject(model.toJSON())));
} else {
onSelect(slimImageObject(selectedImages.models[0].toJSON()));
}
}
onSelect() {
const {
onSelect,
multiple = false
} = this.props; // Get media attachment details from the frame state.
} = this.props;
// Get media attachment details from the frame state.
const attachment = this.frame.state().get('selection').toJSON();
onSelect(multiple ? attachment : attachment[0]);
}
onOpen() {
const {
wp
@@ -430,80 +406,73 @@ class MediaUpload extends external_wp_element_namespaceObject.Component {
const {
value
} = this.props;
this.updateCollection(); //Handle active tab in media model on model open.
this.updateCollection();
//Handle active tab in media model on model open.
if (this.props.mode) {
this.frame.content.mode(this.props.mode);
} // Handle both this.props.value being either (number[]) multiple ids
}
// Handle both this.props.value being either (number[]) multiple ids
// (for galleries) or a (number) singular id (e.g. image block).
const hasMedia = Array.isArray(value) ? !!value?.length : !!value;
if (!hasMedia) {
return;
}
const isGallery = this.props.gallery;
const selection = this.frame.state().get('selection');
const valueArray = Array.isArray(value) ? value : [value];
if (!isGallery) {
valueArray.forEach(id => {
selection.add(wp.media.attachment(id));
});
} // Load the images so they are available in the media modal.
}
// Load the images so they are available in the media modal.
const attachments = getAttachmentsCollection(valueArray);
const attachments = getAttachmentsCollection(valueArray); // Once attachments are loaded, set the current selection.
// Once attachments are loaded, set the current selection.
attachments.more().done(function () {
if (isGallery && attachments?.models?.length) {
selection.add(attachments.models);
}
});
}
onClose() {
const {
onClose
} = this.props;
if (onClose) {
onClose();
}
}
updateCollection() {
const frameContent = this.frame.content.get();
if (frameContent && frameContent.collection) {
const collection = frameContent.collection; // Clean all attachments we have in memory.
const collection = frameContent.collection;
collection.toArray().forEach(model => model.trigger('destroy', model)); // Reset has more flag, if library had small amount of items all items may have been loaded before.
// Clean all attachments we have in memory.
collection.toArray().forEach(model => model.trigger('destroy', model));
collection.mirroring._hasMore = true; // Request items.
// Reset has more flag, if library had small amount of items all items may have been loaded before.
collection.mirroring._hasMore = true;
// Request items.
collection.more();
}
}
openModal() {
if (this.props.gallery) {
this.buildAndSetGalleryFrame();
}
this.frame.open();
}
render() {
return this.props.render({
open: this.openModal
});
}
}
/* harmony default export */ var media_upload = (MediaUpload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/index.js
@@ -521,8 +490,8 @@ var external_wp_blob_namespaceObject = window["wp"]["blob"];
const noop = () => {};
/**
* 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.
@@ -536,19 +505,17 @@ const noop = () => {};
*
* @return {?Array} An array of mime types or the parameter passed if it was "falsy".
*/
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.
@@ -564,7 +531,6 @@ function getMimeTypesArray(wpMimeTypesObject) {
* @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({
allowedTypes,
additionalData = {},
@@ -577,109 +543,105 @@ async function uploadMedia({
// 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.
};
// 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.
}
// 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.
};
// 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) {
// 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.
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
});
continue;
} // Check if the 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
});
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
});
continue;
}
validFiles.push(mediaFile); // Set temporary URL to create placeholder media file, this is replaced
// with final file from media gallery when upload is `done` below.
// Check if the 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
});
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
});
continue;
}
validFiles.push(mediaFile);
// Set temporary URL to create placeholder media file, this is replaced
// with final file from media gallery when upload is `done` below.
filesSet.push({
url: (0,external_wp_blob_namespaceObject.createBlobURL)(mediaFile)
});
onFileChange(filesSet);
}
for (let idx = 0; idx < validFiles.length; ++idx) {
const mediaFile = validFiles[idx];
try {
var _savedMedia$caption$r;
const savedMedia = await createMediaFromFile(mediaFile, additionalData); // eslint-disable-next-line camelcase
const savedMedia = await createMediaFromFile(mediaFile, additionalData);
// eslint-disable-next-line camelcase
const {
alt_text,
source_url,
...savedMediaProps
} = savedMedia;
const mediaObject = { ...savedMediaProps,
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,
@@ -690,14 +652,13 @@ async function uploadMedia({
// Reset to empty on failure.
setAndUpdateFiles(idx, null);
let message;
if (error.message) {
message = error.message;
} else {
message = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: file name
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);
}
onError({
code: 'GENERAL',
message,
@@ -706,22 +667,20 @@ async function uploadMedia({
}
}
}
/**
* @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,
+35 -41
View File
@@ -39,28 +39,28 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"store": function() { return /* reexport */ store; }
store: function() { return /* reexport */ store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/notices/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"createErrorNotice": function() { return createErrorNotice; },
"createInfoNotice": function() { return createInfoNotice; },
"createNotice": function() { return createNotice; },
"createSuccessNotice": function() { return createSuccessNotice; },
"createWarningNotice": function() { return createWarningNotice; },
"removeAllNotices": function() { return removeAllNotices; },
"removeNotice": function() { return removeNotice; },
"removeNotices": function() { return removeNotices; }
createErrorNotice: function() { return createErrorNotice; },
createInfoNotice: function() { return createInfoNotice; },
createNotice: function() { return createNotice; },
createSuccessNotice: function() { return createSuccessNotice; },
createWarningNotice: function() { return createWarningNotice; },
removeAllNotices: function() { return removeAllNotices; },
removeNotice: function() { return removeNotice; },
removeNotices: function() { return removeNotices; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/notices/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"getNotices": function() { return getNotices; }
getNotices: function() { return getNotices; }
});
;// CONCATENATED MODULE: external ["wp","data"]
@@ -78,20 +78,18 @@ const onSubKey = actionProperty => reducer => (state = {}, action) => {
// Retrieve subkey from action. Do not track if undefined; useful for cases
// where reducer is scoped by action shape.
const key = action[actionProperty];
if (key === undefined) {
return state;
} // Avoid updating state if unchanged. Note that this also accounts for a
// reducer which returns undefined on a key which is not yet tracked.
const nextKeyState = reducer(state[key], action);
if (nextKeyState === state[key]) {
return state;
}
return { ...state,
// Avoid updating state if unchanged. Note that this also accounts for a
// reducer which returns undefined on a key which is not yet tracked.
const nextKeyState = reducer(state[key], action);
if (nextKeyState === state[key]) {
return state;
}
return {
...state,
[key]: nextKeyState
};
};
@@ -102,6 +100,7 @@ const onSubKey = actionProperty => reducer => (state = {}, action) => {
* Internal dependencies
*/
/**
* Reducer returning the next notices state. The notices state is an object
* where each key is a context, its value an array of notice objects.
@@ -111,7 +110,6 @@ const onSubKey = actionProperty => reducer => (state = {}, action) => {
*
* @return {Object} Updated state.
*/
const notices = on_sub_key('context')((state = [], action) => {
switch (action.type) {
case 'CREATE_NOTICE':
@@ -119,23 +117,19 @@ const notices = on_sub_key('context')((state = [], action) => {
return [...state.filter(({
id
}) => id !== action.notice.id), action.notice];
case 'REMOVE_NOTICE':
return state.filter(({
id
}) => id !== action.id);
case 'REMOVE_NOTICES':
return state.filter(({
id
}) => !action.ids.includes(id));
case 'REMOVE_ALL_NOTICES':
return state.filter(({
type
}) => type !== action.noticeType);
}
return state;
});
/* harmony default export */ var reducer = (notices);
@@ -149,12 +143,12 @@ const notices = on_sub_key('context')((state = [], action) => {
* @type {string}
*/
const DEFAULT_CONTEXT = 'global';
/**
* Default notice status.
*
* @type {string}
*/
const DEFAULT_STATUS = 'info';
;// CONCATENATED MODULE: ./node_modules/@wordpress/notices/build-module/store/actions.js
@@ -162,6 +156,7 @@ const DEFAULT_STATUS = 'info';
* Internal dependencies
*/
/**
* @typedef {Object} WPNoticeAction Object describing a user action option associated with a notice.
*
@@ -170,10 +165,10 @@ const DEFAULT_STATUS = 'info';
* browser navigation.
* @property {?Function} onClick Optional function to invoke when action is
* triggered by user.
*
*/
let uniqueId = 0;
/**
* Returns an action object used in signalling that a notice is to be created.
*
@@ -225,7 +220,6 @@ let uniqueId = 0;
*
* @return {Object} Action object.
*/
function createNotice(status = DEFAULT_STATUS, content, options = {}) {
const {
speak = true,
@@ -238,10 +232,11 @@ function createNotice(status = DEFAULT_STATUS, content, options = {}) {
icon = null,
explicitDismiss = false,
onDismiss
} = options; // The supported value shape of content is currently limited to plain text
} = options;
// The supported value shape of content is currently limited to plain text
// strings. To avoid setting expectation that e.g. a WPElement could be
// supported, cast to a string.
content = String(content);
return {
type: 'CREATE_NOTICE',
@@ -261,6 +256,7 @@ function createNotice(status = DEFAULT_STATUS, content, options = {}) {
}
};
}
/**
* Returns an action object used in signalling that a success notice is to be
* created. Refer to `createNotice` for options documentation.
@@ -296,10 +292,10 @@ function createNotice(status = DEFAULT_STATUS, content, options = {}) {
*
* @return {Object} Action object.
*/
function createSuccessNotice(content, options) {
return createNotice('success', content, options);
}
/**
* Returns an action object used in signalling that an info notice is to be
* created. Refer to `createNotice` for options documentation.
@@ -334,10 +330,10 @@ function createSuccessNotice(content, options) {
*
* @return {Object} Action object.
*/
function createInfoNotice(content, options) {
return createNotice('info', content, options);
}
/**
* Returns an action object used in signalling that an error notice is to be
* created. Refer to `createNotice` for options documentation.
@@ -375,10 +371,10 @@ function createInfoNotice(content, options) {
*
* @return {Object} Action object.
*/
function createErrorNotice(content, options) {
return createNotice('error', content, options);
}
/**
* Returns an action object used in signalling that a warning notice is to be
* created. Refer to `createNotice` for options documentation.
@@ -417,10 +413,10 @@ function createErrorNotice(content, options) {
*
* @return {Object} Action object.
*/
function createWarningNotice(content, options) {
return createNotice('warning', content, options);
}
/**
* Returns an action object used in signalling that a notice is to be removed.
*
@@ -462,7 +458,6 @@ function createWarningNotice(content, options) {
*
* @return {Object} Action object.
*/
function removeNotice(id, context = DEFAULT_CONTEXT) {
return {
type: 'REMOVE_NOTICE',
@@ -470,6 +465,7 @@ function removeNotice(id, context = DEFAULT_CONTEXT) {
context
};
}
/**
* Removes all notices from a given context. Defaults to the default context.
*
@@ -516,7 +512,6 @@ function removeNotice(id, context = DEFAULT_CONTEXT) {
*
* @return {Object} Action object.
*/
function removeAllNotices(noticeType = 'default', context = DEFAULT_CONTEXT) {
return {
type: 'REMOVE_ALL_NOTICES',
@@ -524,6 +519,7 @@ function removeAllNotices(noticeType = 'default', context = DEFAULT_CONTEXT) {
context
};
}
/**
* Returns an action object used in signalling that several notices are to be removed.
*
@@ -562,7 +558,6 @@ function removeAllNotices(noticeType = 'default', context = DEFAULT_CONTEXT) {
* ```
* @return {Object} Action object.
*/
function removeNotices(ids, context = DEFAULT_CONTEXT) {
return {
type: 'REMOVE_NOTICES',
@@ -576,6 +571,7 @@ function removeNotices(ids, context = DEFAULT_CONTEXT) {
* Internal dependencies
*/
/** @typedef {import('./actions').WPNoticeAction} WPNoticeAction */
/**
@@ -587,8 +583,8 @@ function removeNotices(ids, context = DEFAULT_CONTEXT) {
*
* @type {Array}
*/
const DEFAULT_NOTICES = [];
/**
* @typedef {Object} WPNotice Notice object.
*
@@ -612,7 +608,6 @@ const DEFAULT_NOTICES = [];
* announced to screen readers. Defaults to
* `true`.
* @property {WPNoticeAction[]} actions User actions to present with notice.
*
*/
/**
@@ -642,7 +637,6 @@ const DEFAULT_NOTICES = [];
*
* @return {WPNotice[]} Array of notices.
*/
function getNotices(state, context = DEFAULT_CONTEXT) {
return state[context] || DEFAULT_NOTICES;
}
@@ -652,6 +646,7 @@ function getNotices(state, context = DEFAULT_CONTEXT) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -664,7 +659,6 @@ function getNotices(state, context = DEFAULT_CONTEXT) {
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)('core/notices', {
reducer: reducer,
actions: actions_namespaceObject,
+26 -44
View File
@@ -51,27 +51,27 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"DotTip": function() { return /* reexport */ dot_tip; },
"store": function() { return /* reexport */ store; }
DotTip: function() { return /* reexport */ dot_tip; },
store: function() { return /* reexport */ store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/nux/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"disableTips": function() { return disableTips; },
"dismissTip": function() { return dismissTip; },
"enableTips": function() { return enableTips; },
"triggerGuide": function() { return triggerGuide; }
disableTips: function() { return disableTips; },
dismissTip: function() { return dismissTip; },
enableTips: function() { return enableTips; },
triggerGuide: function() { return triggerGuide; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/nux/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"areTipsEnabled": function() { return selectors_areTipsEnabled; },
"getAssociatedGuide": function() { return getAssociatedGuide; },
"isTipVisible": function() { return isTipVisible; }
areTipsEnabled: function() { return selectors_areTipsEnabled; },
getAssociatedGuide: function() { return getAssociatedGuide; },
isTipVisible: function() { return isTipVisible; }
});
;// CONCATENATED MODULE: external ["wp","deprecated"]
@@ -84,6 +84,7 @@ var external_wp_data_namespaceObject = window["wp"]["data"];
* WordPress dependencies
*/
/**
* Reducer that tracks which tips are in a guide. Each guide is represented by
* an array which contains the tip identifiers contained within that guide.
@@ -93,15 +94,14 @@ var external_wp_data_namespaceObject = window["wp"]["data"];
*
* @return {Array} Updated state.
*/
function guides(state = [], action) {
switch (action.type) {
case 'TRIGGER_GUIDE':
return [...state, action.tipIds];
}
return state;
}
/**
* Reducer that tracks whether or not tips are globally enabled.
*
@@ -110,18 +110,16 @@ function guides(state = [], action) {
*
* @return {boolean} Updated state.
*/
function areTipsEnabled(state = true, action) {
switch (action.type) {
case 'DISABLE_TIPS':
return false;
case 'ENABLE_TIPS':
return true;
}
return state;
}
/**
* Reducer that tracks which tips have been dismissed. If the state object
* contains a tip identifier, then that tip is dismissed.
@@ -131,18 +129,16 @@ function areTipsEnabled(state = true, action) {
*
* @return {Object} Updated state.
*/
function dismissedTips(state = {}, action) {
switch (action.type) {
case 'DISMISS_TIP':
return { ...state,
return {
...state,
[action.id]: true
};
case 'ENABLE_TIPS':
return {};
}
return state;
}
const preferences = (0,external_wp_data_namespaceObject.combineReducers)({
@@ -169,6 +165,7 @@ function triggerGuide(tipIds) {
tipIds
};
}
/**
* Returns an action object that, when dispatched, dismisses the given tip. A
* dismissed tip will not show again.
@@ -177,31 +174,30 @@ function triggerGuide(tipIds) {
*
* @return {Object} Action object.
*/
function dismissTip(id) {
return {
type: 'DISMISS_TIP',
id
};
}
/**
* Returns an action object that, when dispatched, prevents all tips from
* showing again.
*
* @return {Object} Action object.
*/
function disableTips() {
return {
type: 'DISABLE_TIPS'
};
}
/**
* Returns an action object that, when dispatched, makes all tips show again.
*
* @return {Object} Action object.
*/
function enableTips() {
return {
type: 'ENABLE_TIPS'
@@ -511,6 +507,7 @@ function isShallowEqual(a, b, fromIndex) {
* External dependencies
*/
/**
* An object containing information about a guide.
*
@@ -529,7 +526,6 @@ function isShallowEqual(a, b, fromIndex) {
*
* @return {?NUXGuideInfo} Information about the associated guide.
*/
const getAssociatedGuide = rememo((state, tipId) => {
for (const tipIds of state.guides) {
if (tipIds.includes(tipId)) {
@@ -542,9 +538,9 @@ const getAssociatedGuide = rememo((state, tipId) => {
};
}
}
return null;
}, state => [state.guides, state.preferences.dismissedTips]);
/**
* Determines whether or not the given tip is showing. Tips are hidden if they
* are disabled, have been dismissed, or are not the current tip in any
@@ -555,24 +551,20 @@ const getAssociatedGuide = rememo((state, tipId) => {
*
* @return {boolean} Whether or not the given tip is showing.
*/
function isTipVisible(state, tipId) {
if (!state.preferences.areTipsEnabled) {
return false;
}
if (state.preferences.dismissedTips?.hasOwnProperty(tipId)) {
return false;
}
const associatedGuide = getAssociatedGuide(state, tipId);
if (associatedGuide && associatedGuide.currentTipId !== tipId) {
return false;
}
return true;
}
/**
* Returns whether or not tips are globally enabled.
*
@@ -580,7 +572,6 @@ function isTipVisible(state, tipId) {
*
* @return {boolean} Whether tips are globally enabled.
*/
function selectors_areTipsEnabled(state) {
return state.preferences.areTipsEnabled;
}
@@ -590,14 +581,15 @@ function selectors_areTipsEnabled(state) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const STORE_NAME = 'core/nux';
/**
* Store definition for the nux namespace.
*
@@ -605,15 +597,15 @@ const STORE_NAME = 'core/nux';
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, {
reducer: reducer,
actions: actions_namespaceObject,
selectors: selectors_namespaceObject,
persist: ['preferences']
}); // Once we build a more generic persistence plugin that works across types of stores
// we'd be able to replace this with a register call.
});
// Once we build a more generic persistence plugin that works across types of stores
// we'd be able to replace this with a register call.
(0,external_wp_data_namespaceObject.registerStore)(STORE_NAME, {
reducer: reducer,
actions: actions_namespaceObject,
@@ -633,7 +625,6 @@ var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close.js
/**
* WordPress dependencies
*/
@@ -648,7 +639,6 @@ const close_close = (0,external_wp_element_namespaceObject.createElement)(extern
;// CONCATENATED MODULE: ./node_modules/@wordpress/nux/build-module/components/dot-tip/index.js
/**
* WordPress dependencies
*/
@@ -658,18 +648,16 @@ const close_close = (0,external_wp_element_namespaceObject.createElement)(extern
/**
* Internal dependencies
*/
function onClick(event) {
// Tips are often nested within buttons. We stop propagation so that clicking
// on a tip doesn't result in the button being clicked.
event.stopPropagation();
}
function DotTip({
position = 'middle right',
children,
@@ -683,18 +671,14 @@ function DotTip({
if (!anchorParent.current) {
return;
}
if (anchorParent.current.contains(event.relatedTarget)) {
return;
}
onDisable();
}, [onDisable, anchorParent]);
if (!isVisible) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
className: "nux-dot-tip",
position: position,
@@ -736,11 +720,9 @@ function DotTip({
onDismiss() {
dismissTip(tipId);
},
onDisable() {
disableTips();
}
};
}))(DotTip));
+762
View File
@@ -0,0 +1,762 @@
/******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
privateApis: function() { return /* reexport */ privateApis; },
store: function() { return /* reexport */ store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/patterns/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
convertSyncedPatternToStatic: function() { return convertSyncedPatternToStatic; },
createPattern: function() { return createPattern; },
createPatternFromFile: function() { return createPatternFromFile; },
setEditingPattern: function() { return setEditingPattern; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/patterns/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
isEditingPattern: function() { return selectors_isEditingPattern; }
});
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/store/reducer.js
/**
* WordPress dependencies
*/
function isEditingPattern(state = {}, action) {
if (action?.type === 'SET_EDITING_PATTERN') {
return {
...state,
[action.clientId]: action.isEditing
};
}
return state;
}
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
isEditingPattern
}));
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: external ["wp","coreData"]
var external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: external ["wp","blockEditor"]
var external_wp_blockEditor_namespaceObject = window["wp"]["blockEditor"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/constants.js
const PATTERN_TYPES = {
theme: 'pattern',
user: 'wp_block'
};
const PATTERN_DEFAULT_CATEGORY = 'all-patterns';
const PATTERN_USER_CATEGORY = 'my-patterns';
const PATTERN_CORE_SOURCES = ['core', 'pattern-directory/core', 'pattern-directory/featured', 'pattern-directory/theme'];
const PATTERN_SYNC_TYPES = {
full: 'fully',
unsynced: 'unsynced'
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns a generator converting one or more static blocks into a pattern, or creating a new empty pattern.
*
* @param {string} title Pattern title.
* @param {'full'|'unsynced'} syncType They way block is synced, 'full' or 'unsynced'.
* @param {string|undefined} [content] Optional serialized content of blocks to convert to pattern.
* @param {number[]|undefined} [categories] Ids of any selected categories.
*/
const createPattern = (title, syncType, content, categories) => async ({
registry
}) => {
const meta = syncType === PATTERN_SYNC_TYPES.unsynced ? {
wp_pattern_sync_status: syncType
} : undefined;
const reusableBlock = {
title,
content,
status: 'publish',
meta,
wp_pattern_category: categories
};
const updatedRecord = await registry.dispatch(external_wp_coreData_namespaceObject.store).saveEntityRecord('postType', 'wp_block', reusableBlock);
return updatedRecord;
};
/**
* Create a pattern from a JSON file.
* @param {File} file The JSON file instance of the pattern.
* @param {number[]|undefined} [categories] Ids of any selected categories.
*/
const createPatternFromFile = (file, categories) => async ({
dispatch
}) => {
const fileContent = await file.text();
/** @type {import('./types').PatternJSON} */
let parsedContent;
try {
parsedContent = JSON.parse(fileContent);
} catch (e) {
throw new Error('Invalid JSON file');
}
if (parsedContent.__file !== 'wp_block' || !parsedContent.title || !parsedContent.content || typeof parsedContent.title !== 'string' || typeof parsedContent.content !== 'string' || parsedContent.syncStatus && typeof parsedContent.syncStatus !== 'string') {
throw new Error('Invalid pattern JSON file');
}
const pattern = await dispatch.createPattern(parsedContent.title, parsedContent.syncStatus, parsedContent.content, categories);
return pattern;
};
/**
* Returns a generator converting a synced pattern block into a static block.
*
* @param {string} clientId The client ID of the block to attach.
*/
const convertSyncedPatternToStatic = clientId => ({
registry
}) => {
const oldBlock = registry.select(external_wp_blockEditor_namespaceObject.store).getBlock(clientId);
const pattern = registry.select('core').getEditedEntityRecord('postType', 'wp_block', oldBlock.attributes.ref);
const newBlocks = (0,external_wp_blocks_namespaceObject.parse)(typeof pattern.content === 'function' ? pattern.content(pattern) : pattern.content);
registry.dispatch(external_wp_blockEditor_namespaceObject.store).replaceBlocks(oldBlock.clientId, newBlocks);
};
/**
* Returns an action descriptor for SET_EDITING_PATTERN action.
*
* @param {string} clientId The clientID of the pattern to target.
* @param {boolean} isEditing Whether the block should be in editing state.
* @return {Object} Action descriptor.
*/
function setEditingPattern(clientId, isEditing) {
return {
type: 'SET_EDITING_PATTERN',
clientId,
isEditing
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/store/constants.js
/**
* Module Constants
*/
const STORE_NAME = 'core/patterns';
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/store/selectors.js
/**
* Returns true if pattern is in the editing state.
*
* @param {Object} state Global application state.
* @param {number} clientId the clientID of the block.
* @return {boolean} Whether the pattern is in the editing state.
*/
function selectors_isEditingPattern(state, clientId) {
return state.isEditingPattern[clientId];
}
;// CONCATENATED MODULE: external ["wp","privateApis"]
var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/lock-unlock.js
/**
* WordPress dependencies
*/
const {
lock,
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.', '@wordpress/patterns');
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Post editor data store configuration.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#registerStore
*
* @type {Object}
*/
const storeConfig = {
reducer: reducer
};
/**
* Store definition for the editor namespace.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, {
...storeConfig
});
(0,external_wp_data_namespaceObject.register)(store);
unlock(store).registerPrivateActions(actions_namespaceObject);
unlock(store).registerPrivateSelectors(selectors_namespaceObject);
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: external ["wp","notices"]
var external_wp_notices_namespaceObject = window["wp"]["notices"];
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/components/category-selector.js
/**
* WordPress dependencies
*/
const unescapeString = arg => {
return (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(arg);
};
const CATEGORY_SLUG = 'wp_pattern_category';
function CategorySelector({
categoryTerms,
onChange,
categoryMap
}) {
const [search, setSearch] = (0,external_wp_element_namespaceObject.useState)('');
const debouncedSearch = (0,external_wp_compose_namespaceObject.useDebounce)(setSearch, 500);
const suggestions = (0,external_wp_element_namespaceObject.useMemo)(() => {
return Array.from(categoryMap.values()).map(category => unescapeString(category.label)).filter(category => {
if (search !== '') {
return category.toLowerCase().includes(search.toLowerCase());
}
return true;
}).sort((a, b) => a.localeCompare(b));
}, [search, categoryMap]);
function handleChange(termNames) {
const uniqueTerms = termNames.reduce((terms, newTerm) => {
if (!terms.some(term => term.toLowerCase() === newTerm.toLowerCase())) {
terms.push(newTerm);
}
return terms;
}, []);
onChange(uniqueTerms);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FormTokenField, {
className: "patterns-menu-items__convert-modal-categories",
value: categoryTerms,
suggestions: suggestions,
onChange: handleChange,
onInputChange: debouncedSearch,
label: (0,external_wp_i18n_namespaceObject.__)('Categories'),
tokenizeOnBlur: true,
__experimentalExpandOnFocus: true,
__next40pxDefaultSize: true
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/components/create-pattern-modal.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Internal dependencies
*/
function CreatePatternModal({
onSuccess,
onError,
content,
onClose,
className = 'patterns-menu-items__convert-modal'
}) {
const [syncType, setSyncType] = (0,external_wp_element_namespaceObject.useState)(PATTERN_SYNC_TYPES.full);
const [categoryTerms, setCategoryTerms] = (0,external_wp_element_namespaceObject.useState)([]);
const [title, setTitle] = (0,external_wp_element_namespaceObject.useState)('');
const [isSaving, setIsSaving] = (0,external_wp_element_namespaceObject.useState)(false);
const {
createPattern
} = unlock((0,external_wp_data_namespaceObject.useDispatch)(store));
const {
saveEntityRecord,
invalidateResolution
} = (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 {
corePatternCategories,
userPatternCategories
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getUserPatternCategories,
getBlockPatternCategories
} = select(external_wp_coreData_namespaceObject.store);
return {
corePatternCategories: getBlockPatternCategories(),
userPatternCategories: getUserPatternCategories()
};
});
const categoryMap = (0,external_wp_element_namespaceObject.useMemo)(() => {
// Merge the user and core pattern categories and remove any duplicates.
const uniqueCategories = new Map();
[...userPatternCategories, ...corePatternCategories].forEach(category => {
if (!uniqueCategories.has(category.label) &&
// There are two core categories with `Post` label so explicitly remove the one with
// the `query` slug to avoid any confusion.
category.name !== 'query') {
// We need to store the name separately as this is used as the slug in the
// taxonomy and may vary from the label.
uniqueCategories.set(category.label, {
label: category.label,
value: category.label,
name: category.name
});
}
});
return uniqueCategories;
}, [userPatternCategories, corePatternCategories]);
async function onCreate(patternTitle, sync) {
if (!title || isSaving) {
return;
}
try {
setIsSaving(true);
const categories = await Promise.all(categoryTerms.map(termName => findOrCreateTerm(termName)));
const newPattern = await createPattern(patternTitle, sync, typeof content === 'function' ? content() : content, categories);
onSuccess({
pattern: newPattern,
categoryId: PATTERN_DEFAULT_CATEGORY
});
} catch (error) {
createErrorNotice(error.message, {
type: 'snackbar',
id: 'convert-to-pattern-error'
});
onError();
} finally {
setIsSaving(false);
setCategoryTerms([]);
setTitle('');
}
}
/**
* @param {string} term
* @return {Promise<number>} The pattern category id.
*/
async function findOrCreateTerm(term) {
try {
// We need to match any existing term to the correct slug to prevent duplicates, eg.
// the core `Headers` category uses the singular `header` as the slug.
const existingTerm = categoryMap.get(term);
const termData = existingTerm ? {
name: existingTerm.label,
slug: existingTerm.name
} : {
name: term
};
const newTerm = await saveEntityRecord('taxonomy', CATEGORY_SLUG, termData, {
throwOnError: true
});
invalidateResolution('getUserPatternCategories');
return newTerm.id;
} catch (error) {
if (error.code !== 'term_exists') {
throw error;
}
return error.data.term_id;
}
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
title: (0,external_wp_i18n_namespaceObject.__)('Create pattern'),
onRequestClose: () => {
onClose();
setTitle('');
},
overlayClassName: className
}, (0,external_wp_element_namespaceObject.createElement)("form", {
onSubmit: event => {
event.preventDefault();
onCreate(title, syncType);
}
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: "5"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Name'),
value: title,
onChange: setTitle,
placeholder: (0,external_wp_i18n_namespaceObject.__)('My pattern'),
className: "patterns-create-modal__name-input"
}), (0,external_wp_element_namespaceObject.createElement)(CategorySelector, {
categoryTerms: categoryTerms,
onChange: setCategoryTerms,
categoryMap: categoryMap
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Synced'),
help: (0,external_wp_i18n_namespaceObject.__)('Editing the pattern will update it anywhere it is used.'),
checked: syncType === PATTERN_SYNC_TYPES.full,
onChange: () => {
setSyncType(syncType === PATTERN_SYNC_TYPES.full ? PATTERN_SYNC_TYPES.unsynced : PATTERN_SYNC_TYPES.full);
}
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
justify: "right"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "tertiary",
onClick: () => {
onClose();
setTitle('');
}
}, (0,external_wp_i18n_namespaceObject.__)('Cancel')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
type: "submit",
"aria-disabled": !title || isSaving,
isBusy: isSaving
}, (0,external_wp_i18n_namespaceObject.__)('Create'))))));
}
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/symbol.js
/**
* WordPress dependencies
*/
const symbol = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M21.3 10.8l-5.6-5.6c-.7-.7-1.8-.7-2.5 0l-5.6 5.6c-.7.7-.7 1.8 0 2.5l5.6 5.6c.3.3.8.5 1.2.5s.9-.2 1.2-.5l5.6-5.6c.8-.7.8-1.9.1-2.5zm-1 1.4l-5.6 5.6c-.1.1-.3.1-.4 0l-5.6-5.6c-.1-.1-.1-.3 0-.4l5.6-5.6s.1-.1.2-.1.1 0 .2.1l5.6 5.6c.1.1.1.3 0 .4zm-16.6-.4L10 5.5l-1-1-6.3 6.3c-.7.7-.7 1.8 0 2.5L9 19.5l1.1-1.1-6.3-6.3c-.2 0-.2-.2-.1-.3z"
}));
/* harmony default export */ var library_symbol = (symbol);
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/components/pattern-convert-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Menu control to convert block(s) to a pattern block.
*
* @param {Object} props Component props.
* @param {string[]} props.clientIds Client ids of selected blocks.
* @param {string} props.rootClientId ID of the currently selected top-level block.
* @return {import('@wordpress/element').WPComponent} The menu control or null.
*/
function PatternConvertButton({
clientIds,
rootClientId
}) {
const {
createSuccessNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const {
replaceBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
// Ignore reason: false positive of the lint rule.
// eslint-disable-next-line @wordpress/no-unused-vars-before-return
const {
setEditingPattern
} = unlock((0,external_wp_data_namespaceObject.useDispatch)(store));
const [isModalOpen, setIsModalOpen] = (0,external_wp_element_namespaceObject.useState)(false);
const canConvert = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlocksByClientId;
const {
canUser
} = select(external_wp_coreData_namespaceObject.store);
const {
getBlocksByClientId,
canInsertBlockType,
getBlockRootClientId
} = select(external_wp_blockEditor_namespaceObject.store);
const rootId = rootClientId || (clientIds.length > 0 ? getBlockRootClientId(clientIds[0]) : undefined);
const blocks = (_getBlocksByClientId = getBlocksByClientId(clientIds)) !== null && _getBlocksByClientId !== void 0 ? _getBlocksByClientId : [];
const isReusable = blocks.length === 1 && blocks[0] && (0,external_wp_blocks_namespaceObject.isReusableBlock)(blocks[0]) && !!select(external_wp_coreData_namespaceObject.store).getEntityRecord('postType', 'wp_block', blocks[0].attributes.ref);
const _canConvert =
// Hide when this is already a synced pattern.
!isReusable &&
// Hide when patterns are disabled.
canInsertBlockType('core/block', rootId) && blocks.every(block =>
// Guard against the case where a regular block has *just* been converted.
!!block &&
// Hide on invalid blocks.
block.isValid &&
// 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');
return _canConvert;
}, [clientIds, rootClientId]);
const {
getBlocksByClientId
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blockEditor_namespaceObject.store);
const getContent = (0,external_wp_element_namespaceObject.useCallback)(() => (0,external_wp_blocks_namespaceObject.serialize)(getBlocksByClientId(clientIds)), [getBlocksByClientId, clientIds]);
if (!canConvert) {
return null;
}
const handleSuccess = ({
pattern
}) => {
if (pattern.wp_pattern_sync_status !== PATTERN_SYNC_TYPES.unsynced) {
const newBlock = (0,external_wp_blocks_namespaceObject.createBlock)('core/block', {
ref: pattern.id
});
replaceBlocks(clientIds, newBlock);
setEditingPattern(newBlock.clientId, true);
}
createSuccessNotice(pattern.wp_pattern_sync_status === PATTERN_SYNC_TYPES.unsynced ? (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: the name the user has given to the pattern.
(0,external_wp_i18n_namespaceObject.__)('Unsynced pattern created: %s'), pattern.title.raw) : (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: the name the user has given to the pattern.
(0,external_wp_i18n_namespaceObject.__)('Synced pattern created: %s'), pattern.title.raw), {
type: 'snackbar',
id: 'convert-to-pattern-success'
});
setIsModalOpen(false);
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
icon: library_symbol,
onClick: () => setIsModalOpen(true),
"aria-expanded": isModalOpen,
"aria-haspopup": "dialog"
}, (0,external_wp_i18n_namespaceObject.__)('Create pattern')), isModalOpen && (0,external_wp_element_namespaceObject.createElement)(CreatePatternModal, {
content: getContent,
onSuccess: pattern => {
handleSuccess(pattern);
},
onError: () => {
setIsModalOpen(false);
},
onClose: () => {
setIsModalOpen(false);
}
}));
}
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/components/patterns-manage-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PatternsManageButton({
clientId
}) {
const {
canRemove,
isVisible,
innerBlockCount,
managePatternsUrl
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlock,
canRemoveBlock,
getBlockCount,
getSettings
} = select(external_wp_blockEditor_namespaceObject.store);
const {
canUser
} = select(external_wp_coreData_namespaceObject.store);
const reusableBlock = getBlock(clientId);
const isBlockTheme = getSettings().__unstableIsBlockBasedTheme;
return {
canRemove: canRemoveBlock(clientId),
isVisible: !!reusableBlock && (0,external_wp_blocks_namespaceObject.isReusableBlock)(reusableBlock) && !!canUser('update', 'blocks', 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: isBlockTheme && canUser('read', 'templates') ? (0,external_wp_url_namespaceObject.addQueryArgs)('site-editor.php', {
path: '/patterns'
}) : (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
post_type: 'wp_block'
})
};
}, [clientId]);
// Ignore reason: false positive of the lint rule.
// eslint-disable-next-line @wordpress/no-unused-vars-before-return
const {
convertSyncedPatternToStatic
} = unlock((0,external_wp_data_namespaceObject.useDispatch)(store));
if (!isVisible) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
href: managePatternsUrl
}, (0,external_wp_i18n_namespaceObject.__)('Manage patterns')), canRemove && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => convertSyncedPatternToStatic(clientId)
}, innerBlockCount > 1 ? (0,external_wp_i18n_namespaceObject.__)('Detach patterns') : (0,external_wp_i18n_namespaceObject.__)('Detach pattern')));
}
/* harmony default export */ var patterns_manage_button = (PatternsManageButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/components/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PatternsMenuItems({
rootClientId
}) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockSettingsMenuControls, null, ({
selectedClientIds
}) => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(PatternConvertButton, {
clientIds: selectedClientIds,
rootClientId: rootClientId
}), selectedClientIds.length === 1 && (0,external_wp_element_namespaceObject.createElement)(patterns_manage_button, {
clientId: selectedClientIds[0]
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/private-apis.js
/**
* Internal dependencies
*/
const privateApis = {};
lock(privateApis, {
CreatePatternModal: CreatePatternModal,
PatternsMenuItems: PatternsMenuItems,
PATTERN_TYPES: PATTERN_TYPES,
PATTERN_DEFAULT_CATEGORY: PATTERN_DEFAULT_CATEGORY,
PATTERN_USER_CATEGORY: PATTERN_USER_CATEGORY,
PATTERN_CORE_SOURCES: PATTERN_CORE_SOURCES,
PATTERN_SYNC_TYPES: PATTERN_SYNC_TYPES
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/patterns/build-module/index.js
/**
* Internal dependencies
*/
(window.wp = window.wp || {}).patterns = __webpack_exports__;
/******/ })()
;
File diff suppressed because one or more lines are too long
+29 -44
View File
@@ -51,12 +51,13 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"PluginArea": function() { return /* reexport */ plugin_area; },
"getPlugin": function() { return /* reexport */ getPlugin; },
"getPlugins": function() { return /* reexport */ getPlugins; },
"registerPlugin": function() { return /* reexport */ registerPlugin; },
"unregisterPlugin": function() { return /* reexport */ unregisterPlugin; },
"withPluginContext": function() { return /* reexport */ withPluginContext; }
PluginArea: function() { return /* reexport */ plugin_area; },
getPlugin: function() { return /* reexport */ getPlugin; },
getPlugins: function() { return /* reexport */ getPlugins; },
registerPlugin: function() { return /* reexport */ registerPlugin; },
unregisterPlugin: function() { return /* reexport */ unregisterPlugin; },
usePluginContext: function() { return /* reexport */ usePluginContext; },
withPluginContext: function() { return /* reexport */ withPluginContext; }
});
;// CONCATENATED MODULE: external ["wp","element"]
@@ -232,23 +233,30 @@ var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(exte
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/plugins/build-module/components/plugin-context/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
Consumer,
Provider
} = (0,external_wp_element_namespaceObject.createContext)({
const Context = (0,external_wp_element_namespaceObject.createContext)({
name: null,
icon: null
});
const PluginContextProvider = Context.Provider;
/**
* A hook that returns the plugin context.
*
* @return {PluginContext} Plugin context
*/
function usePluginContext() {
return (0,external_wp_element_namespaceObject.useContext)(Context);
}
/**
* A Higher Order Component used to inject Plugin context to the
@@ -260,9 +268,9 @@ const {
*
* @return {WPComponent} Enhanced component with injected context as props.
*/
const withPluginContext = mapContextToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(OriginalComponent => {
return props => (0,external_wp_element_namespaceObject.createElement)(Consumer, null, context => (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, { ...props,
return props => (0,external_wp_element_namespaceObject.createElement)(Context.Consumer, null, context => (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, {
...props,
...mapContextToProps(context, props)
}));
}, 'withPluginContext');
@@ -282,43 +290,36 @@ class PluginErrorBoundary extends external_wp_element_namespaceObject.Component
hasError: false
};
}
static getDerivedStateFromError() {
return {
hasError: true
};
}
/**
* @param {Error} error Error object passed by React.
*/
componentDidCatch(error) {
const {
name,
onError
} = this.props;
if (onError) {
onError(name, error);
}
}
render() {
if (!this.state.hasError) {
return this.props.children;
}
return null;
}
}
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plugins.js
/**
* WordPress dependencies
*/
@@ -339,11 +340,11 @@ const plugins = (0,external_wp_element_namespaceObject.createElement)(external_w
*/
/**
* Plugin definitions keyed by plugin name.
*/
const api_plugins = {};
/**
* Registers a plugin to the editor.
*
@@ -421,50 +422,41 @@ const api_plugins = {};
*
* @return The final plugin settings object.
*/
function registerPlugin(name, settings) {
if (typeof settings !== 'object') {
console.error('No settings object provided!');
return null;
}
if (typeof name !== 'string') {
console.error('Plugin name must be string.');
return null;
}
if (!/^[a-z][a-z0-9-]*$/.test(name)) {
console.error('Plugin name must include only lowercase alphanumeric characters or dashes, and start with a letter. Example: "my-plugin".');
return null;
}
if (api_plugins[name]) {
console.error(`Plugin "${name}" is already registered.`);
}
settings = (0,external_wp_hooks_namespaceObject.applyFilters)('plugins.registerPlugin', settings, name);
const {
render,
scope
} = settings;
if (typeof render !== 'function') {
console.error('The "render" property must be specified and must be a valid function.');
return null;
}
if (scope) {
if (typeof scope !== 'string') {
console.error('Plugin scope must be string.');
return null;
}
if (!/^[a-z][a-z0-9-]*$/.test(scope)) {
console.error('Plugin scope must include only lowercase alphanumeric characters or dashes, and start with a letter. Example: "my-page".');
return null;
}
}
api_plugins[name] = {
name,
icon: library_plugins,
@@ -473,6 +465,7 @@ function registerPlugin(name, settings) {
(0,external_wp_hooks_namespaceObject.doAction)('plugins.pluginRegistered', settings, name);
return settings;
}
/**
* Unregisters a plugin by name.
*
@@ -497,18 +490,17 @@ function registerPlugin(name, settings) {
* @return The previous plugin settings object, if it has been
* successfully unregistered; otherwise `undefined`.
*/
function unregisterPlugin(name) {
if (!api_plugins[name]) {
console.error('Plugin "' + name + '" is not registered.');
return;
}
const oldPlugin = api_plugins[name];
delete api_plugins[name];
(0,external_wp_hooks_namespaceObject.doAction)('plugins.pluginUnregistered', oldPlugin, name);
return oldPlugin;
}
/**
* Returns a registered plugin settings.
*
@@ -516,10 +508,10 @@ function unregisterPlugin(name) {
*
* @return Plugin setting.
*/
function getPlugin(name) {
return api_plugins[name];
}
/**
* Returns all registered plugins without a scope or for a given scope.
*
@@ -528,18 +520,17 @@ function getPlugin(name) {
*
* @return The list of plugins without a scope or for a given scope.
*/
function getPlugins(scope) {
return Object.values(api_plugins).filter(plugin => plugin.scope === scope);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/plugins/build-module/components/plugin-area/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
@@ -553,11 +544,11 @@ function getPlugins(scope) {
const getPluginContext = memize((icon, name) => ({
icon,
name
}));
/**
* A component that renders all plugin fills in a hidden div.
*
@@ -595,7 +586,6 @@ const getPluginContext = memize((icon, name) => ({
*
* @return {WPComponent} The component to be rendered.
*/
function PluginArea({
scope,
onError
@@ -611,17 +601,13 @@ function PluginArea({
(0,external_wp_hooks_namespaceObject.removeAction)('plugins.pluginUnregistered', 'core/plugins/plugin-area/plugins-unregistered');
};
},
getValue() {
const nextValue = getPlugins(scope);
if (!external_wp_isShallowEqual_default()(lastValue, nextValue)) {
lastValue = nextValue;
}
return lastValue;
}
};
}, [scope]);
const plugins = (0,external_wp_element_namespaceObject.useSyncExternalStore)(store.subscribe, store.getValue);
@@ -633,7 +619,7 @@ function PluginArea({
icon,
name,
render: Plugin
}) => (0,external_wp_element_namespaceObject.createElement)(Provider, {
}) => (0,external_wp_element_namespaceObject.createElement)(PluginContextProvider, {
key: name,
value: getPluginContext(icon, name)
}, (0,external_wp_element_namespaceObject.createElement)(PluginErrorBoundary, {
@@ -641,7 +627,6 @@ function PluginArea({
onError: onError
}, (0,external_wp_element_namespaceObject.createElement)(Plugin, null)))));
}
/* harmony default export */ var plugin_area = (PluginArea);
;// CONCATENATED MODULE: ./node_modules/@wordpress/plugins/build-module/components/index.js
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
!function(){"use strict";var e={n:function(n){var r=n&&n.__esModule?function(){return n.default}:function(){return n};return e.d(r,{a:r}),r},d:function(n,r){for(var t in r)e.o(r,t)&&!e.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:r[t]})},o:function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},n={};e.r(n),e.d(n,{PluginArea:function(){return y},getPlugin:function(){return v},getPlugins:function(){return w},registerPlugin:function(){return f},unregisterPlugin:function(){return m},withPluginContext:function(){return a}});var r=window.wp.element;var t=window.wp.hooks,o=window.wp.isShallowEqual,i=e.n(o),l=window.wp.compose;const{Consumer:u,Provider:s}=(0,r.createContext)({name:null,icon:null}),a=e=>(0,l.createHigherOrderComponent)((n=>t=>(0,r.createElement)(u,null,(o=>(0,r.createElement)(n,{...t,...e(o,t)})))),"withPluginContext");class c extends r.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){const{name:n,onError:r}=this.props;r&&r(n,e)}render(){return this.state.hasError?null:this.props.children}}var p=window.wp.primitives;var g=(0,r.createElement)(p.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(p.Path,{d:"M10.5 4v4h3V4H15v4h1.5a1 1 0 011 1v4l-3 4v2a1 1 0 01-1 1h-3a1 1 0 01-1-1v-2l-3-4V9a1 1 0 011-1H9V4h1.5zm.5 12.5v2h2v-2l3-4v-3H8v3l3 4z"}));const d={};function f(e,n){if("object"!=typeof n)return console.error("No settings object provided!"),null;if("string"!=typeof e)return console.error("Plugin name must be string."),null;if(!/^[a-z][a-z0-9-]*$/.test(e))return console.error('Plugin name must include only lowercase alphanumeric characters or dashes, and start with a letter. Example: "my-plugin".'),null;d[e]&&console.error(`Plugin "${e}" is already registered.`),n=(0,t.applyFilters)("plugins.registerPlugin",n,e);const{render:r,scope:o}=n;if("function"!=typeof r)return console.error('The "render" property must be specified and must be a valid function.'),null;if(o){if("string"!=typeof o)return console.error("Plugin scope must be string."),null;if(!/^[a-z][a-z0-9-]*$/.test(o))return console.error('Plugin scope must include only lowercase alphanumeric characters or dashes, and start with a letter. Example: "my-page".'),null}return d[e]={name:e,icon:g,...n},(0,t.doAction)("plugins.pluginRegistered",n,e),n}function m(e){if(!d[e])return void console.error('Plugin "'+e+'" is not registered.');const n=d[e];return delete d[e],(0,t.doAction)("plugins.pluginUnregistered",n,e),n}function v(e){return d[e]}function w(e){return Object.values(d).filter((n=>n.scope===e))}const h=function(e,n){var r,t,o=0;function i(){var i,l,u=r,s=arguments.length;e:for(;u;){if(u.args.length===arguments.length){for(l=0;l<s;l++)if(u.args[l]!==arguments[l]){u=u.next;continue e}return u!==r&&(u===t&&(t=u.prev),u.prev.next=u.next,u.next&&(u.next.prev=u.prev),u.next=r,u.prev=null,r.prev=u,r=u),u.val}u=u.next}for(i=new Array(s),l=0;l<s;l++)i[l]=arguments[l];return u={args:i,val:e.apply(null,i)},r?(r.prev=u,u.next=r):t=u,o===n.maxSize?(t=t.prev).next=null:o++,r=u,u.val}return n=n||{},i.clear=function(){r=null,t=null,o=0},i}(((e,n)=>({icon:e,name:n})));var y=function({scope:e,onError:n}){const o=(0,r.useMemo)((()=>{let n=[];return{subscribe(e){return(0,t.addAction)("plugins.pluginRegistered","core/plugins/plugin-area/plugins-registered",e),(0,t.addAction)("plugins.pluginUnregistered","core/plugins/plugin-area/plugins-unregistered",e),()=>{(0,t.removeAction)("plugins.pluginRegistered","core/plugins/plugin-area/plugins-registered"),(0,t.removeAction)("plugins.pluginUnregistered","core/plugins/plugin-area/plugins-unregistered")}},getValue(){const r=w(e);return i()(n,r)||(n=r),n}}}),[e]),l=(0,r.useSyncExternalStore)(o.subscribe,o.getValue);return(0,r.createElement)("div",{style:{display:"none"}},l.map((({icon:e,name:t,render:o})=>(0,r.createElement)(s,{key:t,value:h(e,t)},(0,r.createElement)(c,{name:t,onError:n},(0,r.createElement)(o,null))))))};(window.wp=window.wp||{}).plugins=n}();
!function(){"use strict";var e={n:function(n){var r=n&&n.__esModule?function(){return n.default}:function(){return n};return e.d(r,{a:r}),r},d:function(n,r){for(var t in r)e.o(r,t)&&!e.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:r[t]})},o:function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},n={};e.r(n),e.d(n,{PluginArea:function(){return x},getPlugin:function(){return w},getPlugins:function(){return h},registerPlugin:function(){return m},unregisterPlugin:function(){return v},usePluginContext:function(){return a},withPluginContext:function(){return c}});var r=window.wp.element;var t=window.wp.hooks,o=window.wp.isShallowEqual,i=e.n(o),u=window.wp.compose;const l=(0,r.createContext)({name:null,icon:null}),s=l.Provider;function a(){return(0,r.useContext)(l)}const c=e=>(0,u.createHigherOrderComponent)((n=>t=>(0,r.createElement)(l.Consumer,null,(o=>(0,r.createElement)(n,{...t,...e(o,t)})))),"withPluginContext");class p extends r.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){const{name:n,onError:r}=this.props;r&&r(n,e)}render(){return this.state.hasError?null:this.props.children}}var g=window.wp.primitives;var d=(0,r.createElement)(g.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(g.Path,{d:"M10.5 4v4h3V4H15v4h1.5a1 1 0 011 1v4l-3 4v2a1 1 0 01-1 1h-3a1 1 0 01-1-1v-2l-3-4V9a1 1 0 011-1H9V4h1.5zm.5 12.5v2h2v-2l3-4v-3H8v3l3 4z"}));const f={};function m(e,n){if("object"!=typeof n)return console.error("No settings object provided!"),null;if("string"!=typeof e)return console.error("Plugin name must be string."),null;if(!/^[a-z][a-z0-9-]*$/.test(e))return console.error('Plugin name must include only lowercase alphanumeric characters or dashes, and start with a letter. Example: "my-plugin".'),null;f[e]&&console.error(`Plugin "${e}" is already registered.`),n=(0,t.applyFilters)("plugins.registerPlugin",n,e);const{render:r,scope:o}=n;if("function"!=typeof r)return console.error('The "render" property must be specified and must be a valid function.'),null;if(o){if("string"!=typeof o)return console.error("Plugin scope must be string."),null;if(!/^[a-z][a-z0-9-]*$/.test(o))return console.error('Plugin scope must include only lowercase alphanumeric characters or dashes, and start with a letter. Example: "my-page".'),null}return f[e]={name:e,icon:d,...n},(0,t.doAction)("plugins.pluginRegistered",n,e),n}function v(e){if(!f[e])return void console.error('Plugin "'+e+'" is not registered.');const n=f[e];return delete f[e],(0,t.doAction)("plugins.pluginUnregistered",n,e),n}function w(e){return f[e]}function h(e){return Object.values(f).filter((n=>n.scope===e))}const y=function(e,n){var r,t,o=0;function i(){var i,u,l=r,s=arguments.length;e:for(;l;){if(l.args.length===arguments.length){for(u=0;u<s;u++)if(l.args[u]!==arguments[u]){l=l.next;continue e}return l!==r&&(l===t&&(t=l.prev),l.prev.next=l.next,l.next&&(l.next.prev=l.prev),l.next=r,l.prev=null,r.prev=l,r=l),l.val}l=l.next}for(i=new Array(s),u=0;u<s;u++)i[u]=arguments[u];return l={args:i,val:e.apply(null,i)},r?(r.prev=l,l.next=r):t=l,o===n.maxSize?(t=t.prev).next=null:o++,r=l,l.val}return n=n||{},i.clear=function(){r=null,t=null,o=0},i}(((e,n)=>({icon:e,name:n})));var x=function({scope:e,onError:n}){const o=(0,r.useMemo)((()=>{let n=[];return{subscribe(e){return(0,t.addAction)("plugins.pluginRegistered","core/plugins/plugin-area/plugins-registered",e),(0,t.addAction)("plugins.pluginUnregistered","core/plugins/plugin-area/plugins-unregistered",e),()=>{(0,t.removeAction)("plugins.pluginRegistered","core/plugins/plugin-area/plugins-registered"),(0,t.removeAction)("plugins.pluginUnregistered","core/plugins/plugin-area/plugins-unregistered")}},getValue(){const r=h(e);return i()(n,r)||(n=r),n}}}),[e]),u=(0,r.useSyncExternalStore)(o.subscribe,o.getValue);return(0,r.createElement)("div",{style:{display:"none"}},u.map((({icon:e,name:t,render:o})=>(0,r.createElement)(s,{key:t,value:y(e,t)},(0,r.createElement)(p,{name:t,onError:n},(0,r.createElement)(o,null))))))};(window.wp=window.wp||{}).plugins=n}();
+115 -107
View File
@@ -51,8 +51,8 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"__unstableCreatePersistenceLayer": function() { return /* binding */ __unstableCreatePersistenceLayer; },
"create": function() { return /* reexport */ create; }
__unstableCreatePersistenceLayer: function() { return /* binding */ __unstableCreatePersistenceLayer; },
create: function() { return /* reexport */ create; }
});
;// CONCATENATED MODULE: external ["wp","apiFetch"]
@@ -96,20 +96,19 @@ function debounceAsync(func, delayMS) {
});
});
}
if (activePromise) {
// Let any active promises finish before queuing the next request.
await activePromise;
} // Clear any active timeouts, abandoning any requests that have
}
// Clear any active timeouts, abandoning any requests that have
// been queued but not been made.
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
} // Trigger any trailing edge calls to the function.
}
// Trigger any trailing edge calls to the function.
return new Promise((resolve, reject) => {
// Schedule the next request but with a delay.
timeoutId = setTimeout(() => {
@@ -133,13 +132,14 @@ function debounceAsync(func, delayMS) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const EMPTY_OBJECT = {};
const localStorage = window.localStorage;
/**
* Creates a persistence layer that stores data in WordPress user meta via the
* REST API.
@@ -157,7 +157,6 @@ const localStorage = window.localStorage;
*
* @return {Object} A persistence layer for WordPress user meta.
*/
function create({
preloadedData,
localStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',
@@ -165,23 +164,23 @@ function create({
} = {}) {
let cache = preloadedData;
const debouncedApiFetch = debounceAsync((external_wp_apiFetch_default()), requestDebounceMS);
async function get() {
if (cache) {
return cache;
}
const user = await external_wp_apiFetch_default()({
path: '/wp/v2/users/me?context=edit'
});
const serverData = user?.meta?.persisted_preferences;
const localData = JSON.parse(localStorage.getItem(localStorageRestoreKey)); // Date parse returns NaN for invalid input. Coerce anything invalid
const localData = JSON.parse(localStorage.getItem(localStorageRestoreKey));
// Date parse returns NaN for invalid input. Coerce anything invalid
// into a conveniently comparable zero.
const serverTimestamp = Date.parse(serverData?._modified) || 0;
const localTimestamp = Date.parse(localData?._modified) || 0; // Prefer server data if it exists and is more recent.
// Otherwise fallback to localStorage data.
const localTimestamp = Date.parse(localData?._modified) || 0;
// Prefer server data if it exists and is more recent.
// Otherwise fallback to localStorage data.
if (serverData && serverTimestamp >= localTimestamp) {
cache = serverData;
} else if (localData) {
@@ -189,24 +188,25 @@ function create({
} else {
cache = EMPTY_OBJECT;
}
return cache;
}
function set(newData) {
const dataWithTimestamp = { ...newData,
const dataWithTimestamp = {
...newData,
_modified: new Date().toISOString()
};
cache = dataWithTimestamp; // Store data in local storage as a fallback. If for some reason the
cache = dataWithTimestamp;
// Store data in local storage as a fallback. If for some reason the
// api request does not complete or becomes unavailable, this data
// can be used to restore preferences.
localStorage.setItem(localStorageRestoreKey, JSON.stringify(dataWithTimestamp));
localStorage.setItem(localStorageRestoreKey, JSON.stringify(dataWithTimestamp)); // The user meta endpoint seems susceptible to errors when consecutive
// The user meta endpoint seems susceptible to errors when consecutive
// requests are made in quick succession. Ensure there's a gap between
// any consecutive requests.
//
// Catch and do nothing with errors from the REST API.
debouncedApiFetch({
path: '/wp/v2/users/me',
method: 'PUT',
@@ -223,7 +223,6 @@ function create({
}
}).catch(() => {});
}
return {
get,
set
@@ -290,61 +289,63 @@ function create({
*/
function moveFeaturePreferences(state, sourceStoreName) {
const preferencesStoreName = 'core/preferences';
const interfaceStoreName = 'core/interface'; // Features most recently (and briefly) lived in the interface package.
const interfaceStoreName = 'core/interface';
// Features most recently (and briefly) lived in the interface package.
// If data exists there, prioritize using that for the migration. If not
// also check the original package as the user may have updated from an
// older block editor version.
const interfaceFeatures = state?.[interfaceStoreName]?.preferences?.features?.[sourceStoreName];
const sourceFeatures = state?.[sourceStoreName]?.preferences?.features;
const featuresToMigrate = interfaceFeatures ? interfaceFeatures : sourceFeatures;
if (!featuresToMigrate) {
return state;
}
const existingPreferences = state?.[preferencesStoreName]?.preferences;
const existingPreferences = state?.[preferencesStoreName]?.preferences; // Avoid migrating features again if they've previously been migrated.
// Avoid migrating features again if they've previously been migrated.
if (existingPreferences?.[sourceStoreName]) {
return state;
}
let updatedInterfaceState;
if (interfaceFeatures) {
const otherInterfaceState = state?.[interfaceStoreName];
const otherInterfaceScopes = state?.[interfaceStoreName]?.preferences?.features;
updatedInterfaceState = {
[interfaceStoreName]: { ...otherInterfaceState,
[interfaceStoreName]: {
...otherInterfaceState,
preferences: {
features: { ...otherInterfaceScopes,
features: {
...otherInterfaceScopes,
[sourceStoreName]: undefined
}
}
}
};
}
let updatedSourceState;
if (sourceFeatures) {
const otherSourceState = state?.[sourceStoreName];
const sourcePreferences = state?.[sourceStoreName]?.preferences;
updatedSourceState = {
[sourceStoreName]: { ...otherSourceState,
preferences: { ...sourcePreferences,
[sourceStoreName]: {
...otherSourceState,
preferences: {
...sourcePreferences,
features: undefined
}
}
};
} // Set the feature values in the interface store, the features
}
// Set the feature values in the interface store, the features
// object is keyed by 'scope', which matches the store name for
// the source.
return { ...state,
return {
...state,
[preferencesStoreName]: {
preferences: { ...existingPreferences,
preferences: {
...existingPreferences,
[sourceStoreName]: featuresToMigrate
}
},
@@ -400,40 +401,37 @@ function moveThirdPartyFeaturePreferencesToPreferences(state) {
const preferencesStoreName = 'core/preferences';
const interfaceScopes = state?.[interfaceStoreName]?.preferences?.features;
const interfaceScopeKeys = interfaceScopes ? Object.keys(interfaceScopes) : [];
if (!interfaceScopeKeys?.length) {
return state;
}
return interfaceScopeKeys.reduce(function (convertedState, scope) {
if (scope.startsWith('core')) {
return convertedState;
}
const featuresToMigrate = interfaceScopes?.[scope];
if (!featuresToMigrate) {
return convertedState;
}
const existingMigratedData = convertedState?.[preferencesStoreName]?.preferences?.[scope];
if (existingMigratedData) {
return convertedState;
}
const otherPreferencesScopes = convertedState?.[preferencesStoreName]?.preferences;
const otherInterfaceState = convertedState?.[interfaceStoreName];
const otherInterfaceScopes = convertedState?.[interfaceStoreName]?.preferences?.features;
return { ...convertedState,
return {
...convertedState,
[preferencesStoreName]: {
preferences: { ...otherPreferencesScopes,
preferences: {
...otherPreferencesScopes,
[scope]: featuresToMigrate
}
},
[interfaceStoreName]: { ...otherInterfaceState,
[interfaceStoreName]: {
...otherInterfaceState,
preferences: {
features: { ...otherInterfaceScopes,
features: {
...otherInterfaceScopes,
[scope]: undefined
}
}
@@ -444,6 +442,7 @@ function moveThirdPartyFeaturePreferencesToPreferences(state) {
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-individual-preference.js
const identity = arg => arg;
/**
* Migrates an individual item inside the `preferences` object for a package's store.
*
@@ -479,44 +478,48 @@ const identity = arg => arg;
* @param {string} key The key in the preferences object to migrate.
* @param {?Function} convert A function that converts preferences from one format to another.
*/
function moveIndividualPreferenceToPreferences(state, {
from: sourceStoreName,
to: scope
}, key, convert = identity) {
const preferencesStoreName = 'core/preferences';
const sourcePreference = state?.[sourceStoreName]?.preferences?.[key]; // There's nothing to migrate, exit early.
const sourcePreference = state?.[sourceStoreName]?.preferences?.[key];
// There's nothing to migrate, exit early.
if (sourcePreference === undefined) {
return state;
}
const targetPreference = state?.[preferencesStoreName]?.preferences?.[scope]?.[key];
const targetPreference = state?.[preferencesStoreName]?.preferences?.[scope]?.[key]; // There's existing data at the target, so don't overwrite it, exit early.
// There's existing data at the target, so don't overwrite it, exit early.
if (targetPreference) {
return state;
}
const otherScopes = state?.[preferencesStoreName]?.preferences;
const otherPreferences = state?.[preferencesStoreName]?.preferences?.[scope];
const otherSourceState = state?.[sourceStoreName];
const allSourcePreferences = state?.[sourceStoreName]?.preferences; // Pass an object with the key and value as this allows the convert
// function to convert to a data structure that has different keys.
const allSourcePreferences = state?.[sourceStoreName]?.preferences;
// Pass an object with the key and value as this allows the convert
// function to convert to a data structure that has different keys.
const convertedPreferences = convert({
[key]: sourcePreference
});
return { ...state,
return {
...state,
[preferencesStoreName]: {
preferences: { ...otherScopes,
[scope]: { ...otherPreferences,
preferences: {
...otherScopes,
[scope]: {
...otherPreferences,
...convertedPreferences
}
}
},
[sourceStoreName]: { ...otherSourceState,
preferences: { ...allSourcePreferences,
[sourceStoreName]: {
...otherSourceState,
preferences: {
...allSourcePreferences,
[key]: undefined
}
}
@@ -573,55 +576,61 @@ function moveIndividualPreferenceToPreferences(state, {
*/
function moveInterfaceEnableItems(state) {
var _state$preferencesSto, _sourceEnableItems$si, _sourceEnableItems$mu;
const interfaceStoreName = 'core/interface';
const preferencesStoreName = 'core/preferences';
const sourceEnableItems = state?.[interfaceStoreName]?.enableItems; // There's nothing to migrate, exit early.
const sourceEnableItems = state?.[interfaceStoreName]?.enableItems;
// There's nothing to migrate, exit early.
if (!sourceEnableItems) {
return state;
}
const allPreferences = (_state$preferencesSto = state?.[preferencesStoreName]?.preferences) !== null && _state$preferencesSto !== void 0 ? _state$preferencesSto : {};
const allPreferences = (_state$preferencesSto = state?.[preferencesStoreName]?.preferences) !== null && _state$preferencesSto !== void 0 ? _state$preferencesSto : {}; // First convert complementaryAreas into the right format.
// First convert complementaryAreas into the right format.
// Use the existing preferences as the accumulator so that the data is
// merged.
const sourceComplementaryAreas = (_sourceEnableItems$si = sourceEnableItems?.singleEnableItems?.complementaryArea) !== null && _sourceEnableItems$si !== void 0 ? _sourceEnableItems$si : {};
const preferencesWithConvertedComplementaryAreas = Object.keys(sourceComplementaryAreas).reduce((accumulator, scope) => {
const data = sourceComplementaryAreas[scope]; // Don't overwrite any existing data in the preferences store.
const data = sourceComplementaryAreas[scope];
// Don't overwrite any existing data in the preferences store.
if (accumulator?.[scope]?.complementaryArea) {
return accumulator;
}
return { ...accumulator,
[scope]: { ...accumulator[scope],
return {
...accumulator,
[scope]: {
...accumulator[scope],
complementaryArea: data
}
};
}, allPreferences); // Next feed the converted complementary areas back into a reducer that
// converts the pinned items, resulting in the fully migrated data.
}, allPreferences);
// Next feed the converted complementary areas back into a reducer that
// converts the pinned items, resulting in the fully migrated data.
const sourcePinnedItems = (_sourceEnableItems$mu = sourceEnableItems?.multipleEnableItems?.pinnedItems) !== null && _sourceEnableItems$mu !== void 0 ? _sourceEnableItems$mu : {};
const allConvertedData = Object.keys(sourcePinnedItems).reduce((accumulator, scope) => {
const data = sourcePinnedItems[scope]; // Don't overwrite any existing data in the preferences store.
const data = sourcePinnedItems[scope];
// Don't overwrite any existing data in the preferences store.
if (accumulator?.[scope]?.pinnedItems) {
return accumulator;
}
return { ...accumulator,
[scope]: { ...accumulator[scope],
return {
...accumulator,
[scope]: {
...accumulator[scope],
pinnedItems: data
}
};
}, preferencesWithConvertedComplementaryAreas);
const otherInterfaceItems = state[interfaceStoreName];
return { ...state,
return {
...state,
[preferencesStoreName]: {
preferences: allConvertedData
},
[interfaceStoreName]: { ...otherInterfaceItems,
[interfaceStoreName]: {
...otherInterfaceItems,
enableItems: undefined
}
};
@@ -661,19 +670,15 @@ function moveInterfaceEnableItems(state) {
*/
function convertEditPostPanels(preferences) {
var _preferences$panels;
const panels = (_preferences$panels = preferences?.panels) !== null && _preferences$panels !== void 0 ? _preferences$panels : {};
return Object.keys(panels).reduce((convertedData, panelName) => {
const panel = panels[panelName];
if (panel?.enabled === false) {
convertedData.inactivePanels.push(panelName);
}
if (panel?.opened === true) {
convertedData.openPanels.push(panelName);
}
return convertedData;
}, {
inactivePanels: [],
@@ -690,6 +695,7 @@ function convertEditPostPanels(preferences) {
/**
* Gets the legacy local storage data for a given user.
*
@@ -697,12 +703,12 @@ function convertEditPostPanels(preferences) {
*
* @return {Object | null} The local storage data.
*/
function getLegacyData(userId) {
const key = `WP_DATA_USER_${userId}`;
const unparsedData = window.localStorage.getItem(key);
return JSON.parse(unparsedData);
}
/**
* Converts data from the old `@wordpress/data` package format.
*
@@ -711,27 +717,28 @@ function getLegacyData(userId) {
* @return {Object | undefined} The converted data or `undefined` if there was
* nothing to convert.
*/
function convertLegacyData(data) {
if (!data) {
return;
} // Move boolean feature preferences from each editor into the
}
// Move boolean feature preferences from each editor into the
// preferences store data structure.
data = moveFeaturePreferences(data, 'core/edit-widgets');
data = moveFeaturePreferences(data, 'core/customize-widgets');
data = moveFeaturePreferences(data, 'core/edit-post');
data = moveFeaturePreferences(data, 'core/edit-site'); // Move third party boolean feature preferences from the interface package
data = moveFeaturePreferences(data, 'core/edit-site');
// Move third party boolean feature preferences from the interface package
// to the preferences store data structure.
data = moveThirdPartyFeaturePreferencesToPreferences(data);
data = moveThirdPartyFeaturePreferencesToPreferences(data); // Move and convert the interface store's `enableItems` data into the
// Move and convert the interface store's `enableItems` data into the
// preferences data structure.
data = moveInterfaceEnableItems(data);
data = moveInterfaceEnableItems(data); // Move individual ad-hoc preferences from various packages into the
// Move individual ad-hoc preferences from various packages into the
// preferences store data structure.
data = moveIndividualPreferenceToPreferences(data, {
from: 'core/edit-post',
to: 'core/edit-post'
@@ -755,11 +762,13 @@ function convertLegacyData(data) {
data = moveIndividualPreferenceToPreferences(data, {
from: 'core/edit-site',
to: 'core/edit-site'
}, 'editorMode'); // The new system is only concerned with persisting
// 'core/preferences' preferences reducer, so only return that.
}, 'editorMode');
// The new system is only concerned with persisting
// 'core/preferences' preferences reducer, so only return that.
return data?.['core/preferences']?.preferences;
}
/**
* Gets the legacy local storage data for the given user and returns the
* data converted to the new format.
@@ -769,7 +778,6 @@ function convertLegacyData(data) {
* @return {Object | undefined} The converted data or undefined if no local
* storage data could be found.
*/
function convertLegacyLocalStorageData(userId) {
const data = getLegacyData(userId);
return convertLegacyData(data);
@@ -778,17 +786,18 @@ function convertLegacyLocalStorageData(userId) {
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/convert-complementary-areas.js
function convertComplementaryAreas(state) {
return Object.keys(state).reduce((stateAccumulator, scope) => {
const scopeData = state[scope]; // If a complementary area is truthy, convert it to the `isComplementaryAreaVisible` boolean.
const scopeData = state[scope];
// If a complementary area is truthy, convert it to the `isComplementaryAreaVisible` boolean.
if (scopeData?.complementaryArea) {
const updatedScopeData = { ...scopeData
const updatedScopeData = {
...scopeData
};
delete updatedScopeData.complementaryArea;
updatedScopeData.isComplementaryAreaVisible = true;
stateAccumulator[scope] = updatedScopeData;
return stateAccumulator;
}
return stateAccumulator;
}, state);
}
@@ -810,6 +819,7 @@ function convertPreferencesPackageData(data) {
/**
* Creates the persistence layer with preloaded data.
*
@@ -824,16 +834,15 @@ function convertPreferencesPackageData(data) {
*
* @return {Object} The persistence layer initialized with the preloaded data.
*/
function __unstableCreatePersistenceLayer(serverData, userId) {
const localStorageRestoreKey = `WP_PREFERENCES_USER_${userId}`;
const localData = JSON.parse(window.localStorage.getItem(localStorageRestoreKey)); // Date parse returns NaN for invalid input. Coerce anything invalid
// into a conveniently comparable zero.
const localData = JSON.parse(window.localStorage.getItem(localStorageRestoreKey));
// Date parse returns NaN for invalid input. Coerce anything invalid
// into a conveniently comparable zero.
const serverModified = Date.parse(serverData && serverData._modified) || 0;
const localModified = Date.parse(localData && localData._modified) || 0;
let preloadedData;
if (serverData && serverModified >= localModified) {
preloadedData = convertPreferencesPackageData(serverData);
} else if (localData) {
@@ -842,7 +851,6 @@ function __unstableCreatePersistenceLayer(serverData, userId) {
// Check if there is data in the legacy format from the old persistence system.
preloadedData = convertLegacyLocalStorageData(userId);
}
return create({
preloadedData,
localStorageRestoreKey
+25 -35
View File
@@ -39,25 +39,25 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"PreferenceToggleMenuItem": function() { return /* reexport */ PreferenceToggleMenuItem; },
"store": function() { return /* reexport */ store; }
PreferenceToggleMenuItem: function() { return /* reexport */ PreferenceToggleMenuItem; },
store: function() { return /* reexport */ store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/preferences/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"set": function() { return set; },
"setDefaults": function() { return setDefaults; },
"setPersistenceLayer": function() { return setPersistenceLayer; },
"toggle": function() { return toggle; }
set: function() { return set; },
setDefaults: function() { return setDefaults; },
setPersistenceLayer: function() { return setPersistenceLayer; },
toggle: function() { return toggle; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/preferences/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"get": function() { return get; }
get: function() { return get; }
});
;// CONCATENATED MODULE: external ["wp","element"]
@@ -72,7 +72,6 @@ var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/check.js
/**
* WordPress dependencies
*/
@@ -92,6 +91,7 @@ var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
* WordPress dependencies
*/
/**
* Reducer returning the defaults for user preferences.
*
@@ -103,22 +103,23 @@ var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
*
* @return {Object} Updated state.
*/
function defaults(state = {}, action) {
if (action.type === 'SET_PREFERENCE_DEFAULTS') {
const {
scope,
defaults: values
} = action;
return { ...state,
[scope]: { ...state[scope],
return {
...state,
[scope]: {
...state[scope],
...values
}
};
}
return state;
}
/**
* Higher order reducer that does the following:
* - Merges any data from the persistence layer into the state when the
@@ -129,7 +130,6 @@ function defaults(state = {}, action) {
*
* @return {Function} The enhanced reducer.
*/
function withPersistenceLayer(reducer) {
let persistenceLayer;
return (state, action) => {
@@ -143,16 +143,14 @@ function withPersistenceLayer(reducer) {
persistenceLayer = persistence;
return persistedData;
}
const nextState = reducer(state, action);
if (action.type === 'SET_PREFERENCE_VALUE') {
persistenceLayer?.set(nextState);
}
return nextState;
};
}
/**
* Reducer returning the user preferences.
*
@@ -161,8 +159,6 @@ function withPersistenceLayer(reducer) {
*
* @return {Object} Updated state.
*/
const preferences = withPersistenceLayer((state = {}, action) => {
if (action.type === 'SET_PREFERENCE_VALUE') {
const {
@@ -170,13 +166,14 @@ const preferences = withPersistenceLayer((state = {}, action) => {
name,
value
} = action;
return { ...state,
[scope]: { ...state[scope],
return {
...state,
[scope]: {
...state[scope],
[name]: value
}
};
}
return state;
});
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
@@ -201,6 +198,7 @@ function toggle(scope, name) {
dispatch.set(scope, name, !currentValue);
};
}
/**
* Returns an action object used in signalling that a preference should be set
* to a value
@@ -211,7 +209,6 @@ function toggle(scope, name) {
*
* @return {Object} Action object.
*/
function set(scope, name, value) {
return {
type: 'SET_PREFERENCE_VALUE',
@@ -220,6 +217,7 @@ function set(scope, name, value) {
value
};
}
/**
* Returns an action object used in signalling that preference defaults should
* be set.
@@ -229,7 +227,6 @@ function set(scope, name, value) {
*
* @return {Object} Action object.
*/
function setDefaults(scope, defaults) {
return {
type: 'SET_PREFERENCE_DEFAULTS',
@@ -237,10 +234,9 @@ function setDefaults(scope, defaults) {
defaults
};
}
/** @typedef {() => Promise<Object>} WPPreferencesPersistenceLayerGet */
/** @typedef {(Object) => void} WPPreferencesPersistenceLayerSet */
/**
* @typedef WPPreferencesPersistenceLayer
*
@@ -263,7 +259,6 @@ function setDefaults(scope, defaults) {
*
* @return {Object} Action object.
*/
async function setPersistenceLayer(persistenceLayer) {
const persistedData = await persistenceLayer.get();
return {
@@ -302,6 +297,7 @@ const STORE_NAME = 'core/preferences';
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -317,7 +313,6 @@ const STORE_NAME = 'core/preferences';
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, {
reducer: reducer,
actions: actions_namespaceObject,
@@ -327,7 +322,6 @@ const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME,
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/components/preference-toggle-menu-item/index.js
/**
* WordPress dependencies
*/
@@ -336,11 +330,11 @@ const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME,
/**
* Internal dependencies
*/
function PreferenceToggleMenuItem({
scope,
name,
@@ -356,21 +350,17 @@ function PreferenceToggleMenuItem({
const {
toggle
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const speakMessage = () => {
if (isActive) {
const message = messageDeactivated || (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: preference name, e.g. 'Fullscreen mode' */
const message = messageDeactivated || (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %s: preference name, e.g. 'Fullscreen mode' */
(0,external_wp_i18n_namespaceObject.__)('Preference deactivated - %s'), label);
(0,external_wp_a11y_namespaceObject.speak)(message);
} else {
const message = messageActivated || (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: preference name, e.g. 'Fullscreen mode' */
const message = messageActivated || (0,external_wp_i18n_namespaceObject.sprintf)( /* translators: %s: preference name, e.g. 'Fullscreen mode' */
(0,external_wp_i18n_namespaceObject.__)('Preference activated - %s'), label);
(0,external_wp_a11y_namespaceObject.speak)(message);
}
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
icon: isActive && library_check,
isSelected: isActive,
+40 -35
View File
@@ -144,20 +144,20 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"BlockQuotation": function() { return /* reexport */ BlockQuotation; },
"Circle": function() { return /* reexport */ Circle; },
"Defs": function() { return /* reexport */ Defs; },
"G": function() { return /* reexport */ G; },
"HorizontalRule": function() { return /* reexport */ HorizontalRule; },
"Line": function() { return /* reexport */ Line; },
"LinearGradient": function() { return /* reexport */ LinearGradient; },
"Path": function() { return /* reexport */ Path; },
"Polygon": function() { return /* reexport */ Polygon; },
"RadialGradient": function() { return /* reexport */ RadialGradient; },
"Rect": function() { return /* reexport */ Rect; },
"SVG": function() { return /* reexport */ SVG; },
"Stop": function() { return /* reexport */ Stop; },
"View": function() { return /* reexport */ View; }
BlockQuotation: function() { return /* reexport */ BlockQuotation; },
Circle: function() { return /* reexport */ Circle; },
Defs: function() { return /* reexport */ Defs; },
G: function() { return /* reexport */ G; },
HorizontalRule: function() { return /* reexport */ HorizontalRule; },
Line: function() { return /* reexport */ Line; },
LinearGradient: function() { return /* reexport */ LinearGradient; },
Path: function() { return /* reexport */ Path; },
Polygon: function() { return /* reexport */ Polygon; },
RadialGradient: function() { return /* reexport */ RadialGradient; },
Rect: function() { return /* reexport */ Rect; },
SVG: function() { return /* reexport */ SVG; },
Stop: function() { return /* reexport */ Stop; },
View: function() { return /* reexport */ View; }
});
// EXTERNAL MODULE: ./node_modules/classnames/index.js
@@ -170,6 +170,7 @@ var external_wp_element_namespaceObject = window["wp"]["element"];
* External dependencies
*/
/**
* WordPress dependencies
*/
@@ -182,96 +183,100 @@ var external_wp_element_namespaceObject = window["wp"]["element"];
*
* @return {JSX.Element} Circle component
*/
const Circle = props => (0,external_wp_element_namespaceObject.createElement)('circle', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'g'>} props
*
* @return {JSX.Element} G component
*/
const G = props => (0,external_wp_element_namespaceObject.createElement)('g', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'line'>} props
*
* @return {JSX.Element} Path component
*/
const Line = props => (0,external_wp_element_namespaceObject.createElement)('line', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'path'>} props
*
* @return {JSX.Element} Path component
*/
const Path = props => (0,external_wp_element_namespaceObject.createElement)('path', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'polygon'>} props
*
* @return {JSX.Element} Polygon component
*/
const Polygon = props => (0,external_wp_element_namespaceObject.createElement)('polygon', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'rect'>} props
*
* @return {JSX.Element} Rect component
*/
const Rect = props => (0,external_wp_element_namespaceObject.createElement)('rect', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'defs'>} props
*
* @return {JSX.Element} Defs component
*/
const Defs = props => (0,external_wp_element_namespaceObject.createElement)('defs', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'radialGradient'>} props
*
* @return {JSX.Element} RadialGradient component
*/
const RadialGradient = props => (0,external_wp_element_namespaceObject.createElement)('radialGradient', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'linearGradient'>} props
*
* @return {JSX.Element} LinearGradient component
*/
const LinearGradient = props => (0,external_wp_element_namespaceObject.createElement)('linearGradient', props);
/**
* @param {import('react').ComponentPropsWithoutRef<'stop'>} props
*
* @return {JSX.Element} Stop component
*/
const Stop = props => (0,external_wp_element_namespaceObject.createElement)('stop', props);
const SVG = (0,external_wp_element_namespaceObject.forwardRef)(
/**
*
* @param {SVGProps} props isPressed indicates whether the SVG should appear as pressed.
* Other props will be passed through to svg component.
* @param {SVGProps} props isPressed indicates whether the SVG should appear as pressed.
* Other props will be passed through to svg component.
* @param {import('react').ForwardedRef<SVGSVGElement>} ref The forwarded ref to the SVG element.
*
* @return {JSX.Element} Stop component
*/
const SVG = ({
({
className,
isPressed,
...props
}) => {
const appliedProps = { ...props,
}, ref) => {
const appliedProps = {
...props,
className: classnames_default()(className, {
'is-pressed': isPressed
}) || undefined,
'aria-hidden': true,
focusable: false
}; // Disable reason: We need to have a way to render HTML tag for web.
// eslint-disable-next-line react/forbid-elements
};
return (0,external_wp_element_namespaceObject.createElement)("svg", { ...appliedProps
// Disable reason: We need to have a way to render HTML tag for web.
// eslint-disable-next-line react/forbid-elements
return (0,external_wp_element_namespaceObject.createElement)("svg", {
...appliedProps,
ref: ref
});
};
});
SVG.displayName = 'SVG';
;// CONCATENATED MODULE: ./node_modules/@wordpress/primitives/build-module/horizontal-rule/index.js
const HorizontalRule = 'hr';
+1 -1
View File
@@ -4,4 +4,4 @@
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/!function(){"use strict";var r={}.hasOwnProperty;function o(){for(var e=[],t=0;t<arguments.length;t++){var n=arguments[t];if(n){var i=typeof n;if("string"===i||"number"===i)e.push(n);else if(Array.isArray(n)){if(n.length){var u=o.apply(null,n);u&&e.push(u)}}else if("object"===i){if(n.toString!==Object.prototype.toString&&!n.toString.toString().includes("[native code]")){e.push(n.toString());continue}for(var a in n)r.call(n,a)&&n[a]&&e.push(a)}}}return e.join(" ")}e.exports?(o.default=o,e.exports=o):void 0===(n=function(){return o}.apply(t,[]))||(e.exports=n)}()}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};!function(){"use strict";n.r(r),n.d(r,{BlockQuotation:function(){return g},Circle:function(){return i},Defs:function(){return s},G:function(){return u},HorizontalRule:function(){return y},Line:function(){return a},LinearGradient:function(){return d},Path:function(){return c},Polygon:function(){return l},RadialGradient:function(){return p},Rect:function(){return f},SVG:function(){return m},Stop:function(){return v},View:function(){return b}});var e=n(4403),t=n.n(e),o=window.wp.element;const i=e=>(0,o.createElement)("circle",e),u=e=>(0,o.createElement)("g",e),a=e=>(0,o.createElement)("line",e),c=e=>(0,o.createElement)("path",e),l=e=>(0,o.createElement)("polygon",e),f=e=>(0,o.createElement)("rect",e),s=e=>(0,o.createElement)("defs",e),p=e=>(0,o.createElement)("radialGradient",e),d=e=>(0,o.createElement)("linearGradient",e),v=e=>(0,o.createElement)("stop",e),m=({className:e,isPressed:n,...r})=>{const i={...r,className:t()(e,{"is-pressed":n})||void 0,"aria-hidden":!0,focusable:!1};return(0,o.createElement)("svg",{...i})},y="hr",g="blockquote",b="div"}(),(window.wp=window.wp||{}).primitives=r}();
*/!function(){"use strict";var r={}.hasOwnProperty;function o(){for(var e=[],t=0;t<arguments.length;t++){var n=arguments[t];if(n){var i=typeof n;if("string"===i||"number"===i)e.push(n);else if(Array.isArray(n)){if(n.length){var u=o.apply(null,n);u&&e.push(u)}}else if("object"===i){if(n.toString!==Object.prototype.toString&&!n.toString.toString().includes("[native code]")){e.push(n.toString());continue}for(var a in n)r.call(n,a)&&n[a]&&e.push(a)}}}return e.join(" ")}e.exports?(o.default=o,e.exports=o):void 0===(n=function(){return o}.apply(t,[]))||(e.exports=n)}()}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};!function(){"use strict";n.r(r),n.d(r,{BlockQuotation:function(){return g},Circle:function(){return i},Defs:function(){return s},G:function(){return u},HorizontalRule:function(){return y},Line:function(){return a},LinearGradient:function(){return d},Path:function(){return c},Polygon:function(){return l},RadialGradient:function(){return p},Rect:function(){return f},SVG:function(){return m},Stop:function(){return v},View:function(){return b}});var e=n(4403),t=n.n(e),o=window.wp.element;const i=e=>(0,o.createElement)("circle",e),u=e=>(0,o.createElement)("g",e),a=e=>(0,o.createElement)("line",e),c=e=>(0,o.createElement)("path",e),l=e=>(0,o.createElement)("polygon",e),f=e=>(0,o.createElement)("rect",e),s=e=>(0,o.createElement)("defs",e),p=e=>(0,o.createElement)("radialGradient",e),d=e=>(0,o.createElement)("linearGradient",e),v=e=>(0,o.createElement)("stop",e),m=(0,o.forwardRef)((({className:e,isPressed:n,...r},i)=>{const u={...r,className:t()(e,{"is-pressed":n})||void 0,"aria-hidden":!0,focusable:!1};return(0,o.createElement)("svg",{...u,ref:i})}));m.displayName="SVG";const y="hr",g="blockquote",b="div"}(),(window.wp=window.wp||{}).primitives=r}();
+8 -20
View File
@@ -297,7 +297,7 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"createQueue": function() { return /* binding */ createQueue; }
createQueue: function() { return /* binding */ createQueue; }
});
// EXTERNAL MODULE: ./node_modules/requestidlecallback/index.js
@@ -307,6 +307,7 @@ var requestidlecallback = __webpack_require__(3159);
* External dependencies
*/
/**
* @typedef {( timeOrDeadline: IdleDeadline | number ) => void} Callback
*/
@@ -314,14 +315,12 @@ var requestidlecallback = __webpack_require__(3159);
/**
* @return {(callback: Callback) => void} RequestIdleCallback
*/
function createRequestIdleCallback() {
if (typeof window === 'undefined') {
return callback => {
setTimeout(() => callback(Date.now()), 0);
};
}
return window.requestIdleCallback;
}
/* harmony default export */ var request_idle_callback = (createRequestIdleCallback());
@@ -331,6 +330,7 @@ function createRequestIdleCallback() {
* Internal dependencies
*/
/**
* Enqueued callback to invoke once idle time permits.
*
@@ -394,11 +394,11 @@ function createRequestIdleCallback() {
*
* @return {WPPriorityQueue} Queue object with `add`, `flush` and `reset` methods.
*/
const createQueue = () => {
/** @type {Map<WPPriorityQueueContext, WPPriorityQueueCallback>} */
const waitingList = new Map();
let isRunning = false;
/**
* Callback to process as much queue as time permits.
*
@@ -415,24 +415,21 @@ const createQueue = () => {
* @param {IdleDeadline|number} deadline Idle callback deadline object, or
* animation frame timestamp.
*/
const runWaitingList = deadline => {
for (const [nextElement, callback] of waitingList) {
waitingList.delete(nextElement);
callback();
if ('number' === typeof deadline || deadline.timeRemaining() <= 0) {
break;
}
}
if (waitingList.size === 0) {
isRunning = false;
return;
}
request_idle_callback(runWaitingList);
};
/**
* Add a callback to the queue for a given context.
*
@@ -446,16 +443,14 @@ const createQueue = () => {
* @param {WPPriorityQueueContext} element Context object.
* @param {WPPriorityQueueCallback} item Callback function.
*/
const add = (element, item) => {
waitingList.set(element, item);
if (!isRunning) {
isRunning = true;
request_idle_callback(runWaitingList);
}
};
/**
* Flushes queue for a given context, returning true if the flush was
* performed, or false if there is no queue for the given context.
@@ -466,19 +461,16 @@ const createQueue = () => {
*
* @return {boolean} Whether flush was performed.
*/
const flush = element => {
const callback = waitingList.get(element);
if (undefined === callback) {
return false;
}
waitingList.delete(element);
callback();
return true;
};
/**
* Clears the queue for a given context, cancelling the callbacks without
* executing them. Returns `true` if there were scheduled callbacks to cancel,
@@ -490,23 +482,19 @@ const createQueue = () => {
*
* @return {boolean} Whether any callbacks got cancelled.
*/
const cancel = element => {
return waitingList.delete(element);
};
/**
* Reset the queue without running the pending callbacks.
*
* @type {WPPriorityQueueReset}
*/
const reset = () => {
waitingList.clear();
isRunning = false;
};
return {
add,
flush,
+14 -25
View File
@@ -39,7 +39,7 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"__dangerousOptInToUnstableAPIsOnlyForCoreModules": function() { return /* reexport */ __dangerousOptInToUnstableAPIsOnlyForCoreModules; }
__dangerousOptInToUnstableAPIsOnlyForCoreModules: function() { return /* reexport */ __dangerousOptInToUnstableAPIsOnlyForCoreModules; }
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/private-apis/build-module/implementation.js
@@ -54,15 +54,16 @@ __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-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/reusable-blocks', '@wordpress/router'];
const CORE_MODULES_USING_PRIVATE_APIS = ['@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/patterns', '@wordpress/reusable-blocks', '@wordpress/router'];
/**
* A list of core modules that already opted-in to
* the privateApis package.
*
* @type {string[]}
*/
const registeredPrivateApis = [];
/*
* Warning for theme and plugin developers.
*
@@ -77,21 +78,21 @@ const registeredPrivateApis = [];
* WITHOUT NOTICE. THIS CHANGE WILL BREAK EXISTING THIRD-PARTY CODE. SUCH A
* CHANGE MAY OCCUR IN EITHER A MAJOR OR MINOR RELEASE.
*/
const requiredConsent = 'I know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.';
const requiredConsent = 'I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.';
/** @type {boolean} */
let allowReRegistration; // The safety measure is meant for WordPress core where IS_WORDPRESS_CORE
let allowReRegistration;
// The safety measure is meant for WordPress core where IS_WORDPRESS_CORE
// is set to true.
// For the general use-case, the re-registration should be allowed by default
// Let's default to true, then. Try/catch will fall back to "true" even if the
// environment variable is not explicitly defined.
try {
allowReRegistration = true ? false : 0;
} catch (error) {
allowReRegistration = true;
}
/**
* Called by a @wordpress package wishing to opt-in to accessing or exposing
* private private APIs.
@@ -100,30 +101,26 @@ try {
* @param {string} moduleName The name of the module that is opting in.
* @return {{lock: typeof lock, unlock: typeof unlock}} An object containing the lock and unlock functions.
*/
const __dangerousOptInToUnstableAPIsOnlyForCoreModules = (consent, moduleName) => {
if (!CORE_MODULES_USING_PRIVATE_APIS.includes(moduleName)) {
throw new Error(`You tried to opt-in to unstable APIs as module "${moduleName}". ` + '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 (!allowReRegistration && registeredPrivateApis.includes(moduleName)) {
// This check doesn't play well with Story Books / Hot Module Reloading
// and isn't included in the Gutenberg plugin. It only matters in the
// WordPress core release.
throw new Error(`You tried to opt-in to unstable APIs as module "${moduleName}" 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 (consent !== requiredConsent) {
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.');
}
registeredPrivateApis.push(moduleName);
return {
lock,
unlock
};
};
/**
* Binds private data to an object.
* It does not alter the passed object in any way, only
@@ -148,18 +145,16 @@ const __dangerousOptInToUnstableAPIsOnlyForCoreModules = (consent, moduleName) =
* @param {any} object The object to bind the private data to.
* @param {any} privateData The private data to bind to the object.
*/
function lock(object, privateData) {
if (!object) {
throw new Error('Cannot lock an undefined object.');
}
if (!(__private in object)) {
object[__private] = {};
}
lockedData.set(object[__private], privateData);
}
/**
* Unlocks the private data bound to an object.
*
@@ -183,27 +178,24 @@ function lock(object, privateData) {
* @param {any} object The object to unlock the private data from.
* @return {any} The private data bound to the object.
*/
function unlock(object) {
if (!object) {
throw new Error('Cannot unlock an undefined object.');
}
if (!(__private in object)) {
throw new Error('Cannot unlock an object that was not locked before. ');
}
return lockedData.get(object[__private]);
}
const lockedData = new WeakMap();
/**
* Used by lock() and unlock() to uniquely identify the private data
* related to a containing object.
*/
const __private = Symbol('Private API ID');
const __private = Symbol('Private API ID'); // Unit tests utilities:
// Unit tests utilities:
/**
* Private function to allow the unit tests to allow
@@ -211,16 +203,14 @@ const __private = Symbol('Private API ID'); // Unit tests utilities:
*
* @param {string} name The name of the module.
*/
function allowCoreModule(name) {
CORE_MODULES_USING_PRIVATE_APIS.push(name);
}
/**
* Private function to allow the unit tests to set
* a custom list of allowed modules.
*/
function resetAllowedCoreModules() {
while (CORE_MODULES_USING_PRIVATE_APIS.length) {
CORE_MODULES_USING_PRIVATE_APIS.pop();
@@ -230,7 +220,6 @@ function resetAllowedCoreModules() {
* Private function to allow the unit tests to reset
* the list of registered private apis.
*/
function resetRegisteredPrivateApis() {
while (registeredPrivateApis.length) {
registeredPrivateApis.pop();
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
!function(){"use strict";var e={d:function(o,r){for(var t in r)e.o(r,t)&&!e.o(o,t)&&Object.defineProperty(o,t,{enumerable:!0,get:r[t]})},o:function(e,o){return Object.prototype.hasOwnProperty.call(e,o)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},o={};e.r(o),e.d(o,{__dangerousOptInToUnstableAPIsOnlyForCoreModules:function(){return s}});const r=["@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/reusable-blocks","@wordpress/router"],t=[];let n;try{n=!1}catch(e){n=!0}const s=(e,o)=>{if(!r.includes(o))throw new Error(`You tried to opt-in to unstable APIs as module "${o}". 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(!n&&t.includes(o))throw new Error(`You tried to opt-in to unstable APIs as module "${o}" 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 know using unstable features means my plugin or theme will inevitably break on the next WordPress release."!==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 t.push(o),{lock:i,unlock:a}};function i(e,o){if(!e)throw new Error("Cannot lock an undefined object.");u in e||(e[u]={}),d.set(e[u],o)}function a(e){if(!e)throw new Error("Cannot unlock an undefined object.");if(!(u in e))throw new Error("Cannot unlock an object that was not locked before. ");return d.get(e[u])}const d=new WeakMap,u=Symbol("Private API ID");(window.wp=window.wp||{}).privateApis=o}();
!function(){"use strict";var e={d:function(o,r){for(var t in r)e.o(r,t)&&!e.o(o,t)&&Object.defineProperty(o,t,{enumerable:!0,get:r[t]})},o:function(e,o){return Object.prototype.hasOwnProperty.call(e,o)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},o={};e.r(o),e.d(o,{__dangerousOptInToUnstableAPIsOnlyForCoreModules:function(){return s}});const r=["@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/patterns","@wordpress/reusable-blocks","@wordpress/router"],t=[];let n;try{n=!1}catch(e){n=!0}const s=(e,o)=>{if(!r.includes(o))throw new Error(`You tried to opt-in to unstable APIs as module "${o}". 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(!n&&t.includes(o))throw new Error(`You tried to opt-in to unstable APIs as module "${o}" 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 know using unstable features means my theme or plugin will inevitably 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 t.push(o),{lock:i,unlock:a}};function i(e,o){if(!e)throw new Error("Cannot lock an undefined object.");u in e||(e[u]={}),d.set(e[u],o)}function a(e){if(!e)throw new Error("Cannot unlock an undefined object.");if(!(u in e))throw new Error("Cannot unlock an object that was not locked before. ");return d.get(e[u])}const d=new WeakMap,u=Symbol("Private API ID");(window.wp=window.wp||{}).privateApis=o}();
+4 -14
View File
@@ -707,7 +707,6 @@ __webpack_require__.d(__webpack_exports__, {
;// CONCATENATED MODULE: ./node_modules/@wordpress/redux-routine/build-module/is-generator.js
/* eslint-disable jsdoc/valid-types */
/**
* Returns true if the given object is a generator, or false otherwise.
*
@@ -772,8 +771,8 @@ function isPlainObject(o) {
* External dependencies
*/
/* eslint-disable jsdoc/valid-types */
/* eslint-disable jsdoc/valid-types */
/**
* Returns true if the given object quacks like an action.
*
@@ -781,10 +780,10 @@ function isPlainObject(o) {
*
* @return {object is import('redux').AnyAction} Whether object is an action.
*/
function isAction(object) {
return isPlainObject(object) && typeof object.type === 'string';
}
/**
* Returns true if the given object quacks like an action and has a specific
* action type
@@ -794,7 +793,6 @@ function isAction(object) {
*
* @return {object is import('redux').AnyAction} Whether object is an action and is of specific type.
*/
function isActionOfType(object, expectedType) {
/* eslint-enable jsdoc/valid-types */
return isAction(object) && object.type === expectedType;
@@ -811,48 +809,41 @@ function isActionOfType(object, expectedType) {
* Internal dependencies
*/
/**
* Create a co-routine runtime.
*
* @param controls Object of control handlers.
* @param dispatch Unhandled action dispatch.
*/
function createRuntime(controls = {}, dispatch) {
const rungenControls = Object.entries(controls).map(([actionType, control]) => (value, next, iterate, yieldNext, yieldError) => {
if (!isActionOfType(value, actionType)) {
return false;
}
const routine = control(value);
if (isPromise(routine)) {
// Async control routine awaits resolution.
routine.then(yieldNext, yieldError);
} else {
yieldNext(routine);
}
return true;
});
const unhandledActionControl = (value, next) => {
if (!isAction(value)) {
return false;
}
dispatch(value);
next();
return true;
};
rungenControls.push(unhandledActionControl);
const rungenRuntime = (0,dist.create)(rungenControls);
return action => new Promise((resolve, reject) => rungenRuntime(action, result => {
if (isAction(result)) {
dispatch(result);
}
resolve(result);
}, reject));
}
@@ -863,6 +854,7 @@ function createRuntime(controls = {}, dispatch) {
*/
/**
* Creates a Redux middleware, given an object of controls where each key is an
* action type for which to act upon, the value a function which returns either
@@ -875,7 +867,6 @@ function createRuntime(controls = {}, dispatch) {
*
* @return {import('redux').Middleware} Co-routine runtime
*/
function createMiddleware(controls = {}) {
return store => {
const runtime = createRuntime(controls, store.dispatch);
@@ -883,7 +874,6 @@ function createMiddleware(controls = {}) {
if (!isGenerator(action)) {
return next(action);
}
return runtime(action);
};
};
+58 -65
View File
@@ -39,25 +39,25 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"ReusableBlocksMenuItems": function() { return /* reexport */ ReusableBlocksMenuItems; },
"store": function() { return /* reexport */ store; }
ReusableBlocksMenuItems: function() { return /* reexport */ ReusableBlocksMenuItems; },
store: function() { return /* reexport */ store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/reusable-blocks/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"__experimentalConvertBlockToStatic": function() { return __experimentalConvertBlockToStatic; },
"__experimentalConvertBlocksToReusable": function() { return __experimentalConvertBlocksToReusable; },
"__experimentalDeleteReusableBlock": function() { return __experimentalDeleteReusableBlock; },
"__experimentalSetEditingReusableBlock": function() { return __experimentalSetEditingReusableBlock; }
__experimentalConvertBlockToStatic: function() { return __experimentalConvertBlockToStatic; },
__experimentalConvertBlocksToReusable: function() { return __experimentalConvertBlocksToReusable; },
__experimentalDeleteReusableBlock: function() { return __experimentalDeleteReusableBlock; },
__experimentalSetEditingReusableBlock: function() { return __experimentalSetEditingReusableBlock; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/reusable-blocks/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"__experimentalIsEditingReusableBlock": function() { return __experimentalIsEditingReusableBlock; }
__experimentalIsEditingReusableBlock: function() { return __experimentalIsEditingReusableBlock; }
});
;// CONCATENATED MODULE: external ["wp","data"]
@@ -75,12 +75,12 @@ var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
/**
* Returns a generator converting a reusable block into a static block.
*
* @param {string} clientId The client ID of the block to attach.
*/
const __experimentalConvertBlockToStatic = clientId => ({
registry
}) => {
@@ -89,6 +89,7 @@ const __experimentalConvertBlockToStatic = clientId => ({
const newBlocks = (0,external_wp_blocks_namespaceObject.parse)(typeof reusableBlock.content === 'function' ? reusableBlock.content(reusableBlock) : reusableBlock.content);
registry.dispatch(external_wp_blockEditor_namespaceObject.store).replaceBlocks(oldBlock.clientId, newBlocks);
};
/**
* Returns a generator converting one or more static blocks into a pattern.
*
@@ -96,7 +97,6 @@ const __experimentalConvertBlockToStatic = clientId => ({
* @param {string} title Pattern title.
* @param {undefined|'unsynced'} syncType They way block is synced, current undefined (synced) and 'unsynced'.
*/
const __experimentalConvertBlocksToReusable = (clientIds, title, syncType) => async ({
registry,
dispatch
@@ -105,50 +105,49 @@ const __experimentalConvertBlocksToReusable = (clientIds, title, syncType) => as
wp_pattern_sync_status: syncType
} : undefined;
const reusableBlock = {
title: title || (0,external_wp_i18n_namespaceObject.__)('Untitled Pattern block'),
title: title || (0,external_wp_i18n_namespaceObject.__)('Untitled pattern block'),
content: (0,external_wp_blocks_namespaceObject.serialize)(registry.select(external_wp_blockEditor_namespaceObject.store).getBlocksByClientId(clientIds)),
status: 'publish',
meta
};
const updatedRecord = await registry.dispatch('core').saveEntityRecord('postType', 'wp_block', reusableBlock);
if (syncType === 'unsynced') {
return;
}
const newBlock = (0,external_wp_blocks_namespaceObject.createBlock)('core/block', {
ref: updatedRecord.id
});
registry.dispatch(external_wp_blockEditor_namespaceObject.store).replaceBlocks(clientIds, newBlock);
dispatch.__experimentalSetEditingReusableBlock(newBlock.clientId, true);
};
/**
* Returns a generator deleting a reusable block.
*
* @param {string} id The ID of the reusable block to delete.
*/
const __experimentalDeleteReusableBlock = id => async ({
registry
}) => {
const reusableBlock = registry.select('core').getEditedEntityRecord('postType', 'wp_block', id); // Don't allow a reusable block with a temporary ID to be deleted.
const reusableBlock = registry.select('core').getEditedEntityRecord('postType', 'wp_block', id);
// Don't allow a reusable block with a temporary ID to be deleted.
if (!reusableBlock) {
return;
} // Remove any other blocks that reference this reusable block.
}
// Remove any other blocks that reference this reusable block.
const allBlocks = registry.select(external_wp_blockEditor_namespaceObject.store).getBlocks();
const associatedBlocks = allBlocks.filter(block => (0,external_wp_blocks_namespaceObject.isReusableBlock)(block) && block.attributes.ref === id);
const associatedBlockClientIds = associatedBlocks.map(block => block.clientId); // Remove the parsed block.
const associatedBlockClientIds = associatedBlocks.map(block => block.clientId);
// Remove the parsed block.
if (associatedBlockClientIds.length) {
registry.dispatch(external_wp_blockEditor_namespaceObject.store).removeBlocks(associatedBlockClientIds);
}
await registry.dispatch('core').deleteEntityRecord('postType', 'wp_block', id);
};
/**
* Returns an action descriptor for SET_EDITING_REUSABLE_BLOCK action.
*
@@ -156,7 +155,6 @@ const __experimentalDeleteReusableBlock = id => async ({
* @param {boolean} isEditing Whether the block should be in editing state.
* @return {Object} Action descriptor.
*/
function __experimentalSetEditingReusableBlock(clientId, isEditing) {
return {
type: 'SET_EDITING_REUSABLE_BLOCK',
@@ -172,11 +170,11 @@ function __experimentalSetEditingReusableBlock(clientId, isEditing) {
function isEditingReusableBlock(state = {}, action) {
if (action?.type === 'SET_EDITING_REUSABLE_BLOCK') {
return { ...state,
return {
...state,
[action.clientId]: action.isEditing
};
}
return state;
}
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
@@ -200,14 +198,15 @@ function __experimentalIsEditingReusableBlock(state, clientId) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const STORE_NAME = 'core/reusable-blocks';
/**
* Store definition for the reusable blocks namespace.
*
@@ -215,7 +214,6 @@ const STORE_NAME = 'core/reusable-blocks';
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, {
actions: actions_namespaceObject,
reducer: reducer,
@@ -231,7 +229,6 @@ var external_wp_components_namespaceObject = window["wp"]["components"];
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/symbol.js
/**
* WordPress dependencies
*/
@@ -257,11 +254,10 @@ var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
const {
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.', '@wordpress/reusable-blocks');
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I know using unstable features means my theme or plugin will inevitably 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
*/
@@ -274,6 +270,7 @@ const {
/**
* Internal dependencies
*/
@@ -286,12 +283,13 @@ const {
* @param {Object} props Component props.
* @param {string[]} props.clientIds Client ids of selected blocks.
* @param {string} props.rootClientId ID of the currently selected top-level block.
* @param {()=>void} props.onClose Callback to close the menu.
* @return {import('@wordpress/element').WPComponent} The menu control or null.
*/
function ReusableBlockConvertButton({
clientIds,
rootClientId
rootClientId,
onClose
}) {
const {
useReusableBlocksRenameHint,
@@ -303,7 +301,6 @@ function ReusableBlockConvertButton({
const [title, setTitle] = (0,external_wp_element_namespaceObject.useState)('');
const canConvert = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlocksByClientId;
const {
canUser
} = select(external_wp_coreData_namespaceObject.store);
@@ -315,15 +312,19 @@ function ReusableBlockConvertButton({
const rootId = rootClientId || (clientIds.length > 0 ? getBlockRootClientId(clientIds[0]) : undefined);
const blocks = (_getBlocksByClientId = getBlocksByClientId(clientIds)) !== null && _getBlocksByClientId !== void 0 ? _getBlocksByClientId : [];
const isReusable = blocks.length === 1 && blocks[0] && (0,external_wp_blocks_namespaceObject.isReusableBlock)(blocks[0]) && !!select(external_wp_coreData_namespaceObject.store).getEntityRecord('postType', 'wp_block', blocks[0].attributes.ref);
const _canConvert = // Hide when this is already a reusable block.
!isReusable && // Hide when reusable blocks are disabled.
canInsertBlockType('core/block', rootId) && blocks.every(block => // Guard against the case where a regular block has *just* been converted.
!!block && // Hide on invalid blocks.
block.isValid && // 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.
const _canConvert =
// Hide when this is already a reusable block.
!isReusable &&
// Hide when reusable blocks are disabled.
canInsertBlockType('core/block', rootId) && blocks.every(block =>
// Guard against the case where a regular block has *just* been converted.
!!block &&
// Hide on invalid blocks.
block.isValid &&
// 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');
return _canConvert;
}, [clientIds, rootClientId]);
const {
@@ -336,9 +337,11 @@ function ReusableBlockConvertButton({
const onConvert = (0,external_wp_element_namespaceObject.useCallback)(async function (reusableBlockTitle) {
try {
await convertBlocksToReusable(clientIds, reusableBlockTitle, syncType);
createSuccessNotice(!syncType ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: the name the user has given to the pattern.
(0,external_wp_i18n_namespaceObject.__)('Synced Pattern created: %s'), reusableBlockTitle) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: the name the user has given to the pattern.
(0,external_wp_i18n_namespaceObject.__)('Unsynced Pattern created: %s'), reusableBlockTitle), {
createSuccessNotice(!syncType ? (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: the name the user has given to the pattern.
(0,external_wp_i18n_namespaceObject.__)('Synced pattern created: %s'), reusableBlockTitle) : (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: the name the user has given to the pattern.
(0,external_wp_i18n_namespaceObject.__)('Unsynced pattern created: %s'), reusableBlockTitle), {
type: 'snackbar',
id: 'convert-to-reusable-block-success'
});
@@ -349,14 +352,10 @@ function ReusableBlockConvertButton({
});
}
}, [convertBlocksToReusable, clientIds, syncType, createSuccessNotice, createErrorNotice]);
if (!canConvert) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockSettingsMenuControls, null, ({
onClose
}) => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
icon: library_symbol,
onClick: () => setIsModalOpen(true)
}, showRenameHint ? (0,external_wp_i18n_namespaceObject.__)('Create pattern/reusable block') : (0,external_wp_i18n_namespaceObject.__)('Create pattern')), isModalOpen && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
@@ -400,14 +399,13 @@ function ReusableBlockConvertButton({
}, (0,external_wp_i18n_namespaceObject.__)('Cancel')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
type: "submit"
}, (0,external_wp_i18n_namespaceObject.__)('Create'))))))));
}, (0,external_wp_i18n_namespaceObject.__)('Create')))))));
}
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/reusable-blocks/build-module/components/reusable-blocks-menu-items/reusable-blocks-manage-button.js
/**
* WordPress dependencies
*/
@@ -418,12 +416,11 @@ var external_wp_url_namespaceObject = window["wp"]["url"];
/**
* Internal dependencies
*/
function ReusableBlocksManageButton({
clientId
}) {
@@ -443,9 +440,7 @@ function ReusableBlocksManageButton({
canUser
} = select(external_wp_coreData_namespaceObject.store);
const reusableBlock = getBlock(clientId);
const isBlockTheme = getSettings().__unstableIsBlockBasedTheme;
return {
canRemove: canRemoveBlock(clientId),
isVisible: !!reusableBlock && (0,external_wp_blocks_namespaceObject.isReusableBlock)(reusableBlock) && !!canUser('update', 'blocks', reusableBlock.attributes.ref),
@@ -463,23 +458,19 @@ function ReusableBlocksManageButton({
const {
__experimentalConvertBlockToStatic: convertBlockToStatic
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
if (!isVisible) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockSettingsMenuControls, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
href: managePatternsUrl
}, (0,external_wp_i18n_namespaceObject.__)('Manage patterns')), canRemove && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => convertBlockToStatic(clientId)
}, innerBlockCount > 1 ? (0,external_wp_i18n_namespaceObject.__)('Detach patterns') : (0,external_wp_i18n_namespaceObject.__)('Detach pattern')));
}
/* harmony default export */ var reusable_blocks_manage_button = (ReusableBlocksManageButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/reusable-blocks/build-module/components/reusable-blocks-menu-items/index.js
/**
* WordPress dependencies
*/
@@ -490,17 +481,19 @@ function ReusableBlocksManageButton({
*/
function ReusableBlocksMenuItems({
rootClientId
}) {
const clientIds = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).getSelectedBlockClientIds(), []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(ReusableBlockConvertButton, {
clientIds: clientIds,
rootClientId: rootClientId
}), clientIds.length === 1 && (0,external_wp_element_namespaceObject.createElement)(reusable_blocks_manage_button, {
clientId: clientIds[0]
}));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockSettingsMenuControls, null, ({
onClose,
selectedClientIds
}) => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(ReusableBlockConvertButton, {
clientIds: selectedClientIds,
rootClientId: rootClientId,
onClose: onClose
}), selectedClientIds.length === 1 && (0,external_wp_element_namespaceObject.createElement)(reusable_blocks_manage_button, {
clientId: selectedClientIds[0]
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/reusable-blocks/build-module/components/index.js
File diff suppressed because one or more lines are too long
+461 -952
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+6 -11
View File
@@ -39,7 +39,7 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"privateApis": function() { return /* reexport */ privateApis; }
privateApis: function() { return /* reexport */ privateApis; }
});
;// CONCATENATED MODULE: external ["wp","element"]
@@ -856,45 +856,41 @@ var external_wp_url_namespaceObject = window["wp"]["url"];
* External dependencies
*/
/**
* WordPress dependencies
*/
const history_history = createBrowserHistory();
const originalHistoryPush = history_history.push;
const originalHistoryReplace = history_history.replace;
function push(params, state) {
const currentArgs = (0,external_wp_url_namespaceObject.getQueryArgs)(window.location.href);
const currentUrlWithoutArgs = (0,external_wp_url_namespaceObject.removeQueryArgs)(window.location.href, ...Object.keys(currentArgs));
const newUrl = (0,external_wp_url_namespaceObject.addQueryArgs)(currentUrlWithoutArgs, params);
return originalHistoryPush.call(history_history, newUrl, state);
}
function replace(params, state) {
const currentArgs = (0,external_wp_url_namespaceObject.getQueryArgs)(window.location.href);
const currentUrlWithoutArgs = (0,external_wp_url_namespaceObject.removeQueryArgs)(window.location.href, ...Object.keys(currentArgs));
const newUrl = (0,external_wp_url_namespaceObject.addQueryArgs)(currentUrlWithoutArgs, params);
return originalHistoryReplace.call(history_history, newUrl, state);
}
history_history.push = push;
history_history.replace = replace;
/* harmony default export */ var build_module_history = (history_history);
;// CONCATENATED MODULE: ./node_modules/@wordpress/router/build-module/router.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const RoutesContext = (0,external_wp_element_namespaceObject.createContext)();
const HistoryContext = (0,external_wp_element_namespaceObject.createContext)();
function useLocation() {
@@ -903,14 +899,13 @@ function useLocation() {
function useHistory() {
return (0,external_wp_element_namespaceObject.useContext)(HistoryContext);
}
function getLocationWithParams(location) {
const searchParams = new URLSearchParams(location.search);
return { ...location,
return {
...location,
params: Object.fromEntries(searchParams.entries())
};
}
function RouterProvider({
children
}) {
@@ -939,7 +934,7 @@ var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
const {
lock,
unlock
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.', '@wordpress/router');
} = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.', '@wordpress/router');
;// CONCATENATED MODULE: ./node_modules/@wordpress/router/build-module/private-apis.js
/**
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
!function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(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,{privateApis:function(){return A}});var n,r=window.wp.element;function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o.apply(this,arguments)}!function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"}(n||(n={}));var a=function(e){return e};var u="beforeunload",i="popstate";function c(e){e.preventDefault(),e.returnValue=""}function s(){var e=[];return{get length(){return e.length},push:function(t){return e.push(t),function(){e=e.filter((function(e){return e!==t}))}},call:function(t){e.forEach((function(e){return e&&e(t)}))}}}function l(){return Math.random().toString(36).substr(2,8)}function f(e){var t=e.pathname,n=void 0===t?"/":t,r=e.search,o=void 0===r?"":r,a=e.hash,u=void 0===a?"":a;return o&&"?"!==o&&(n+="?"===o.charAt(0)?o:"?"+o),u&&"#"!==u&&(n+="#"===u.charAt(0)?u:"#"+u),n}function h(e){var t={};if(e){var n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));var r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}var p=window.wp.url;const d=function(e){void 0===e&&(e={});var t=e.window,r=void 0===t?document.defaultView:t,p=r.history;function d(){var e=r.location,t=e.pathname,n=e.search,o=e.hash,u=p.state||{};return[u.idx,a({pathname:t,search:n,hash:o,state:u.usr||null,key:u.key||"default"})]}var v=null;r.addEventListener(i,(function(){if(v)P.call(v),v=null;else{var e=n.Pop,t=d(),r=t[0],o=t[1];if(P.length){if(null!=r){var a=w-r;a&&(v={action:e,location:o,retry:function(){x(-1*a)}},x(a))}}else j(e)}}));var y=n.Pop,g=d(),w=g[0],b=g[1],m=s(),P=s();function O(e){return"string"==typeof e?e:f(e)}function k(e,t){return void 0===t&&(t=null),a(o({pathname:b.pathname,hash:"",search:""},"string"==typeof e?h(e):e,{state:t,key:l()}))}function A(e,t){return[{usr:e.state,key:e.key,idx:t},O(e)]}function S(e,t,n){return!P.length||(P.call({action:e,location:t,retry:n}),!1)}function j(e){y=e;var t=d();w=t[0],b=t[1],m.call({action:y,location:b})}function x(e){p.go(e)}null==w&&(w=0,p.replaceState(o({},p.state,{idx:w}),""));var E={get action(){return y},get location(){return b},createHref:O,push:function e(t,o){var a=n.Push,u=k(t,o);if(S(a,u,(function(){e(t,o)}))){var i=A(u,w+1),c=i[0],s=i[1];try{p.pushState(c,"",s)}catch(e){r.location.assign(s)}j(a)}},replace:function e(t,r){var o=n.Replace,a=k(t,r);if(S(o,a,(function(){e(t,r)}))){var u=A(a,w),i=u[0],c=u[1];p.replaceState(i,"",c),j(o)}},go:x,back:function(){x(-1)},forward:function(){x(1)},listen:function(e){return m.push(e)},block:function(e){var t=P.push(e);return 1===P.length&&r.addEventListener(u,c),function(){t(),P.length||r.removeEventListener(u,c)}}};return E}(),v=d.push,y=d.replace;d.push=function(e,t){const n=(0,p.getQueryArgs)(window.location.href),r=(0,p.removeQueryArgs)(window.location.href,...Object.keys(n)),o=(0,p.addQueryArgs)(r,e);return v.call(d,o,t)},d.replace=function(e,t){const n=(0,p.getQueryArgs)(window.location.href),r=(0,p.removeQueryArgs)(window.location.href,...Object.keys(n)),o=(0,p.addQueryArgs)(r,e);return y.call(d,o,t)};var g=d;const w=(0,r.createContext)(),b=(0,r.createContext)();function m(e){const t=new URLSearchParams(e.search);return{...e,params:Object.fromEntries(t.entries())}}var P=window.wp.privateApis;const{lock:O,unlock:k}=(0,P.__dangerousOptInToUnstableAPIsOnlyForCoreModules)("I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.","@wordpress/router"),A={};O(A,{useHistory:function(){return(0,r.useContext)(b)},useLocation:function(){return(0,r.useContext)(w)},RouterProvider:function({children:e}){const[t,n]=(0,r.useState)((()=>m(g.location)));return(0,r.useEffect)((()=>g.listen((({location:e})=>{n(m(e))}))),[]),(0,r.createElement)(b.Provider,{value:g},(0,r.createElement)(w.Provider,{value:t},e))}}),(window.wp=window.wp||{}).router=t}();
!function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(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,{privateApis:function(){return A}});var n,r=window.wp.element;function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o.apply(this,arguments)}!function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"}(n||(n={}));var a=function(e){return e};var u="beforeunload",i="popstate";function c(e){e.preventDefault(),e.returnValue=""}function s(){var e=[];return{get length(){return e.length},push:function(t){return e.push(t),function(){e=e.filter((function(e){return e!==t}))}},call:function(t){e.forEach((function(e){return e&&e(t)}))}}}function l(){return Math.random().toString(36).substr(2,8)}function f(e){var t=e.pathname,n=void 0===t?"/":t,r=e.search,o=void 0===r?"":r,a=e.hash,u=void 0===a?"":a;return o&&"?"!==o&&(n+="?"===o.charAt(0)?o:"?"+o),u&&"#"!==u&&(n+="#"===u.charAt(0)?u:"#"+u),n}function h(e){var t={};if(e){var n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));var r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}var p=window.wp.url;const d=function(e){void 0===e&&(e={});var t=e.window,r=void 0===t?document.defaultView:t,p=r.history;function d(){var e=r.location,t=e.pathname,n=e.search,o=e.hash,u=p.state||{};return[u.idx,a({pathname:t,search:n,hash:o,state:u.usr||null,key:u.key||"default"})]}var v=null;r.addEventListener(i,(function(){if(v)P.call(v),v=null;else{var e=n.Pop,t=d(),r=t[0],o=t[1];if(P.length){if(null!=r){var a=w-r;a&&(v={action:e,location:o,retry:function(){x(-1*a)}},x(a))}}else j(e)}}));var y=n.Pop,g=d(),w=g[0],b=g[1],m=s(),P=s();function O(e){return"string"==typeof e?e:f(e)}function k(e,t){return void 0===t&&(t=null),a(o({pathname:b.pathname,hash:"",search:""},"string"==typeof e?h(e):e,{state:t,key:l()}))}function A(e,t){return[{usr:e.state,key:e.key,idx:t},O(e)]}function S(e,t,n){return!P.length||(P.call({action:e,location:t,retry:n}),!1)}function j(e){y=e;var t=d();w=t[0],b=t[1],m.call({action:y,location:b})}function x(e){p.go(e)}null==w&&(w=0,p.replaceState(o({},p.state,{idx:w}),""));var E={get action(){return y},get location(){return b},createHref:O,push:function e(t,o){var a=n.Push,u=k(t,o);if(S(a,u,(function(){e(t,o)}))){var i=A(u,w+1),c=i[0],s=i[1];try{p.pushState(c,"",s)}catch(e){r.location.assign(s)}j(a)}},replace:function e(t,r){var o=n.Replace,a=k(t,r);if(S(o,a,(function(){e(t,r)}))){var u=A(a,w),i=u[0],c=u[1];p.replaceState(i,"",c),j(o)}},go:x,back:function(){x(-1)},forward:function(){x(1)},listen:function(e){return m.push(e)},block:function(e){var t=P.push(e);return 1===P.length&&r.addEventListener(u,c),function(){t(),P.length||r.removeEventListener(u,c)}}};return E}(),v=d.push,y=d.replace;d.push=function(e,t){const n=(0,p.getQueryArgs)(window.location.href),r=(0,p.removeQueryArgs)(window.location.href,...Object.keys(n)),o=(0,p.addQueryArgs)(r,e);return v.call(d,o,t)},d.replace=function(e,t){const n=(0,p.getQueryArgs)(window.location.href),r=(0,p.removeQueryArgs)(window.location.href,...Object.keys(n)),o=(0,p.addQueryArgs)(r,e);return y.call(d,o,t)};var g=d;const w=(0,r.createContext)(),b=(0,r.createContext)();function m(e){const t=new URLSearchParams(e.search);return{...e,params:Object.fromEntries(t.entries())}}var P=window.wp.privateApis;const{lock:O,unlock:k}=(0,P.__dangerousOptInToUnstableAPIsOnlyForCoreModules)("I know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.","@wordpress/router"),A={};O(A,{useHistory:function(){return(0,r.useContext)(b)},useLocation:function(){return(0,r.useContext)(w)},RouterProvider:function({children:e}){const[t,n]=(0,r.useState)((()=>m(g.location)));return(0,r.useEffect)((()=>g.listen((({location:e})=>{n(m(e))}))),[]),(0,r.createElement)(b.Provider,{value:g},(0,r.createElement)(w.Provider,{value:t},e))}}),(window.wp=window.wp||{}).router=t}();
+21 -35
View File
@@ -169,11 +169,11 @@ var external_wp_components_namespaceObject = window["wp"]["components"];
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/server-side-render/build-module/server-side-render.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
@@ -184,7 +184,6 @@ var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
const EMPTY_OBJECT = {};
function rendererPath(block, attributes = null, urlQueryArgs = {}) {
return (0,external_wp_url_namespaceObject.addQueryArgs)(`/wp/v2/block-renderer/${block}`, {
@@ -214,11 +213,11 @@ function removeBlockSupportAttributes(attributes) {
typography,
...restStyles
} = attributes?.style || EMPTY_OBJECT;
return { ...restAttributes,
return {
...restAttributes,
style: restStyles
};
}
function DefaultEmptyResponsePlaceholder({
className
}) {
@@ -226,18 +225,17 @@ function DefaultEmptyResponsePlaceholder({
className: className
}, (0,external_wp_i18n_namespaceObject.__)('Block rendered as empty.'));
}
function DefaultErrorResponsePlaceholder({
response,
className
}) {
const errorMessage = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: error message describing the problem
const errorMessage = (0,external_wp_i18n_namespaceObject.sprintf)(
// translators: %s: error message describing the problem
(0,external_wp_i18n_namespaceObject.__)('Error loading block: %s'), response.errorMsg);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, {
className: className
}, errorMessage);
}
function DefaultLoadingResponsePlaceholder({
children,
showLoader
@@ -260,7 +258,6 @@ function DefaultLoadingResponsePlaceholder({
}
}, children));
}
function ServerSideRender(props) {
const {
attributes,
@@ -279,32 +276,28 @@ function ServerSideRender(props) {
const [response, setResponse] = (0,external_wp_element_namespaceObject.useState)(null);
const prevProps = (0,external_wp_compose_namespaceObject.usePrevious)(props);
const [isLoading, setIsLoading] = (0,external_wp_element_namespaceObject.useState)(false);
function fetchData() {
var _sanitizedAttributes, _sanitizedAttributes2;
if (!isMountedRef.current) {
return;
}
setIsLoading(true);
let sanitizedAttributes = attributes && (0,external_wp_blocks_namespaceObject.__experimentalSanitizeBlockAttributes)(block, attributes);
if (skipBlockSupportAttributes) {
sanitizedAttributes = removeBlockSupportAttributes(sanitizedAttributes);
} // If httpMethod is 'POST', send the attributes in the request body instead of the URL.
}
// If httpMethod is 'POST', send the attributes in the request body instead of the URL.
// This allows sending a larger attributes object than in a GET request, where the attributes are in the URL.
const isPostRequest = 'POST' === httpMethod;
const urlAttributes = isPostRequest ? null : (_sanitizedAttributes = sanitizedAttributes) !== null && _sanitizedAttributes !== void 0 ? _sanitizedAttributes : null;
const path = rendererPath(block, urlAttributes, urlQueryArgs);
const data = isPostRequest ? {
attributes: (_sanitizedAttributes2 = sanitizedAttributes) !== null && _sanitizedAttributes2 !== void 0 ? _sanitizedAttributes2 : null
} : null; // Store the latest fetch request so that when we process it, we can
// check if it is the current request, to avoid race conditions on slow networks.
} : null;
// Store the latest fetch request so that when we process it, we can
// check if it is the current request, to avoid race conditions on slow networks.
const fetchRequest = fetchRequestRef.current = external_wp_apiFetch_default()({
path,
data,
@@ -327,10 +320,10 @@ function ServerSideRender(props) {
});
return fetchRequest;
}
const debouncedFetchData = (0,external_wp_compose_namespaceObject.useDebounce)(fetchData, 500);
const debouncedFetchData = (0,external_wp_compose_namespaceObject.useDebounce)(fetchData, 500); // When the component unmounts, set isMountedRef to false. This will
// When the component unmounts, set isMountedRef to false. This will
// let the async fetch callbacks know when to stop.
(0,external_wp_element_namespaceObject.useEffect)(() => () => {
isMountedRef.current = false;
}, []);
@@ -343,17 +336,16 @@ function ServerSideRender(props) {
debouncedFetchData();
}
});
/**
* Effect to handle showing the loading placeholder.
* Show it only if there is no previous response or
* the request takes more than one second.
*/
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isLoading) {
return;
}
const timeout = setTimeout(() => {
setShowLoader(true);
}, 1000);
@@ -362,27 +354,25 @@ function ServerSideRender(props) {
const hasResponse = !!response;
const hasEmptyResponse = response === '';
const hasError = response?.error;
if (isLoading) {
return (0,external_wp_element_namespaceObject.createElement)(LoadingResponsePlaceholder, { ...props,
return (0,external_wp_element_namespaceObject.createElement)(LoadingResponsePlaceholder, {
...props,
showLoader: showLoader
}, hasResponse && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, {
className: className
}, response));
}
if (hasEmptyResponse || !hasResponse) {
return (0,external_wp_element_namespaceObject.createElement)(EmptyResponsePlaceholder, { ...props
return (0,external_wp_element_namespaceObject.createElement)(EmptyResponsePlaceholder, {
...props
});
}
if (hasError) {
return (0,external_wp_element_namespaceObject.createElement)(ErrorResponsePlaceholder, {
response: response,
...props
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, {
className: className
}, response);
@@ -390,12 +380,12 @@ function ServerSideRender(props) {
;// CONCATENATED MODULE: ./node_modules/@wordpress/server-side-render/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -404,27 +394,24 @@ function ServerSideRender(props) {
/**
* Constants
*/
const build_module_EMPTY_OBJECT = {};
const ExportedServerSideRender = (0,external_wp_data_namespaceObject.withSelect)(select => {
// FIXME: @wordpress/server-side-render should not depend on @wordpress/editor.
// It is used by blocks that can be loaded into a *non-post* block editor.
// eslint-disable-next-line @wordpress/data-no-store-string-literals
const coreEditorSelect = select('core/editor');
if (coreEditorSelect) {
const currentPostId = coreEditorSelect.getCurrentPostId(); // For templates and template parts we use a custom ID format.
const currentPostId = coreEditorSelect.getCurrentPostId();
// For templates and template parts we use a custom ID format.
// Since they aren't real posts, we don't want to use their ID
// for server-side rendering. Since they use a string based ID,
// we can assume real post IDs are numbers.
if (currentPostId && typeof currentPostId === 'number') {
return {
currentPostId
};
}
}
return build_module_EMPTY_OBJECT;
})(({
urlQueryArgs = build_module_EMPTY_OBJECT,
@@ -435,7 +422,6 @@ const ExportedServerSideRender = (0,external_wp_data_namespaceObject.withSelect)
if (!currentPostId) {
return urlQueryArgs;
}
return {
post_id: currentPostId,
...urlQueryArgs
+40 -42
View File
@@ -198,6 +198,7 @@ function memize(fn, options) {
* External dependencies
*/
/**
* Shortcode attributes object.
*
@@ -236,40 +237,38 @@ function memize(fn, options) {
*
* @return {WPShortcodeMatch | undefined} Matched information.
*/
function next(tag, text, index = 0) {
const re = regexp(tag);
re.lastIndex = index;
const match = re.exec(text);
if (!match) {
return;
} // If we matched an escaped shortcode, try again.
}
// If we matched an escaped shortcode, try again.
if ('[' === match[1] && ']' === match[7]) {
return next(tag, text, re.lastIndex);
}
const result = {
index: match.index,
content: match[0],
shortcode: fromMatch(match)
}; // If we matched a leading `[`, strip it from the match and increment the
// index accordingly.
};
// If we matched a leading `[`, strip it from the match and increment the
// index accordingly.
if (match[1]) {
result.content = result.content.slice(1);
result.index++;
} // If we matched a trailing `]`, strip it from the match.
}
// If we matched a trailing `]`, strip it from the match.
if (match[7]) {
result.content = result.content.slice(0, -1);
}
return result;
}
/**
* Replace matching shortcodes in a block of text.
*
@@ -280,22 +279,23 @@ function next(tag, text, index = 0) {
*
* @return {string} Text with shortcodes replaced.
*/
function replace(tag, text, callback) {
return text.replace(regexp(tag), function (match, left, $3, attrs, slash, content, closing, right) {
// If both extra brackets exist, the shortcode has been properly
// escaped.
if (left === '[' && right === ']') {
return match;
} // Create the match object and pass it through the callback.
}
// Create the match object and pass it through the callback.
const result = callback(fromMatch(arguments));
const result = callback(fromMatch(arguments)); // Make sure to return any of the extra brackets if they weren't used to
// Make sure to return any of the extra brackets if they weren't used to
// escape the shortcode.
return result || result === '' ? left + result + right : match;
});
}
/**
* Generate a string from shortcode parameters.
*
@@ -309,10 +309,10 @@ function replace(tag, text, callback) {
*
* @return {string} String representation of the shortcode.
*/
function string(options) {
return new shortcode(options).string();
}
/**
* Generate a RegExp to identify a shortcode.
*
@@ -333,10 +333,10 @@ function string(options) {
*
* @return {RegExp} Shortcode RegExp.
*/
function regexp(tag) {
return new RegExp('\\[(\\[?)(' + tag + ')(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)', 'g');
}
/**
* Parse shortcode attributes.
*
@@ -354,10 +354,11 @@ function regexp(tag) {
*
* @return {WPShortcodeAttrs} Parsed shortcode attributes.
*/
const attrs = memize(text => {
const named = {};
const numeric = []; // This regular expression is reused from `shortcode_parse_atts()` in
const numeric = [];
// This regular expression is reused from `shortcode_parse_atts()` in
// `wp-includes/shortcodes.php`.
//
// Capture groups:
@@ -371,12 +372,13 @@ const attrs = memize(text => {
// 7. A numeric attribute in double quotes.
// 8. A numeric attribute in single quotes.
// 9. An unquoted numeric attribute.
const pattern = /([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*'([^']*)'(?:\s|$)|([\w-]+)\s*=\s*([^\s'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|'([^']*)'(?:\s|$)|(\S+)(?:\s|$)/g;
const pattern = /([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*'([^']*)'(?:\s|$)|([\w-]+)\s*=\s*([^\s'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|'([^']*)'(?:\s|$)|(\S+)(?:\s|$)/g; // Map zero-width spaces to actual spaces.
// Map zero-width spaces to actual spaces.
text = text.replace(/[\u00a0\u200b]/g, ' ');
let match; // Match and normalize attributes.
let match;
// Match and normalize attributes.
while (match = pattern.exec(text)) {
if (match[1]) {
named[match[1].toLowerCase()] = match[2];
@@ -392,12 +394,12 @@ const attrs = memize(text => {
numeric.push(match[9]);
}
}
return {
named,
numeric
};
});
/**
* Generate a Shortcode Object from a RegExp match.
*
@@ -409,10 +411,8 @@ const attrs = memize(text => {
*
* @return {WPShortcode} Shortcode instance.
*/
function fromMatch(match) {
let type;
if (match[4]) {
type = 'self-closing';
} else if (match[6]) {
@@ -420,7 +420,6 @@ function fromMatch(match) {
} else {
type = 'single';
}
return new shortcode({
tag: match[2],
attrs: match[3],
@@ -428,6 +427,7 @@ function fromMatch(match) {
content: match[5]
});
}
/**
* Creates a shortcode instance.
*
@@ -440,7 +440,6 @@ function fromMatch(match) {
*
* @return {WPShortcode} Shortcode instance.
*/
const shortcode = Object.assign(function (options) {
const {
tag,
@@ -452,23 +451,25 @@ const shortcode = Object.assign(function (options) {
tag,
type,
content
}); // Ensure we have a correctly formatted `attrs` object.
});
// Ensure we have a correctly formatted `attrs` object.
this.attrs = {
named: {},
numeric: []
};
if (!attributes) {
return;
}
const attributeTypes = ['named', 'numeric'];
const attributeTypes = ['named', 'numeric']; // Parse a string of attributes.
// Parse a string of attributes.
if (typeof attributes === 'string') {
this.attrs = attrs(attributes); // Identify a correctly formatted `attrs` object.
this.attrs = attrs(attributes);
// Identify a correctly formatted `attrs` object.
} else if (attributes.length === attributeTypes.length && attributeTypes.every((t, key) => t === attributes[key])) {
this.attrs = attributes; // Handle a flat object of attributes.
this.attrs = attributes;
// Handle a flat object of attributes.
} else {
Object.entries(attributes).forEach(([key, value]) => {
this.set(key, value);
@@ -496,7 +497,6 @@ Object.assign(shortcode.prototype, {
get(attr) {
return this.attrs[typeof attr === 'number' ? 'numeric' : 'named'][attr];
},
/**
* Set a shortcode attribute.
*
@@ -512,7 +512,6 @@ Object.assign(shortcode.prototype, {
this.attrs[typeof attr === 'number' ? 'numeric' : 'named'][attr] = value;
return this;
},
/**
* Transform the shortcode into a string.
*
@@ -529,26 +528,25 @@ Object.assign(shortcode.prototype, {
});
Object.entries(this.attrs.named).forEach(([name, value]) => {
text += ' ' + name + '="' + value + '"';
}); // If the tag is marked as `single` or `self-closing`, close the tag and
// ignore any additional content.
});
// If the tag is marked as `single` or `self-closing`, close the tag and
// ignore any additional content.
if ('single' === this.type) {
return text + ']';
} else if ('self-closing' === this.type) {
return text + ' /]';
} // Complete the opening tag.
}
// Complete the opening tag.
text += ']';
if (this.content) {
text += this.content;
} // Add the closing tag.
}
// Add the closing tag.
return text + '[/' + this.tag + ']';
}
});
/* harmony default export */ var build_module = (shortcode);
+592 -35
View File
@@ -39,12 +39,479 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"compileCSS": function() { return /* binding */ compileCSS; },
"getCSSRules": function() { return /* binding */ getCSSRules; }
compileCSS: function() { return /* binding */ compileCSS; },
getCSSRules: function() { return /* binding */ getCSSRules; }
});
;// CONCATENATED MODULE: external "lodash"
var external_lodash_namespaceObject = window["lodash"];
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.mjs
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
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 */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
function __runInitializers(thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
function __propKey(x) {
return typeof x === "symbol" ? x : "".concat(x);
};
function __setFunctionName(f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
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;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __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); }); }; }
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); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function __classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(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;
if (async) {
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 (typeof dispose !== "function") throw new TypeError("Object not disposable.");
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function __disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
function next() {
while (env.stack.length) {
var rec = 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(); });
}
catch (e) {
fail(e);
}
}
if (env.hasError) throw env.error;
}
return next();
}
/* harmony default export */ var tslib_es6 = ({
__extends,
__assign,
__rest,
__decorate,
__param,
__metadata,
__awaiter,
__generator,
__createBinding,
__exportStar,
__values,
__read,
__spread,
__spreadArrays,
__spreadArray,
__await,
__asyncGenerator,
__asyncDelegator,
__asyncValues,
__makeTemplateObject,
__importStar,
__importDefault,
__classPrivateFieldGet,
__classPrivateFieldSet,
__classPrivateFieldIn,
__addDisposableResource,
__disposeResources,
});
;// CONCATENATED MODULE: ./node_modules/lower-case/dist.es2015/index.js
/**
* Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
*/
var SUPPORTED_LOCALE = {
tr: {
regexp: /\u0130|\u0049|\u0049\u0307/g,
map: {
İ: "\u0069",
I: "\u0131",
İ: "\u0069",
},
},
az: {
regexp: /\u0130/g,
map: {
İ: "\u0069",
I: "\u0131",
İ: "\u0069",
},
},
lt: {
regexp: /\u0049|\u004A|\u012E|\u00CC|\u00CD|\u0128/g,
map: {
I: "\u0069\u0307",
J: "\u006A\u0307",
Į: "\u012F\u0307",
Ì: "\u0069\u0307\u0300",
Í: "\u0069\u0307\u0301",
Ĩ: "\u0069\u0307\u0303",
},
},
};
/**
* Localized lower case.
*/
function localeLowerCase(str, locale) {
var lang = SUPPORTED_LOCALE[locale.toLowerCase()];
if (lang)
return lowerCase(str.replace(lang.regexp, function (m) { return lang.map[m]; }));
return lowerCase(str);
}
/**
* Lower case as a function.
*/
function lowerCase(str) {
return str.toLowerCase();
}
;// CONCATENATED MODULE: ./node_modules/no-case/dist.es2015/index.js
// Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case").
var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
// Remove all non-word characters.
var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
/**
* Normalize the string into something other libraries can manipulate easier.
*/
function noCase(input, options) {
if (options === void 0) { options = {}; }
var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
var start = 0;
var end = result.length;
// Trim the delimiter from around the output string.
while (result.charAt(start) === "\0")
start++;
while (result.charAt(end - 1) === "\0")
end--;
// Transform each token independently.
return result.slice(start, end).split("\0").map(transform).join(delimiter);
}
/**
* Replace `re` in the input string with the replacement value.
*/
function replace(input, re, value) {
if (re instanceof RegExp)
return input.replace(re, value);
return re.reduce(function (input, re) { return input.replace(re, value); }, input);
}
;// CONCATENATED MODULE: ./node_modules/dot-case/dist.es2015/index.js
function dotCase(input, options) {
if (options === void 0) { options = {}; }
return noCase(input, __assign({ delimiter: "." }, options));
}
;// CONCATENATED MODULE: ./node_modules/param-case/dist.es2015/index.js
function paramCase(input, options) {
if (options === void 0) { options = {}; }
return dotCase(input, __assign({ delimiter: "-" }, options));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/constants.js
const VARIABLE_REFERENCE_PREFIX = 'var:';
const VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE = '|';
@@ -55,11 +522,29 @@ const VARIABLE_PATH_SEPARATOR_TOKEN_STYLE = '--';
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Helper util to return a value from a certain path of the object.
* Path is specified as an array of properties, like `[ 'x', 'y' ]`.
*
* @param object Input object.
* @param path Path to the object property.
* @return Value of the object property at the specified path.
*/
const getStyleValueByPath = (object, path) => {
let value = object;
path.forEach(fieldName => {
value = value?.[fieldName];
});
return value;
};
/**
* Returns a JSON representation of the generated CSS rules.
*
@@ -70,15 +555,15 @@ const VARIABLE_PATH_SEPARATOR_TOKEN_STYLE = '--';
*
* @return GeneratedCSSRule[] CSS rules.
*/
function generateRule(style, options, path, ruleKey) {
const styleValue = (0,external_lodash_namespaceObject.get)(style, path);
const styleValue = getStyleValueByPath(style, path);
return styleValue ? [{
selector: options?.selector,
key: ruleKey,
value: getCSSVarFromStyleValue(styleValue)
}] : [];
}
/**
* Returns a JSON representation of the generated CSS rules taking into account box model properties, top, right, bottom, left.
*
@@ -90,16 +575,12 @@ function generateRule(style, options, path, ruleKey) {
*
* @return GeneratedCSSRule[] CSS rules.
*/
function generateBoxRules(style, options, path, ruleKeys, individualProperties = ['top', 'right', 'bottom', 'left']) {
const boxStyle = (0,external_lodash_namespaceObject.get)(style, path);
const boxStyle = getStyleValueByPath(style, path);
if (!boxStyle) {
return [];
}
const rules = [];
if (typeof boxStyle === 'string') {
rules.push({
selector: options?.selector,
@@ -108,8 +589,7 @@ function generateBoxRules(style, options, path, ruleKeys, individualProperties =
});
} else {
const sideRules = individualProperties.reduce((acc, side) => {
const value = getCSSVarFromStyleValue((0,external_lodash_namespaceObject.get)(boxStyle, [side]));
const value = getCSSVarFromStyleValue(getStyleValueByPath(boxStyle, [side]));
if (value) {
acc.push({
selector: options?.selector,
@@ -117,14 +597,13 @@ function generateBoxRules(style, options, path, ruleKeys, individualProperties =
value
});
}
return acc;
}, []);
rules.push(...sideRules);
}
return rules;
}
/**
* Returns a CSS var value from incoming style value following the pattern `var:description|context|slug`.
*
@@ -132,15 +611,23 @@ function generateBoxRules(style, options, path, ruleKeys, individualProperties =
*
* @return string A CSS var value.
*/
function getCSSVarFromStyleValue(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 => (0,external_lodash_namespaceObject.kebabCase)(presetVariable)).join(VARIABLE_PATH_SEPARATOR_TOKEN_STYLE);
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,
// fooBar => foo-bar, 3Bar => 3-bar
/([0-9])([a-z])/g,
// 3bar => 3-bar
/([A-Za-z])([0-9])/g,
// Foo3 => foo-3, foo3 => foo-3
/([A-Z])([A-Z][a-z])/g // FOOBar => foo-bar
]
})).join(VARIABLE_PATH_SEPARATOR_TOKEN_STYLE);
return `var(--wp--${variable})`;
}
return styleValue;
}
/**
* Capitalizes the first letter in a string.
*
@@ -148,11 +635,11 @@ function getCSSVarFromStyleValue(styleValue) {
*
* @return String with the first letter capitalized.
*/
function upperFirst(string) {
const [firstLetter, ...rest] = string;
return firstLetter.toUpperCase() + rest.join('');
}
/**
* Converts an array of strings into a camelCase string.
*
@@ -160,17 +647,39 @@ function upperFirst(string) {
*
* @return camelCase string.
*/
function camelCaseJoin(strings) {
const [firstItem, ...rest] = strings;
return firstItem.toLowerCase() + rest.map(upperFirst).join('');
}
/**
* Safely decodes a URI with `decodeURI`. Returns the URI unmodified if
* `decodeURI` throws an error.
*
* @param {string} uri URI to decode.
*
* @example
* ```js
* const badUri = safeDecodeURI( '%z' ); // does not throw an Error, simply returns '%z'
* ```
*
* @return {string} Decoded URI if possible.
*/
function safeDecodeURI(uri) {
try {
return decodeURI(uri);
} catch (uriError) {
return uri;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/border/index.js
/**
* Internal dependencies
*/
/**
* Creates a function for generating CSS rules when the style path is the same as the camelCase CSS property used in React.
*
@@ -178,10 +687,10 @@ function camelCaseJoin(strings) {
*
* @return A function that generates CSS rules.
*/
function createBorderGenerateFunction(path) {
return (style, options) => generateRule(style, options, path, camelCaseJoin(path));
}
/**
* Creates a function for generating border-{top,bottom,left,right}-{color,style,width} CSS rules.
*
@@ -189,8 +698,6 @@ function createBorderGenerateFunction(path) {
*
* @return A function that generates CSS rules.
*/
function createBorderEdgeGenerateFunction(edge) {
return (style, options) => {
return ['color', 'style', 'width'].flatMap(key => {
@@ -199,7 +706,6 @@ function createBorderEdgeGenerateFunction(edge) {
});
};
}
const color = {
name: 'color',
generate: createBorderGenerateFunction(['border', 'color'])
@@ -244,6 +750,7 @@ const borderLeft = {
* Internal dependencies
*/
const background = {
name: 'background',
generate: (style, options) => {
@@ -257,6 +764,7 @@ const background = {
* Internal dependencies
*/
const gradient = {
name: 'gradient',
generate: (style, options) => {
@@ -270,6 +778,7 @@ const gradient = {
* Internal dependencies
*/
const text_text = {
name: 'text',
generate: (style, options) => {
@@ -292,6 +801,7 @@ const text_text = {
* Internal dependencies
*/
const minHeight = {
name: 'minHeight',
generate: (style, options) => {
@@ -300,11 +810,49 @@ const minHeight = {
};
/* harmony default export */ var dimensions = ([minHeight]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/background/index.js
/**
* Internal dependencies
*/
const backgroundImage = {
name: 'backgroundImage',
generate: (style, options) => {
const _backgroundImage = style?.background?.backgroundImage;
const _backgroundSize = style?.background?.backgroundSize;
const styleRules = [];
if (!_backgroundImage) {
return styleRules;
}
if (_backgroundImage?.source === 'file' && _backgroundImage?.url) {
styleRules.push({
selector: options.selector,
key: 'backgroundImage',
// Passed `url` may already be encoded. To prevent double encoding, decodeURI is executed to revert to the original string.
value: `url( '${encodeURI(safeDecodeURI(_backgroundImage.url))}' )`
});
}
// If no background size is set, but an image is, default to cover.
if (!_backgroundSize) {
styleRules.push({
selector: options.selector,
key: 'backgroundSize',
value: 'cover'
});
}
return styleRules;
}
};
/* harmony default export */ var styles_background = ([backgroundImage]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/shadow/index.js
/**
* Internal dependencies
*/
const shadow = {
name: 'shadow',
generate: (style, options) => {
@@ -318,6 +866,7 @@ const shadow = {
* Internal dependencies
*/
const outline_color = {
name: 'color',
generate: (style, options, path = ['outline', 'color'], ruleKey = 'outlineColor') => {
@@ -349,6 +898,7 @@ const outline_width = {
* Internal dependencies
*/
const padding = {
name: 'padding',
generate: (style, options) => {
@@ -365,6 +915,7 @@ const padding = {
* Internal dependencies
*/
const margin = {
name: 'margin',
generate: (style, options) => {
@@ -389,6 +940,7 @@ const margin = {
* Internal dependencies
*/
const fontSize = {
name: 'fontSize',
generate: (style, options) => {
@@ -443,7 +995,13 @@ const textTransform = {
return generateRule(style, options, ['typography', 'textTransform'], 'textTransform');
}
};
/* harmony default export */ var typography = ([fontFamily, fontSize, fontStyle, fontWeight, letterSpacing, lineHeight, textColumns, textDecoration, textTransform]);
const writingMode = {
name: 'writingMode',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'writingMode'], 'writingMode');
}
};
/* harmony default export */ var typography = ([fontFamily, fontSize, fontStyle, fontWeight, letterSpacing, lineHeight, textColumns, textDecoration, textTransform, writingMode]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/index.js
/**
@@ -456,18 +1014,21 @@ const textTransform = {
const styleDefinitions = [...border, ...styles_color, ...dimensions, ...outline, ...spacing, ...typography, ...styles_shadow];
const styleDefinitions = [...border, ...styles_color, ...dimensions, ...outline, ...spacing, ...typography, ...styles_shadow, ...styles_background];
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Generates a stylesheet for a given style object and selector.
*
@@ -478,40 +1039,37 @@ const styleDefinitions = [...border, ...styles_color, ...dimensions, ...outline,
*
* @return A generated stylesheet or inline style declarations.
*/
function compileCSS(style, options = {}) {
const rules = getCSSRules(style, options); // If no selector is provided, treat generated rules as inline styles to be returned as a single string.
const rules = getCSSRules(style, options);
// If no selector is provided, treat generated rules as inline styles to be returned as a single string.
if (!options?.selector) {
const inlineRules = [];
rules.forEach(rule => {
inlineRules.push(`${(0,external_lodash_namespaceObject.kebabCase)(rule.key)}: ${rule.value};`);
inlineRules.push(`${paramCase(rule.key)}: ${rule.value};`);
});
return inlineRules.join(' ');
}
const groupedRules = rules.reduce((acc, rule) => {
const {
selector
} = rule;
if (!selector) {
return acc;
}
if (!acc[selector]) {
acc[selector] = [];
}
acc[selector].push(rule);
return acc;
}, {});
const selectorRules = Object.keys(groupedRules).reduce((acc, subSelector) => {
acc.push(`${subSelector} { ${groupedRules[subSelector].map(rule => `${(0,external_lodash_namespaceObject.kebabCase)(rule.key)}: ${rule.value};`).join(' ')} }`);
acc.push(`${subSelector} { ${groupedRules[subSelector].map(rule => `${paramCase(rule.key)}: ${rule.value};`).join(' ')} }`);
return acc;
}, []);
return selectorRules.join('\n');
}
/**
* Returns a JSON representation of the generated CSS rules.
*
@@ -522,7 +1080,6 @@ function compileCSS(style, options = {}) {
*
* @return A collection of objects containing the selector, if any, the CSS property key (camelcase) and parsed CSS value.
*/
function getCSSRules(style, options = {}) {
const rules = [];
styleDefinitions.forEach(definition => {
File diff suppressed because one or more lines are too long
+19 -40
View File
@@ -38,50 +38,46 @@ class TokenList {
* @param {string} initialValue Initial value to assign.
*/
constructor(initialValue = '') {
this.value = initialValue; // Disable reason: These are type hints on the class.
this.value = initialValue;
// Disable reason: These are type hints on the class.
/* eslint-disable no-unused-expressions */
/** @type {string} */
this._currentValue;
/** @type {string[]} */
/** @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);
}
/**
* Returns the associated set as string.
*
@@ -89,11 +85,10 @@ class TokenList {
*
* @return {string} Token set as string.
*/
get value() {
return this._currentValue;
}
/**
* Replaces the associated set with a new string value.
*
@@ -101,13 +96,12 @@ class TokenList {
*
* @param {string} value New token set as string.
*/
set value(value) {
value = String(value);
this._valueAsArray = [...new Set(value.split(/\s+/g).filter(Boolean))];
this._currentValue = this._valueAsArray.join(' ');
}
/**
* Returns the number of tokens.
*
@@ -115,11 +109,10 @@ class TokenList {
*
* @return {number} Number of tokens.
*/
get length() {
return this._valueAsArray.length;
}
/**
* Returns the stringified form of the TokenList.
*
@@ -128,11 +121,10 @@ class TokenList {
*
* @return {string} Token set as string.
*/
toString() {
return this.value;
}
/**
* Returns an iterator for the TokenList, iterating items of the set.
*
@@ -140,11 +132,10 @@ class TokenList {
*
* @return {IterableIterator<string>} TokenList iterator.
*/
*[Symbol.iterator]() {
return yield* this._valueAsArray;
}
/**
* Returns the token with index `index`.
*
@@ -154,11 +145,10 @@ class TokenList {
*
* @return {string|undefined} Token at index.
*/
item(index) {
return this._valueAsArray[index];
}
/**
* Returns true if `token` is present, and false otherwise.
*
@@ -168,11 +158,10 @@ class TokenList {
*
* @return {boolean} Whether token is present.
*/
contains(item) {
return this._valueAsArray.indexOf(item) !== -1;
}
/**
* Adds all arguments passed, except those already present.
*
@@ -180,11 +169,10 @@ class TokenList {
*
* @param {...string} items Items to add.
*/
add(...items) {
this.value += ' ' + items.join(' ');
}
/**
* Removes arguments passed, if they are present.
*
@@ -192,11 +180,10 @@ class TokenList {
*
* @param {...string} items Items to remove.
*/
remove(...items) {
this.value = this._valueAsArray.filter(val => !items.includes(val)).join(' ');
}
/**
* If `force` is not given, "toggles" `token`, removing it if its present
* and adding it if its not present. If `force` is true, adds token (same
@@ -210,21 +197,18 @@ class TokenList {
*
* @return {boolean} Whether token is present after toggle.
*/
toggle(token, force) {
if (undefined === force) {
force = !this.contains(token);
}
if (force) {
this.add(token);
} else {
this.remove(token);
}
return force;
}
/**
* Replaces `token` with `newToken`. Returns true if `token` was replaced
* with `newToken`, and false otherwise.
@@ -236,17 +220,15 @@ class TokenList {
*
* @return {boolean} Whether replacement occurred.
*/
replace(token, newToken) {
if (!this.contains(token)) {
return false;
}
this.remove(token);
this.add(newToken);
return true;
}
/**
* Returns true if `token` is in the associated attributes supported
* tokens. Returns false otherwise.
@@ -257,12 +239,9 @@ class TokenList {
*
* @return {boolean} Whether token is supported.
*/
supports() {
return true;
}
}
(window.wp = window.wp || {}).tokenList = __webpack_exports__["default"];
+263
View File
@@ -0,0 +1,263 @@
/******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 9127:
/***/ (function(module) {
module.exports = window["wp"]["isShallowEqual"];
/***/ })
/******/ });
/************************************************************************/
/******/ // 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/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
!function() {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ createUndoManager: function() { return /* binding */ createUndoManager; }
/* harmony export */ });
/* harmony import */ var _wordpress_is_shallow_equal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9127);
/* harmony import */ var _wordpress_is_shallow_equal__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_is_shallow_equal__WEBPACK_IMPORTED_MODULE_0__);
/**
* WordPress dependencies
*/
/** @typedef {import('./types').HistoryRecord} HistoryRecord */
/** @typedef {import('./types').HistoryChange} HistoryChange */
/** @typedef {import('./types').HistoryChanges} HistoryChanges */
/** @typedef {import('./types').UndoManager} UndoManager */
/**
* Merge changes for a single item into a record of changes.
*
* @param {Record< string, HistoryChange >} changes1 Previous changes
* @param {Record< string, HistoryChange >} changes2 NextChanges
*
* @return {Record< string, HistoryChange >} Merged changes
*/
function mergeHistoryChanges(changes1, changes2) {
/**
* @type {Record< string, HistoryChange >}
*/
const newChanges = {
...changes1
};
Object.entries(changes2).forEach(([key, value]) => {
if (newChanges[key]) {
newChanges[key] = {
...newChanges[key],
to: value.to
};
} else {
newChanges[key] = value;
}
});
return newChanges;
}
/**
* Adds history changes for a single item into a record of changes.
*
* @param {HistoryRecord} record The record to merge into.
* @param {HistoryChanges} changes The changes to merge.
*/
const addHistoryChangesIntoRecord = (record, changes) => {
const existingChangesIndex = record?.findIndex(({
id: recordIdentifier
}) => {
return typeof recordIdentifier === 'string' ? recordIdentifier === changes.id : _wordpress_is_shallow_equal__WEBPACK_IMPORTED_MODULE_0___default()(recordIdentifier, changes.id);
});
const nextRecord = [...record];
if (existingChangesIndex !== -1) {
// If the edit is already in the stack leave the initial "from" value.
nextRecord[existingChangesIndex] = {
id: changes.id,
changes: mergeHistoryChanges(nextRecord[existingChangesIndex].changes, changes.changes)
};
} else {
nextRecord.push(changes);
}
return nextRecord;
};
/**
* Creates an undo manager.
*
* @return {UndoManager} Undo manager.
*/
function createUndoManager() {
/**
* @type {HistoryRecord[]}
*/
let history = [];
/**
* @type {HistoryRecord}
*/
let stagedRecord = [];
/**
* @type {number}
*/
let offset = 0;
const dropPendingRedos = () => {
history = history.slice(0, offset || undefined);
offset = 0;
};
const appendStagedRecordToLatestHistoryRecord = () => {
var _history$index;
const index = history.length === 0 ? 0 : history.length - 1;
let latestRecord = (_history$index = history[index]) !== null && _history$index !== void 0 ? _history$index : [];
stagedRecord.forEach(changes => {
latestRecord = addHistoryChangesIntoRecord(latestRecord, changes);
});
stagedRecord = [];
history[index] = latestRecord;
};
/**
* Checks whether a record is empty.
* A record is considered empty if it the changes keep the same values.
* Also updates to function values are ignored.
*
* @param {HistoryRecord} record
* @return {boolean} Whether the record is empty.
*/
const isRecordEmpty = record => {
const filteredRecord = record.filter(({
changes
}) => {
return Object.values(changes).some(({
from,
to
}) => typeof from !== 'function' && typeof to !== 'function' && !_wordpress_is_shallow_equal__WEBPACK_IMPORTED_MODULE_0___default()(from, to));
});
return !filteredRecord.length;
};
return {
/**
* Record changes into the history.
*
* @param {HistoryRecord=} record A record of changes to record.
* @param {boolean} isStaged Whether to immediately create an undo point or not.
*/
addRecord(record, isStaged = false) {
const isEmpty = !record || isRecordEmpty(record);
if (isStaged) {
if (isEmpty) {
return;
}
record.forEach(changes => {
stagedRecord = addHistoryChangesIntoRecord(stagedRecord, changes);
});
} else {
dropPendingRedos();
if (stagedRecord.length) {
appendStagedRecordToLatestHistoryRecord();
}
if (isEmpty) {
return;
}
history.push(record);
}
},
undo() {
if (stagedRecord.length) {
dropPendingRedos();
appendStagedRecordToLatestHistoryRecord();
}
const undoRecord = history[history.length - 1 + offset];
if (!undoRecord) {
return;
}
offset -= 1;
return undoRecord;
},
redo() {
const redoRecord = history[history.length + offset];
if (!redoRecord) {
return;
}
offset += 1;
return redoRecord;
},
hasUndo() {
return !!history[history.length - 1 + offset];
},
hasRedo() {
return !!history[history.length + offset];
}
};
}
}();
(window.wp = window.wp || {}).undoManager = __webpack_exports__;
/******/ })()
;
+2
View File
@@ -0,0 +1,2 @@
/*! This file is auto-generated */
!function(){"use strict";var n={9127:function(n){n.exports=window.wp.isShallowEqual}},e={};function t(r){var o=e[r];if(void 0!==o)return o.exports;var u=e[r]={exports:{}};return n[r](u,u.exports,t),u.exports}t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,{a:e}),e},t.d=function(n,e){for(var r in e)t.o(e,r)&&!t.o(n,r)&&Object.defineProperty(n,r,{enumerable:!0,get:e[r]})},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})};var r={};!function(){t.r(r),t.d(r,{createUndoManager:function(){return i}});var n=t(9127),e=t.n(n);function o(n,e){const t={...n};return Object.entries(e).forEach((([n,e])=>{t[n]?t[n]={...t[n],to:e.to}:t[n]=e})),t}const u=(n,t)=>{const r=n?.findIndex((({id:n})=>"string"==typeof n?n===t.id:e()(n,t.id))),u=[...n];return-1!==r?u[r]={id:t.id,changes:o(u[r].changes,t.changes)}:u.push(t),u};function i(){let n=[],t=[],r=0;const o=()=>{n=n.slice(0,r||void 0),r=0},i=()=>{var e;const r=0===n.length?0:n.length-1;let o=null!==(e=n[r])&&void 0!==e?e:[];t.forEach((n=>{o=u(o,n)})),t=[],n[r]=o};return{addRecord(r,c=!1){const f=!r||(n=>!n.filter((({changes:n})=>Object.values(n).some((({from:n,to:t})=>"function"!=typeof n&&"function"!=typeof t&&!e()(n,t))))).length)(r);if(c){if(f)return;r.forEach((n=>{t=u(t,n)}))}else{if(o(),t.length&&i(),f)return;n.push(r)}},undo(){t.length&&(o(),i());const e=n[n.length-1+r];if(e)return r-=1,e},redo(){const e=n[n.length+r];if(e)return r+=1,e},hasUndo(){return!!n[n.length-1+r]},hasRedo(){return!!n[n.length+r]}}}}(),(window.wp=window.wp||{}).undoManager=r}();
+152 -113
View File
@@ -20,6 +20,11 @@ var characterMap = {
"Ầ": "A",
"Ằ": "A",
"Ȃ": "A",
"Ả": "A",
"Ạ": "A",
"Ẩ": "A",
"Ẫ": "A",
"Ậ": "A",
"Ç": "C",
"Ḉ": "C",
"È": "E",
@@ -32,12 +37,20 @@ var characterMap = {
"Ḕ": "E",
"Ḝ": "E",
"Ȇ": "E",
"Ẻ": "E",
"Ẽ": "E",
"Ẹ": "E",
"Ể": "E",
"Ễ": "E",
"Ệ": "E",
"Ì": "I",
"Í": "I",
"Î": "I",
"Ï": "I",
"Ḯ": "I",
"Ȋ": "I",
"Ỉ": "I",
"Ị": "I",
"Ð": "D",
"Ñ": "N",
"Ò": "O",
@@ -50,10 +63,25 @@ var characterMap = {
"Ṍ": "O",
"Ṓ": "O",
"Ȏ": "O",
"Ỏ": "O",
"Ọ": "O",
"Ổ": "O",
"Ỗ": "O",
"Ộ": "O",
"Ờ": "O",
"Ở": "O",
"Ỡ": "O",
"Ớ": "O",
"Ợ": "O",
"Ù": "U",
"Ú": "U",
"Û": "U",
"Ü": "U",
"Ủ": "U",
"Ụ": "U",
"Ử": "U",
"Ữ": "U",
"Ự": "U",
"Ý": "Y",
"à": "a",
"á": "a",
@@ -70,6 +98,11 @@ var characterMap = {
"ầ": "a",
"ằ": "a",
"ȃ": "a",
"ả": "a",
"ạ": "a",
"ẩ": "a",
"ẫ": "a",
"ậ": "a",
"ç": "c",
"ḉ": "c",
"è": "e",
@@ -82,12 +115,20 @@ var characterMap = {
"ḕ": "e",
"ḝ": "e",
"ȇ": "e",
"ẻ": "e",
"ẽ": "e",
"ẹ": "e",
"ể": "e",
"ễ": "e",
"ệ": "e",
"ì": "i",
"í": "i",
"î": "i",
"ï": "i",
"ḯ": "i",
"ȋ": "i",
"ỉ": "i",
"ị": "i",
"ð": "d",
"ñ": "n",
"ò": "o",
@@ -100,10 +141,25 @@ var characterMap = {
"ṍ": "o",
"ṓ": "o",
"ȏ": "o",
"ỏ": "o",
"ọ": "o",
"ổ": "o",
"ỗ": "o",
"ộ": "o",
"ờ": "o",
"ở": "o",
"ỡ": "o",
"ớ": "o",
"ợ": "o",
"ù": "u",
"ú": "u",
"û": "u",
"ü": "u",
"ủ": "u",
"ụ": "u",
"ử": "u",
"ữ": "u",
"ự": "u",
"ý": "y",
"ÿ": "y",
"Ā": "A",
@@ -225,7 +281,6 @@ var characterMap = {
"ş": "s",
"Š": "S",
"š": "s",
"ß": "ss",
"Ţ": "T",
"ţ": "t",
"ț": "t",
@@ -419,7 +474,7 @@ function matcher(match) {
return characterMap[match];
}
var removeAccents = function(string) {
var removeAccents = function(string) {
return string.replace(allAccents, matcher);
};
@@ -511,33 +566,33 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"addQueryArgs": function() { return /* reexport */ addQueryArgs; },
"buildQueryString": function() { return /* reexport */ buildQueryString; },
"cleanForSlug": function() { return /* reexport */ cleanForSlug; },
"filterURLForDisplay": function() { return /* reexport */ filterURLForDisplay; },
"getAuthority": function() { return /* reexport */ getAuthority; },
"getFilename": function() { return /* reexport */ getFilename; },
"getFragment": function() { return /* reexport */ getFragment; },
"getPath": function() { return /* reexport */ getPath; },
"getPathAndQueryString": function() { return /* reexport */ getPathAndQueryString; },
"getProtocol": function() { return /* reexport */ getProtocol; },
"getQueryArg": function() { return /* reexport */ getQueryArg; },
"getQueryArgs": function() { return /* reexport */ getQueryArgs; },
"getQueryString": function() { return /* reexport */ getQueryString; },
"hasQueryArg": function() { return /* reexport */ hasQueryArg; },
"isEmail": function() { return /* reexport */ isEmail; },
"isURL": function() { return /* reexport */ isURL; },
"isValidAuthority": function() { return /* reexport */ isValidAuthority; },
"isValidFragment": function() { return /* reexport */ isValidFragment; },
"isValidPath": function() { return /* reexport */ isValidPath; },
"isValidProtocol": function() { return /* reexport */ isValidProtocol; },
"isValidQueryString": function() { return /* reexport */ isValidQueryString; },
"normalizePath": function() { return /* reexport */ normalizePath; },
"prependHTTP": function() { return /* reexport */ prependHTTP; },
"prependHTTPS": function() { return /* reexport */ prependHTTPS; },
"removeQueryArgs": function() { return /* reexport */ removeQueryArgs; },
"safeDecodeURI": function() { return /* reexport */ safeDecodeURI; },
"safeDecodeURIComponent": function() { return /* reexport */ safeDecodeURIComponent; }
addQueryArgs: function() { return /* reexport */ addQueryArgs; },
buildQueryString: function() { return /* reexport */ buildQueryString; },
cleanForSlug: function() { return /* reexport */ cleanForSlug; },
filterURLForDisplay: function() { return /* reexport */ filterURLForDisplay; },
getAuthority: function() { return /* reexport */ getAuthority; },
getFilename: function() { return /* reexport */ getFilename; },
getFragment: function() { return /* reexport */ getFragment; },
getPath: function() { return /* reexport */ getPath; },
getPathAndQueryString: function() { return /* reexport */ getPathAndQueryString; },
getProtocol: function() { return /* reexport */ getProtocol; },
getQueryArg: function() { return /* reexport */ getQueryArg; },
getQueryArgs: function() { return /* reexport */ getQueryArgs; },
getQueryString: function() { return /* reexport */ getQueryString; },
hasQueryArg: function() { return /* reexport */ hasQueryArg; },
isEmail: function() { return /* reexport */ isEmail; },
isURL: function() { return /* reexport */ isURL; },
isValidAuthority: function() { return /* reexport */ isValidAuthority; },
isValidFragment: function() { return /* reexport */ isValidFragment; },
isValidPath: function() { return /* reexport */ isValidPath; },
isValidProtocol: function() { return /* reexport */ isValidProtocol; },
isValidQueryString: function() { return /* reexport */ isValidQueryString; },
normalizePath: function() { return /* reexport */ normalizePath; },
prependHTTP: function() { return /* reexport */ prependHTTP; },
prependHTTPS: function() { return /* reexport */ prependHTTPS; },
removeQueryArgs: function() { return /* reexport */ removeQueryArgs; },
safeDecodeURI: function() { return /* reexport */ safeDecodeURI; },
safeDecodeURIComponent: function() { return /* reexport */ safeDecodeURIComponent; }
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-url.js
@@ -569,6 +624,7 @@ function isURL(url) {
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-email.js
const EMAIL_REGEXP = /^(mailto:)?[a-z0-9._%+-]+@[a-z0-9][a-z0-9.-]*\.[a-z]{2,63}$/i;
/**
* Determines whether the given string looks like an email.
*
@@ -581,7 +637,6 @@ const EMAIL_REGEXP = /^(mailto:)?[a-z0-9._%+-]+@[a-z0-9][a-z0-9.-]*\.[a-z]{2,63}
*
* @return {boolean} Whether or not it looks like an email.
*/
function isEmail(email) {
return EMAIL_REGEXP.test(email);
}
@@ -602,7 +657,6 @@ function isEmail(email) {
*/
function getProtocol(url) {
const matches = /^([^\s:]+:)/.exec(url);
if (matches) {
return matches[1];
}
@@ -626,7 +680,6 @@ function isValidProtocol(protocol) {
if (!protocol) {
return false;
}
return /^[a-z\-.\+]+[0-9]*:$/i.test(protocol);
}
@@ -646,7 +699,6 @@ function isValidProtocol(protocol) {
*/
function getAuthority(url) {
const matches = /^[^\/\s:]+:(?:\/\/)?\/?([^\/\s#?]+)[\/#?]{0,1}\S*$/.exec(url);
if (matches) {
return matches[1];
}
@@ -670,7 +722,6 @@ function isValidAuthority(authority) {
if (!authority) {
return false;
}
return /^[^\s#?]+$/.test(authority);
}
@@ -690,7 +741,6 @@ function isValidAuthority(authority) {
*/
function getPath(url) {
const matches = /^[^\/\s:]+:(?:\/\/)?[^\/\s#?]+[\/]([^\s#?]+)[#?]{0,1}\S*$/.exec(url);
if (matches) {
return matches[1];
}
@@ -714,7 +764,6 @@ function isValidPath(path) {
if (!path) {
return false;
}
return /^[^\s#?]+$/.test(path);
}
@@ -733,11 +782,9 @@ function isValidPath(path) {
*/
function getQueryString(url) {
let query;
try {
query = new URL(url, 'http://example.com').search.substring(1);
} catch (error) {}
if (query) {
return query;
}
@@ -772,18 +819,16 @@ function buildQueryString(data) {
let string = '';
const stack = Object.entries(data);
let pair;
while (pair = stack.shift()) {
let [key, value] = pair; // Support building deeply nested data, from array or object values.
let [key, value] = pair;
// Support building deeply nested data, from array or object values.
const hasNestedData = Array.isArray(value) || value && value.constructor === Object;
if (hasNestedData) {
// Push array or object values onto the stack as composed of their
// original key and nested index or key, retaining order by a
// combination of Array#reverse and Array#unshift onto the stack.
const valuePairs = Object.entries(value).reverse();
for (const [member, memberValue] of valuePairs) {
stack.unshift([`${key}[${member}]`, memberValue]);
}
@@ -792,14 +837,13 @@ function buildQueryString(data) {
if (value === null) {
value = '';
}
string += '&' + [key, value].map(encodeURIComponent).join('=');
}
} // Loop will concatenate with leading `&`, but it's only expected for all
}
// Loop will concatenate with leading `&`, but it's only expected for all
// but the first query parameter. This strips the leading `&`, while still
// accounting for the case that the string may in-fact be empty.
return string.substr(1);
}
@@ -821,7 +865,6 @@ function isValidQueryString(queryString) {
if (!queryString) {
return false;
}
return /^[^\s#?\/]+$/.test(queryString);
}
@@ -830,6 +873,7 @@ function isValidQueryString(queryString) {
* Internal dependencies
*/
/**
* Returns the path part and query string part of the URL.
*
@@ -843,7 +887,6 @@ function isValidQueryString(queryString) {
*
* @return {string} The path part and query string part of the URL.
*/
function getPathAndQueryString(url) {
const path = getPath(url);
const queryString = getQueryString(url);
@@ -869,7 +912,6 @@ function getPathAndQueryString(url) {
*/
function getFragment(url) {
const matches = /^\S+?(#[^\s\?]*)/.exec(url);
if (matches) {
return matches[1];
}
@@ -893,7 +935,6 @@ function isValidFragment(fragment) {
if (!fragment) {
return false;
}
return /^#[^\s#?\/]*$/.test(fragment);
}
@@ -920,6 +961,7 @@ function safeDecodeURIComponent(uriComponent) {
*/
/** @typedef {import('./get-query-arg').QueryArgParsed} QueryArgParsed */
/**
@@ -934,40 +976,40 @@ function safeDecodeURIComponent(uriComponent) {
* @param {string[]} path Path segment at which to set value.
* @param {*} value Value to set.
*/
function setPath(object, path, value) {
const length = path.length;
const lastIndex = length - 1;
for (let i = 0; i < length; i++) {
let key = path[i];
if (!key && Array.isArray(object)) {
// If key is empty string and next value is array, derive key from
// the current length of the array.
key = object.length.toString();
}
key = ['__proto__', 'constructor', 'prototype'].includes(key) ? key.toUpperCase() : key;
key = ['__proto__', 'constructor', 'prototype'].includes(key) ? key.toUpperCase() : key; // If the next key in the path is numeric (or empty string), it will be
// If the next key in the path is numeric (or empty string), it will be
// created as an array. Otherwise, it will be created as an object.
const isNextKeyArrayIndex = !isNaN(Number(path[i + 1]));
object[key] = i === lastIndex ? // If at end of path, assign the intended value.
value : // Otherwise, advance to the next object in the path, creating
object[key] = i === lastIndex ?
// If at end of path, assign the intended value.
value :
// Otherwise, advance to the next object in the path, creating
// it if it does not yet exist.
object[key] || (isNextKeyArrayIndex ? [] : {});
if (Array.isArray(object[key]) && !isNextKeyArrayIndex) {
// If we current key is non-numeric, but the next value is an
// array, coerce the value to an object.
object[key] = { ...object[key]
object[key] = {
...object[key]
};
} // Update working reference object to the next in the path.
}
// Update working reference object to the next in the path.
object = object[key];
}
}
/**
* Returns an object of query arguments of the given URL. If the given URL is
* invalid or has no querystring, an empty object is returned.
@@ -982,23 +1024,21 @@ function setPath(object, path, value) {
*
* @return {QueryArgs} Query args object.
*/
function getQueryArgs(url) {
return (getQueryString(url) || '' // Normalize space encoding, accounting for PHP URL encoding
return (getQueryString(url) || ''
// Normalize space encoding, accounting for PHP URL encoding
// corresponding to `application/x-www-form-urlencoded`.
//
// See: https://tools.ietf.org/html/rfc1866#section-8.2.1
).replace(/\+/g, '%20').split('&').reduce((accumulator, keyValue) => {
const [key, value = ''] = keyValue.split('=') // Filtering avoids decoding as `undefined` for value, where
const [key, value = ''] = keyValue.split('=')
// Filtering avoids decoding as `undefined` for value, where
// default is restored in destructuring assignment.
.filter(Boolean).map(safeDecodeURIComponent);
if (key) {
const segments = key.replace(/\]/g, '').split('[');
setPath(accumulator, segments, value);
}
return accumulator;
}, Object.create(null));
}
@@ -1009,6 +1049,7 @@ function getQueryArgs(url) {
*/
/**
* Appends arguments as querystring to the provided URL. If the URL already
* includes query arguments, the arguments are merged with (and take precedent
@@ -1025,24 +1066,22 @@ function getQueryArgs(url) {
*
* @return {string} URL with arguments applied.
*/
function addQueryArgs(url = '', args) {
// If no arguments are to be appended, return original URL.
if (!args || !Object.keys(args).length) {
return url;
}
let baseUrl = url;
let baseUrl = url; // Determine whether URL already had query arguments.
// Determine whether URL already had query arguments.
const queryStringIndex = url.indexOf('?');
if (queryStringIndex !== -1) {
// Merge into existing query arguments.
args = Object.assign(getQueryArgs(url), args); // Change working base URL to omit previous query arguments.
args = Object.assign(getQueryArgs(url), args);
// Change working base URL to omit previous query arguments.
baseUrl = baseUrl.substr(0, queryStringIndex);
}
return baseUrl + '?' + buildQueryString(args);
}
@@ -1051,6 +1090,7 @@ function addQueryArgs(url = '', args) {
* Internal dependencies
*/
/**
* @typedef {{[key: string]: QueryArgParsed}} QueryArgObject
*/
@@ -1072,7 +1112,6 @@ function addQueryArgs(url = '', args) {
*
* @return {QueryArgParsed|void} Query arg value.
*/
function getQueryArg(url, arg) {
return getQueryArgs(url)[arg];
}
@@ -1082,6 +1121,7 @@ function getQueryArg(url, arg) {
* Internal dependencies
*/
/**
* Determines whether the URL contains a given query arg.
*
@@ -1095,7 +1135,6 @@ function getQueryArg(url, arg) {
*
* @return {boolean} Whether or not the URL contains the query arg.
*/
function hasQueryArg(url, arg) {
return getQueryArg(url, arg) !== undefined;
}
@@ -1106,6 +1145,7 @@ function hasQueryArg(url, arg) {
*/
/**
* Removes arguments from the query string of the url
*
@@ -1119,14 +1159,11 @@ function hasQueryArg(url, arg) {
*
* @return {string} Updated URL.
*/
function removeQueryArgs(url, ...args) {
const queryStringIndex = url.indexOf('?');
if (queryStringIndex === -1) {
return url;
}
const query = getQueryArgs(url);
const baseURL = url.substr(0, queryStringIndex);
args.forEach(arg => delete query[arg]);
@@ -1140,6 +1177,7 @@ function removeQueryArgs(url, ...args) {
*/
const USABLE_HREF_REGEXP = /^(?:[a-z]+:|#|\?|\.|\/)/i;
/**
* Prepends "http://" to a url, if it looks like something that is meant to be a TLD.
*
@@ -1152,18 +1190,14 @@ const USABLE_HREF_REGEXP = /^(?:[a-z]+:|#|\?|\.|\/)/i;
*
* @return {string} The updated URL.
*/
function prependHTTP(url) {
if (!url) {
return url;
}
url = url.trim();
if (!USABLE_HREF_REGEXP.test(url) && !isEmail(url)) {
return 'http://' + url;
}
return url;
}
@@ -1206,28 +1240,26 @@ function safeDecodeURI(uri) {
*/
function filterURLForDisplay(url, maxLength = null) {
// Remove protocol and www prefixes.
let filteredURL = url.replace(/^(?:https?:)\/\/(?:www\.)?/, ''); // Ends with / and only has that single slash, strip it.
let filteredURL = url.replace(/^(?:https?:)\/\/(?:www\.)?/, '');
// Ends with / and only has that single slash, strip it.
if (filteredURL.match(/^[^\/]+\/$/)) {
filteredURL = filteredURL.replace('/', '');
}
const mediaRegexp = /([\w|:])*\.(?:jpg|jpeg|gif|png|svg)/;
if (!maxLength || filteredURL.length <= maxLength || !filteredURL.match(mediaRegexp)) {
return filteredURL;
} // If the file is not greater than max length, return last portion of URL.
}
// If the file is not greater than max length, return last portion of URL.
filteredURL = filteredURL.split('?')[0];
const urlPieces = filteredURL.split('/');
const file = urlPieces[urlPieces.length - 1];
if (file.length <= maxLength) {
return '…' + filteredURL.slice(-maxLength);
} // If the file is greater than max length, truncate the file.
}
// If the file is greater than max length, truncate the file.
const index = file.lastIndexOf('.');
const [fileName, extension] = [file.slice(0, index), file.slice(index + 1)];
const truncatedFile = fileName.slice(-3) + '.' + extension;
@@ -1242,6 +1274,7 @@ var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
* External dependencies
*/
/**
* Performs some basic cleanup of a string for use as a post slug.
*
@@ -1258,17 +1291,20 @@ var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
*
* @return {string} Processed string.
*/
function cleanForSlug(string) {
if (!string) {
return '';
}
return remove_accents_default()(string) // Convert each group of whitespace, periods, and forward slashes to a hyphen.
.replace(/[\s\./]+/g, '-') // Remove anything that's not a letter, number, underscore or hyphen.
.replace(/[^\p{L}\p{N}_-]+/gu, '') // Convert to lowercase
.toLowerCase() // Replace multiple hyphens with a single one.
.replace(/-+/g, '-') // Remove any remaining leading or trailing hyphens.
return remove_accents_default()(string)
// Convert each group of whitespace, periods, and forward slashes to a hyphen.
.replace(/[\s\./]+/g, '-')
// Remove anything that's not a letter, number, underscore or hyphen.
.replace(/[^\p{L}\p{N}_-]+/gu, '')
// Convert to lowercase
.toLowerCase()
// Replace multiple hyphens with a single one.
.replace(/-+/g, '-')
// Remove any remaining leading or trailing hyphens.
.replace(/(^-+)|(-+$)/g, '');
}
@@ -1288,11 +1324,9 @@ function cleanForSlug(string) {
*/
function getFilename(url) {
let filename;
try {
filename = new URL(url, 'http://example.com').pathname.split('/').pop();
} catch (error) {}
if (filename) {
return filename;
}
@@ -1312,19 +1346,25 @@ function normalizePath(path) {
const splitted = path.split('?');
const query = splitted[1];
const base = splitted[0];
if (!query) {
return base;
} // 'b=1%2C2&c=2&a=5'
}
return base + '?' + query // [ 'b=1%2C2', 'c=2', 'a=5' ]
.split('&') // [ [ 'b, '1%2C2' ], [ 'c', '2' ], [ 'a', '5' ] ]
.map(entry => entry.split('=')) // [ [ 'b', '1,2' ], [ 'c', '2' ], [ 'a', '5' ] ]
.map(pair => pair.map(decodeURIComponent)) // [ [ 'a', '5' ], [ 'b, '1,2' ], [ 'c', '2' ] ]
.sort((a, b) => a[0].localeCompare(b[0])) // [ [ 'a', '5' ], [ 'b, '1%2C2' ], [ 'c', '2' ] ]
.map(pair => pair.map(encodeURIComponent)) // [ 'a=5', 'b=1%2C2', 'c=2' ]
.map(pair => pair.join('=')) // 'a=5&b=1%2C2&c=2'
// 'b=1%2C2&c=2&a=5'
return base + '?' + query
// [ 'b=1%2C2', 'c=2', 'a=5' ]
.split('&')
// [ [ 'b, '1%2C2' ], [ 'c', '2' ], [ 'a', '5' ] ]
.map(entry => entry.split('='))
// [ [ 'b', '1,2' ], [ 'c', '2' ], [ 'a', '5' ] ]
.map(pair => pair.map(decodeURIComponent))
// [ [ 'a', '5' ], [ 'b, '1,2' ], [ 'c', '2' ] ]
.sort((a, b) => a[0].localeCompare(b[0]))
// [ [ 'a', '5' ], [ 'b, '1%2C2' ], [ 'c', '2' ] ]
.map(pair => pair.map(encodeURIComponent))
// [ 'a=5', 'b=1%2C2', 'c=2' ]
.map(pair => pair.join('='))
// 'a=5&b=1%2C2&c=2'
.join('&');
}
@@ -1333,6 +1373,7 @@ function normalizePath(path) {
* Internal dependencies
*/
/**
* Prepends "https://" to a url, if it looks like something that is meant to be a TLD.
*
@@ -1347,17 +1388,15 @@ function normalizePath(path) {
*
* @return {string} The updated URL.
*/
function prependHTTPS(url) {
if (!url) {
return url;
} // If url starts with http://, return it as is.
}
// If url starts with http://, return it as is.
if (url.startsWith('http://')) {
return url;
}
url = prependHTTP(url);
return url.replace(/^http:/, 'https:');
}
+1 -1
View File
File diff suppressed because one or more lines are too long
+2 -3
View File
@@ -487,7 +487,7 @@ var runtime = (function (exports) {
};
function values(iterable) {
if (iterable) {
if (iterable || iterable === "") {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
@@ -517,8 +517,7 @@ var runtime = (function (exports) {
}
}
// Return an iterator with no values.
return { next: doneResult };
throw new TypeError(typeof iterable + " is not iterable");
}
exports.values = values;
File diff suppressed because one or more lines are too long
+75 -45
View File
@@ -4,17 +4,20 @@
(factory((global.WHATWGFetch = {})));
}(this, (function (exports) { 'use strict';
var global =
/* eslint-disable no-prototype-builtins */
var g =
(typeof globalThis !== 'undefined' && globalThis) ||
(typeof self !== 'undefined' && self) ||
(typeof global !== 'undefined' && global);
// eslint-disable-next-line no-undef
(typeof global !== 'undefined' && global) ||
{};
var support = {
searchParams: 'URLSearchParams' in global,
iterable: 'Symbol' in global && 'iterator' in Symbol,
searchParams: 'URLSearchParams' in g,
iterable: 'Symbol' in g && 'iterator' in Symbol,
blob:
'FileReader' in global &&
'Blob' in global &&
'FileReader' in g &&
'Blob' in g &&
(function() {
try {
new Blob();
@@ -23,8 +26,8 @@
return false
}
})(),
formData: 'FormData' in global,
arrayBuffer: 'ArrayBuffer' in global
formData: 'FormData' in g,
arrayBuffer: 'ArrayBuffer' in g
};
function isDataView(obj) {
@@ -95,6 +98,9 @@
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
if (header.length != 2) {
throw new TypeError('Headers constructor: expected name/value pair to be length 2, found' + header.length)
}
this.append(header[0], header[1]);
}, this);
} else if (headers) {
@@ -165,6 +171,7 @@
}
function consumed(body) {
if (body._noBody) return
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
@@ -192,7 +199,9 @@
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type);
var encoding = match ? match[1] : 'utf-8';
reader.readAsText(blob, encoding);
return promise
}
@@ -230,9 +239,11 @@
semantic of setting Request.bodyUsed in the constructor before
_initBody is called.
*/
// eslint-disable-next-line no-self-assign
this.bodyUsed = this.bodyUsed;
this._bodyInit = body;
if (!body) {
this._noBody = true;
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
@@ -280,29 +291,30 @@
return Promise.resolve(new Blob([this._bodyText]))
}
};
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
var isConsumed = consumed(this);
if (isConsumed) {
return isConsumed
}
if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
return Promise.resolve(
this._bodyArrayBuffer.buffer.slice(
this._bodyArrayBuffer.byteOffset,
this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
)
)
} else {
return Promise.resolve(this._bodyArrayBuffer)
}
} else {
return this.blob().then(readBlobAsArrayBuffer)
}
};
}
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
var isConsumed = consumed(this);
if (isConsumed) {
return isConsumed
} else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
return Promise.resolve(
this._bodyArrayBuffer.buffer.slice(
this._bodyArrayBuffer.byteOffset,
this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
)
)
} else {
return Promise.resolve(this._bodyArrayBuffer)
}
} else if (support.blob) {
return this.blob().then(readBlobAsArrayBuffer)
} else {
throw new Error('could not read as ArrayBuffer')
}
};
this.text = function() {
var rejected = consumed(this);
if (rejected) {
@@ -334,7 +346,7 @@
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
var methods = ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE'];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
@@ -375,7 +387,12 @@
}
this.method = normalizeMethod(options.method || this.method || 'GET');
this.mode = options.mode || this.mode || null;
this.signal = options.signal || this.signal;
this.signal = options.signal || this.signal || (function () {
if ('AbortController' in g) {
var ctrl = new AbortController();
return ctrl.signal;
}
}());
this.referrer = null;
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
@@ -437,7 +454,11 @@
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
try {
headers.append(key, value);
} catch (error) {
console.warn('Response ' + error.message);
}
}
});
return headers
@@ -455,6 +476,9 @@
this.type = 'default';
this.status = options.status === undefined ? 200 : options.status;
if (this.status < 200 || this.status > 599) {
throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].")
}
this.ok = this.status >= 200 && this.status < 300;
this.statusText = options.statusText === undefined ? '' : '' + options.statusText;
this.headers = new Headers(options.headers);
@@ -474,7 +498,8 @@
};
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''});
var response = new Response(null, {status: 200, statusText: ''});
response.status = 0;
response.type = 'error';
return response
};
@@ -489,7 +514,7 @@
return new Response(null, {status: status, headers: {location: url}})
};
exports.DOMException = global.DOMException;
exports.DOMException = g.DOMException;
try {
new exports.DOMException();
} catch (err) {
@@ -550,7 +575,7 @@
function fixUrl(url) {
try {
return url === '' && global.location.href ? global.location.href : url
return url === '' && g.location.href ? g.location.href : url
} catch (e) {
return url
}
@@ -568,18 +593,23 @@
if (support.blob) {
xhr.responseType = 'blob';
} else if (
support.arrayBuffer &&
request.headers.get('Content-Type') &&
request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1
support.arrayBuffer
) {
xhr.responseType = 'arraybuffer';
}
}
if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) {
if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers || (g.Headers && init.headers instanceof g.Headers))) {
var names = [];
Object.getOwnPropertyNames(init.headers).forEach(function(name) {
names.push(normalizeName(name));
xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
});
request.headers.forEach(function(value, name) {
if (names.indexOf(name) === -1) {
xhr.setRequestHeader(name, value);
}
});
} else {
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
@@ -603,11 +633,11 @@
fetch.polyfill = true;
if (!global.fetch) {
global.fetch = fetch;
global.Headers = Headers;
global.Request = Request;
global.Response = Response;
if (!g.fetch) {
g.fetch = fetch;
g.Headers = Headers;
g.Request = Request;
g.Response = Response;
}
exports.Headers = Headers;
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+19 -29
View File
@@ -39,23 +39,23 @@ __webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"ifViewportMatches": function() { return /* reexport */ if_viewport_matches; },
"store": function() { return /* reexport */ store; },
"withViewportMatch": function() { return /* reexport */ with_viewport_match; }
ifViewportMatches: function() { return /* reexport */ if_viewport_matches; },
store: function() { return /* reexport */ store; },
withViewportMatch: function() { return /* reexport */ with_viewport_match; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/viewport/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"setIsMatching": function() { return setIsMatching; }
setIsMatching: function() { return setIsMatching; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/viewport/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"isViewportMatch": function() { return isViewportMatch; }
isViewportMatch: function() { return isViewportMatch; }
});
;// CONCATENATED MODULE: external ["wp","compose"]
@@ -77,10 +77,8 @@ function reducer(state = {}, action) {
case 'SET_IS_MATCHING':
return action.values;
}
return state;
}
/* harmony default export */ var store_reducer = (reducer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/viewport/build-module/store/actions.js
@@ -138,7 +136,6 @@ function isViewportMatch(state, query) {
if (query.indexOf(' ') === -1) {
query = '>= ' + query;
}
return !!state[query];
}
@@ -147,14 +144,15 @@ function isViewportMatch(state, query) {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const STORE_NAME = 'core/viewport';
/**
* Store definition for the viewport namespace.
*
@@ -162,7 +160,6 @@ const STORE_NAME = 'core/viewport';
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, {
reducer: store_reducer,
actions: actions_namespaceObject,
@@ -176,12 +173,11 @@ const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME,
*/
/**
* Internal dependencies
*/
const addDimensionsEventListener = (breakpoints, operators) => {
/**
* Callback invoked when media query state should be updated. Is invoked a
@@ -193,6 +189,7 @@ const addDimensionsEventListener = (breakpoints, operators) => {
}, 0, {
leading: true
});
/**
* Hash of breakpoint names with generated MediaQueryList for corresponding
* media query.
@@ -202,7 +199,6 @@ const addDimensionsEventListener = (breakpoints, operators) => {
*
* @type {Object<string,MediaQueryList>}
*/
const operatorEntries = Object.entries(operators);
const queries = Object.entries(breakpoints).flatMap(([name, width]) => {
return operatorEntries.map(([operator, condition]) => {
@@ -211,23 +207,23 @@ const addDimensionsEventListener = (breakpoints, operators) => {
return [`${operator} ${name}`, list];
});
});
window.addEventListener('orientationchange', setIsMatching); // Set initial values.
window.addEventListener('orientationchange', setIsMatching);
// Set initial values.
setIsMatching();
setIsMatching.flush();
};
/* harmony default export */ var listener = (addDimensionsEventListener);
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/viewport/build-module/with-viewport-match.js
/**
* WordPress dependencies
*/
/**
* Higher-order component creator, creating a new component which renders with
* the given prop names, where the value passed to the underlying component is
@@ -251,35 +247,30 @@ var external_wp_element_namespaceObject = window["wp"]["element"];
*
* @return {Function} Higher-order component.
*/
const withViewportMatch = queries => {
const queryEntries = Object.entries(queries);
const useViewPortQueriesResult = () => Object.fromEntries(queryEntries.map(([key, query]) => {
let [operator, breakpointName] = query.split(' ');
if (breakpointName === undefined) {
breakpointName = operator;
operator = '>=';
} // Hooks should unconditionally execute in the same order,
}
// Hooks should unconditionally execute in the same order,
// we are respecting that as from the static query of the HOC we generate
// a hook that calls other hooks always in the same order (because the query never changes).
// eslint-disable-next-line react-hooks/rules-of-hooks
return [key, (0,external_wp_compose_namespaceObject.useViewportMatch)(breakpointName, operator)];
}));
return (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => {
return (0,external_wp_compose_namespaceObject.pure)(props => {
const queriesResult = useViewPortQueriesResult();
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, { ...props,
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, {
...props,
...queriesResult
});
});
}, 'withViewportMatch');
};
/* harmony default export */ var with_viewport_match = (withViewportMatch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/viewport/build-module/if-viewport-matches.js
@@ -287,6 +278,7 @@ const withViewportMatch = queries => {
* WordPress dependencies
*/
/**
* Internal dependencies
*/
@@ -312,11 +304,9 @@ const withViewportMatch = queries => {
*
* @return {Function} Higher-order component.
*/
const ifViewportMatches = query => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)((0,external_wp_compose_namespaceObject.compose)([with_viewport_match({
isViewportMatch: query
}), (0,external_wp_compose_namespaceObject.ifCondition)(props => props.isViewportMatch)]), 'ifViewportMatches');
/* harmony default export */ var if_viewport_matches = (ifViewportMatches);
;// CONCATENATED MODULE: ./node_modules/@wordpress/viewport/build-module/index.js
@@ -327,6 +317,7 @@ const ifViewportMatches = query => (0,external_wp_compose_namespaceObject.create
/**
* Hash of breakpoint names with pixel width at which it becomes effective.
*
@@ -334,7 +325,6 @@ const ifViewportMatches = query => (0,external_wp_compose_namespaceObject.create
*
* @type {Object}
*/
const BREAKPOINTS = {
huge: 1440,
wide: 1280,
@@ -343,12 +333,12 @@ const BREAKPOINTS = {
small: 600,
mobile: 480
};
/**
* Hash of query operators with corresponding condition for media query.
*
* @type {Object}
*/
const OPERATORS = {
'<': 'max-width',
'>=': 'min-width'
+18 -19
View File
@@ -43,10 +43,10 @@ const logged = new Set();
* Internal dependencies
*/
function isDev() {
return typeof process !== 'undefined' && process.env && "production" !== 'production';
return true && true === true;
}
/**
* Shows a warning with `message` if environment is not `production`.
*
@@ -64,28 +64,27 @@ function isDev() {
* }
* ```
*/
function warning(message) {
if (!isDev()) {
return;
} // Skip if already logged.
if (logged.has(message)) {
return;
} // eslint-disable-next-line no-console
console.warn(message); // Throwing an error and catching it immediately to improve debugging
// A consumer can use 'pause on caught exceptions'
// https://github.com/facebook/react/issues/4216
try {
throw Error(message);
} catch (x) {// Do nothing.
}
// Skip if already logged.
if (logged.has(message)) {
return;
}
// eslint-disable-next-line no-console
console.warn(message);
// Throwing an error and catching it immediately to improve debugging
// A consumer can use 'pause on caught exceptions'
// https://github.com/facebook/react/issues/4216
try {
throw Error(message);
} catch (x) {
// Do nothing.
}
logged.add(message);
}
+1 -1
View File
@@ -1,2 +1,2 @@
/*! This file is auto-generated */
!function(){"use strict";var e={d:function(n,t){for(var o in t)e.o(t,o)&&!e.o(n,o)&&Object.defineProperty(n,o,{enumerable:!0,get:t[o]})},o:function(e,n){return Object.prototype.hasOwnProperty.call(e,n)}},n={};e.d(n,{default:function(){return t}});new Set;function t(e){"undefined"!=typeof process&&process.env}(window.wp=window.wp||{}).warning=n.default}();
!function(){"use strict";var n={d:function(t,e){for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},o:function(n,t){return Object.prototype.hasOwnProperty.call(n,t)}},t={};n.d(t,{default:function(){return e}});new Set;function e(n){}(window.wp=window.wp||{}).warning=t.default}();

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